Skip to content

[SOLUTION] Add gateway auth middleware tests for $50 bounty#37

Open
feezy1357 wants to merge 2 commits into
jackjin1997:mainfrom
feezy1357:main
Open

[SOLUTION] Add gateway auth middleware tests for $50 bounty#37
feezy1357 wants to merge 2 commits into
jackjin1997:mainfrom
feezy1357:main

Conversation

@feezy1357

@feezy1357 feezy1357 commented Jul 7, 2026

Copy link
Copy Markdown

Solution for [$50 BOUNTY] Add gateway auth middleware tests

Changes

Added comprehensive test coverage for market/gateway/middleware.go:

AuthMiddleware tests:

  • Missing token → 401 Unauthorized
  • Empty Bearer token → 401 Unauthorized
  • Valid Bearer token → 200, context values set
  • X-API-Key header authentication
  • Wrong auth scheme (Basic) → 401

RateLimitMiddleware tests:

  • Under limit → 200 with rate limit headers
  • Exceeds limit → 429 Too Many Requests
  • Different clients have separate rate limit buckets
  • Rate limit header values are consistent
  • API key based bucketing (separate from IP-based)

Middleware ordering tests:

  • Auth runs before rate limit (unauthenticated requests don't consume rate limit budget)
  • Authenticated requests properly consume rate limit budget
  • Full middleware chain integration test

Token bucket unit tests:

  • Initial state allows with correct remaining count
  • Refills over time based on rate
  • Empty bucket denies with future reset time

Token extraction tests:

  • Bearer token from Authorization header
  • API key from X-API-Key header
  • No auth headers → empty token
  • Bearer takes precedence over API key

Verification

All tests use standard library net/http/httptest and require no external dependencies.

Closes #2

Summary by CodeRabbit

  • Tests
    • Added comprehensive middleware coverage for authentication, rate limiting, and request handling.
    • Verified support for bearer tokens and API keys, including invalid or missing credentials.
    • Confirmed rate limits are tracked correctly per client, with consistent limit headers and proper reset behavior.
    • Added end-to-end checks for middleware ordering and request ID generation.

Adds comprehensive tests for AuthMiddleware, RateLimitMiddleware,
token bucket, middleware ordering, and the full middleware chain.

- AuthMiddleware tests: missing/empty/valid/invalid tokens
- RateLimitMiddleware tests: under/over limit, per-client buckets
- Middleware ordering: auth before rate limiting
- Token bucket unit tests: initial state, refill, empty
- Token extraction: Bearer, API-Key, precedence

Fixes jackjin1997#2
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 56 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

Run ID: 2c9741bd-e506-497e-b5e9-c6ae4d8a7563

📥 Commits

Reviewing files that changed from the base of the PR and between 55380a4 and 459aef0.

📒 Files selected for processing (1)
  • backend/src/protocol/codec.rs
📝 Walkthrough

Walkthrough

Adds a new test file for the gateway package covering AuthMiddleware, RateLimitMiddleware, middleware ordering, extractToken, and token bucket behavior, with helper functions for JSON response generation and decoding.

Changes

Gateway middleware test suite

Layer / File(s) Summary
Test helpers
market/gateway/middleware_test.go
Introduces helpers for producing JSON responses and decoding response bodies used throughout the test suite.
AuthMiddleware tests
market/gateway/middleware_test.go
Covers missing/empty bearer tokens, valid bearer token with context value checks, valid API key header, and wrong auth scheme.
RateLimitMiddleware tests
market/gateway/middleware_test.go
Covers under/over limit requests, per-client and per-API-key bucket separation, and consistency of X-RateLimit-* headers.
Middleware ordering and chain tests
market/gateway/middleware_test.go
Verifies auth executes before rate limiting, authenticated requests consume rate-limit budget, and full chain sets X-Request-ID.
extractToken and token bucket unit tests
market/gateway/middleware_test.go
Validates token extraction precedence (bearer over API key) and token bucket initial state, refill, and empty-bucket denial.

Estimated code review effort: 2 (Simple) | ~15 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers changes and verification, but it omits the required Summary and Checklist sections and lacks concrete testing/build commands. Add the missing Summary, Testing, and Checklist sections, including the exact commands run and build/test results.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding gateway auth middleware tests.
Linked Issues check ✅ Passed The PR adds tests covering auth, rate limiting, token extraction, middleware ordering, and context propagation as required by #2.
Out of Scope Changes check ✅ Passed The only change is a new gateway middleware test file, which stays within the linked issue's scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

Adds comprehensive recovery and regression tests:
- Reject truncated headers/payloads without panicking
- Reject excessive payload lengths with clear errors
- Reject unsupported versions
- Verify checksum mismatch yields clear errors
- Assert failed decode doesn't corrupt decoder state
- Confirm valid frame after invalid input still decodable
- Deterministic tests runnable on all platforms

Fixes Peter7896#2

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
market/gateway/middleware_test.go (2)

282-355: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Simplified chain diverges from the documented production order.

The comment at Line 324 describes the full production order (Recovery → RequestID → Logging → CORS → Auth → RateLimit → Metrics → Context → Handler), but the test only exercises Recovery, RequestID, Auth, and RateLimit. This is fine as an ordering smoke test, but the comment slightly overstates what's actually verified here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@market/gateway/middleware_test.go` around lines 282 - 355, The comment in
TestFullMiddlewareChain overstates the middleware coverage because the handler
chain only includes RecoveryMiddleware, RequestIDMiddleware, AuthMiddleware, and
RateLimitMiddleware. Update the test comment to describe it as a partial
ordering smoke test, or expand the chain to include the missing middleware
symbols (Logging, CORS, Metrics, Context) if you want to verify the full
documented production order.

134-274: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Minor: each RateLimitMiddleware call leaks a ticker goroutine.

Per context snippet 2, RateLimitMiddleware starts a time.NewTicker(5*time.Minute) cleanup goroutine that's never stopped. Multiple tests in this file (Lines 134-274) invoke RateLimitMiddleware directly, each spawning an un-stoppable background goroutine for the life of the test binary. Not a correctness issue for a short-lived test process, but worth noting if this pattern is reused in longer-running test suites.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@market/gateway/middleware_test.go` around lines 134 - 274,
`RateLimitMiddleware` currently starts a cleanup ticker goroutine that is never
stopped, and these tests create several middleware instances. Update the
middleware implementation so the ticker can be stopped or the goroutine can exit
cleanly, and ensure `RateLimitMiddleware` does not leave background work running
after use; if needed, add a shutdown/cleanup path tied to the middleware’s
ticker lifecycle so repeated calls from `TestRateLimitMiddleware_*` don’t leak
goroutines.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@market/gateway/middleware_test.go`:
- Around line 3-10: The test file has an unused `strings` import that prevents
compilation, so remove it from the import block in `middleware_test.go` unless a
real code reference is added elsewhere. Verify the remaining imports used by
`TestMiddleware` and related helpers still compile cleanly with `go test
./market/gateway`.
- Around line 70-100: The test is checking values on the original request
instead of the request passed through AuthMiddleware, so the context assertions
will stay nil. Update TestAuthMiddleware_ValidBearerToken to capture the request
received by testHandler and assert ContextKeyUserID, ContextKeySessionID, and
ContextKeyAuthMethod on that forwarded request (the one created via
Request.WithContext inside AuthMiddleware), not on req.

---

Nitpick comments:
In `@market/gateway/middleware_test.go`:
- Around line 282-355: The comment in TestFullMiddlewareChain overstates the
middleware coverage because the handler chain only includes RecoveryMiddleware,
RequestIDMiddleware, AuthMiddleware, and RateLimitMiddleware. Update the test
comment to describe it as a partial ordering smoke test, or expand the chain to
include the missing middleware symbols (Logging, CORS, Metrics, Context) if you
want to verify the full documented production order.
- Around line 134-274: `RateLimitMiddleware` currently starts a cleanup ticker
goroutine that is never stopped, and these tests create several middleware
instances. Update the middleware implementation so the ticker can be stopped or
the goroutine can exit cleanly, and ensure `RateLimitMiddleware` does not leave
background work running after use; if needed, add a shutdown/cleanup path tied
to the middleware’s ticker lifecycle so repeated calls from
`TestRateLimitMiddleware_*` don’t leak goroutines.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f8177a27-e631-45fe-8ecb-481967b23e5d

📥 Commits

Reviewing files that changed from the base of the PR and between 1462fe7 and 55380a4.

📒 Files selected for processing (1)
  • market/gateway/middleware_test.go

Comment on lines +3 to +10
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Unused import breaks compilation.

strings is imported but never referenced anywhere in this file (only mentioned inside comments at Lines 123-124). Go will fail to compile with imported and not used: "strings", which breaks the entire test file, not just one test — this directly blocks the go test ./market/gateway requirement called out in the PR objectives.

🐛 Proposed fix
 import (
 	"encoding/json"
 	"net/http"
 	"net/http/httptest"
-	"strings"
 	"testing"
 	"time"
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@market/gateway/middleware_test.go` around lines 3 - 10, The test file has an
unused `strings` import that prevents compilation, so remove it from the import
block in `middleware_test.go` unless a real code reference is added elsewhere.
Verify the remaining imports used by `TestMiddleware` and related helpers still
compile cleanly with `go test ./market/gateway`.

Comment on lines +70 to +100
func TestAuthMiddleware_ValidBearerToken(t *testing.T) {
handler := AuthMiddleware(testHandler())

req := httptest.NewRequest(http.MethodGet, "/api/v1/market", nil)
req.Header.Set("Authorization", "Bearer valid-token-12345")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

if rec.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", rec.Code)
}

// Verify user context was set
userID := req.Context().Value(ContextKeyUserID)
if userID == nil {
t.Error("expected user ID in context, got nil")
}
if userID.(string) != "user_stub" {
t.Errorf("expected user ID 'user_stub', got %v", userID)
}

sessionID := req.Context().Value(ContextKeySessionID)
if sessionID == nil {
t.Error("expected session ID in context, got nil")
}

authMethod := req.Context().Value(ContextKeyAuthMethod)
if authMethod.(string) != "bearer" {
t.Errorf("expected auth method 'bearer', got %v", authMethod)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Context assertions check the wrong object — will fail even after fixing compilation.

http.Request.WithContext returns a shallow copy of the request rather than mutating the receiver. In AuthMiddleware, the modified context is only attached to the copy passed to next.ServeHTTP, and this test's testHandler discards that request without exposing it. As a result, req.Context().Value(ContextKeyUserID) at Line 83 still refers to the original, unmodified context and will read nil, causing the test to fail.

Capture the request actually seen by the wrapped handler instead:

🐛 Proposed fix
 func TestAuthMiddleware_ValidBearerToken(t *testing.T) {
-	handler := AuthMiddleware(testHandler())
+	var capturedReq *http.Request
+	inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		capturedReq = r
+		w.WriteHeader(http.StatusOK)
+	})
+	handler := AuthMiddleware(inner)
 
 	req := httptest.NewRequest(http.MethodGet, "/api/v1/market", nil)
 	req.Header.Set("Authorization", "Bearer valid-token-12345")
 	rec := httptest.NewRecorder()
 	handler.ServeHTTP(rec, req)
 
 	if rec.Code != http.StatusOK {
 		t.Errorf("expected status 200, got %d", rec.Code)
 	}
 
 	// Verify user context was set
-	userID := req.Context().Value(ContextKeyUserID)
+	userID := capturedReq.Context().Value(ContextKeyUserID)

Apply the same fix pattern to the other sessionID/authMethod lookups (Lines 91-99).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@market/gateway/middleware_test.go` around lines 70 - 100, The test is
checking values on the original request instead of the request passed through
AuthMiddleware, so the context assertions will stay nil. Update
TestAuthMiddleware_ValidBearerToken to capture the request received by
testHandler and assert ContextKeyUserID, ContextKeySessionID, and
ContextKeyAuthMethod on that forwarded request (the one created via
Request.WithContext inside AuthMiddleware), not on req.

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.

[$50 BOUNTY] [Go] Add gateway auth middleware tests

1 participant