Skip to content

Add gateway auth middleware integration tests#38

Open
spektre-labs wants to merge 4 commits into
jackjin1997:mainfrom
spektre-labs:bounty/issue-2
Open

Add gateway auth middleware integration tests#38
spektre-labs wants to merge 4 commits into
jackjin1997:mainfrom
spektre-labs:bounty/issue-2

Conversation

@spektre-labs

@spektre-labs spektre-labs commented Jul 7, 2026

Copy link
Copy Markdown

Fixes #2

Integration tests for gateway middleware (auth, rate limit ordering, CORS, recovery).
Bounty delivery for issue #2.

Summary by CodeRabbit

  • Tests
    • Added coverage for gateway middleware behavior, including authentication, rate limiting, request IDs, CORS preflight handling, panic recovery, and request timeouts.
    • Verified that unauthenticated requests are rejected, valid bearer tokens work correctly, and request context values are preserved.
    • Confirmed rate limits are applied per API key and that authentication failures do not consume rate-limit capacity.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a new Go test file for the gateway package containing integration-style tests covering AuthMiddleware, RateLimitMiddleware, RequestIDMiddleware, CORSMiddleware, RecoveryMiddleware, and TimeoutMiddleware, including verification of middleware chain ordering between authentication and rate limiting.

Changes

Gateway middleware tests

Layer / File(s) Summary
Test file setup
market/gateway/middleware_test.go
New test file added with package imports and header comments describing middleware ordering/context propagation tests.
AuthMiddleware behavior
market/gateway/middleware_test.go
Tests verify 401 response when Authorization is missing, and that a Bearer token propagates ContextKeyUserID/ContextKeySessionID into the request context.
RateLimitMiddleware and auth/rate-limit ordering
market/gateway/middleware_test.go
Tests confirm rate limiting keys on X-API-Key rather than IP, and that AuthMiddleware runs before RateLimitMiddleware so failed-auth requests don't consume rate-limit budget.
RequestID, CORS, Recovery, Timeout middleware
market/gateway/middleware_test.go
Tests cover X-Request-ID generation/preservation, CORS preflight (204) and Access-Control-Allow-Origin, panic recovery returning 500, and context cancellation via TimeoutMiddleware.

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

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthMiddleware
    participant RateLimitMiddleware
    participant Handler

    Client->>AuthMiddleware: Request with/without Bearer token
    alt token missing/invalid
        AuthMiddleware-->>Client: 401 Unauthorized
    else token valid
        AuthMiddleware->>AuthMiddleware: Set ContextKeyUserID, ContextKeySessionID
        AuthMiddleware->>RateLimitMiddleware: Forward request with context
        alt API key over limit
            RateLimitMiddleware-->>Client: 429 Too Many Requests
        else within limit
            RateLimitMiddleware->>Handler: Forward request
            Handler-->>Client: 200 OK
        end
    end
Loading

Related issues: #2

Suggested labels: tests, gateway, go

Suggested reviewers: jackjin1997

🐰 Middleware guards stand in a row,
Tokens checked before quotas flow,
Panics caught, IDs preserved with care,
Timeouts cancel context with flair,
Tests confirm the chain is sound and slow.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description misses the required Summary, Changes, Testing, and Checklist sections from the template. Add the template sections with a brief summary, notable changes, local testing commands/results, and a completed checklist.
Linked Issues check ❓ Inconclusive The tests cover auth, rate limiting, and context propagation, but the summary does not confirm invalid-token and JSON-shape coverage. Confirm the tests assert invalid-token 401 behavior and the expected JSON error payload, then note that coverage explicitly.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: adding gateway auth middleware integration tests.
Out of Scope Changes check ✅ Passed The added tests stay within gateway middleware testing and do not show unrelated cleanup or feature work.
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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies"


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.

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

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

156-174: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Timing-based assertions may be flaky under load.

10ms timeout vs. 50ms handler wait vs. 100ms outer wait leaves a fairly tight margin on a loaded CI runner. Consider widening the ratios (e.g., 50ms/250ms/500ms) to reduce flakiness risk without materially slowing the suite.

🤖 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 156 - 174, The timeout test
in TestTimeoutMiddleware_CancelsContext uses very tight timing windows that can
flake on slower CI machines. Update the TimeoutMiddleware test to use wider,
more forgiving durations for the middleware timeout, the simulated handler wait,
and the outer select wait while keeping the same cancellation behavior and
references to TimeoutMiddleware, http.HandlerFunc, and the done channel.

12-13: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider removing the bounty attribution comment from test source.

Referencing the bounty/issue link directly in code comments is unusual for committed source; this is typically better placed in the PR description/commit message rather than persisted in the file.

🤖 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 12 - 13, Remove the bounty
attribution note from the test source comment in middleware_test.go and keep the
test file comment focused only on the middleware ordering coverage. Update the
top-of-file comment near the integration test description so it no longer
references the bounty/issue link, while preserving any useful context about
auth, rate limiting, and context propagation.

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

Drop the artificial context import usage.

context.Background() at line 174 exists only to keep the "context" import satisfied; the file otherwise only uses r.Context() method calls, which don't require importing "context" directly. Removing the import removes the need for this workaround line.

♻️ Suggested cleanup
 import (
-	"context"
 	"net/http"
 	"net/http/httptest"
 	"strings"
 	"testing"
 	"time"
 )
@@
-	_ = context.Background() // ensure context import used
 }
🤖 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` at line 174, Remove the artificial context
usage in middleware_test.go by deleting the standalone context.Background()
workaround and dropping the direct "context" import, since the test code only
relies on r.Context() and does not need the package imported. Check the test
setup around the middleware tests and keep only the imports actually referenced
by the test helpers and assertions.
🤖 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.

Nitpick comments:
In `@market/gateway/middleware_test.go`:
- Around line 156-174: The timeout test in TestTimeoutMiddleware_CancelsContext
uses very tight timing windows that can flake on slower CI machines. Update the
TimeoutMiddleware test to use wider, more forgiving durations for the middleware
timeout, the simulated handler wait, and the outer select wait while keeping the
same cancellation behavior and references to TimeoutMiddleware,
http.HandlerFunc, and the done channel.
- Around line 12-13: Remove the bounty attribution note from the test source
comment in middleware_test.go and keep the test file comment focused only on the
middleware ordering coverage. Update the top-of-file comment near the
integration test description so it no longer references the bounty/issue link,
while preserving any useful context about auth, rate limiting, and context
propagation.
- Line 174: Remove the artificial context usage in middleware_test.go by
deleting the standalone context.Background() workaround and dropping the direct
"context" import, since the test code only relies on r.Context() and does not
need the package imported. Check the test setup around the middleware tests and
keep only the imports actually referenced by the test helpers and assertions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fae328a0-0817-4e03-92d8-8dfc58dfac7d

📥 Commits

Reviewing files that changed from the base of the PR and between 1462fe7 and 24e594a.

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

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