Skip to content

Conversation

@nexus49
Copy link
Contributor

@nexus49 nexus49 commented Sep 15, 2025

Summary by CodeRabbit

  • New Features
    • Optional authentication can now be enabled for requests, enhancing security when needed.
  • Refactor
    • Streamlined request middleware to improve reliability and observability (logging, tracing, request IDs, error recovery).
  • Tests
    • Added coverage for both authenticated and unauthenticated request paths to ensure consistent behavior.

• Introduces optional authentication middleware in CreateMiddleware
• Updates tests to validate middleware behavior with and without auth
@nexus49 nexus49 requested review from a team as code owners September 15, 2025 08:37
@coderabbitai
Copy link

coderabbitai bot commented Sep 15, 2025

Walkthrough

Removes the exported Middleware type alias, updates CreateAuthMiddleware to return a slice of concrete middleware functions, modifies CreateMiddleware to accept a boolean to optionally include auth middlewares, and updates tests to cover both with-auth and without-auth paths.

Changes

Cohort / File(s) Summary of changes
Auth middleware type change
middleware/authzMiddlewares.go
Removed exported type alias Middleware. Updated CreateAuthMiddleware signature to return []func(http.Handler) http.Handler. Adjusted doc comment. Returned middlewares unchanged (StoreWebToken, StoreAuthHeader, StoreSpiffeHeader).
Middleware chain assembly
middleware/middleware.go
Changed CreateMiddleware signature to func CreateMiddleware(log *logger.Logger, auth bool) []func(http.Handler) http.Handler. Builds base middlewares and conditionally appends auth middlewares when auth is true. Updated doc comment.
Tests for middleware composition
middleware/middleware_test.go
Updated calls to CreateMiddleware with new boolean parameter. Added test for withAuth=true expecting 8 middlewares; kept/updated test for withAuth=false expecting 5. Verified chaining and 200 OK response.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "feat(middleware): enhance middleware configuration for auth" succinctly and accurately summarizes the main change in this PR — making authentication middleware inclusion configurable and updating middleware signatures. It follows conventional-commit style and is clear enough for a teammate scanning the commit history.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/make-it-easier-to-confgure-all-middlewares

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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 and usage tips.

Copy link

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
middleware/authzMiddlewares.go (1)

7-15: Avoid breaking change: reintroduce a deprecated alias for compatibility

Removing the exported middleware type breaks any downstream code that referenced middleware.Middleware or []Middleware. If the intent isn’t a major release, keep a type alias to preserve source compatibility while still using the concrete function type internally.

Apply this diff in this package (e.g., here or a small types.go):

 package middleware

 import (
 	"net/http"
 )
 
+// Deprecated: Use func(http.Handler) http.Handler directly. Kept for source compatibility; will be removed in the next major version.
+type Middleware = func(http.Handler) http.Handler
+
 // CreateAuthMiddleware returns a slice of middleware functions for authentication and authorization.
 // The returned middlewares are: StoreWebToken, StoreAuthHeader, and StoreSpiffeHeader.
 func CreateAuthMiddleware() []func(http.Handler) http.Handler {
 	return []func(http.Handler) http.Handler{
 		StoreWebToken(),
 		StoreAuthHeader(),
 		StoreSpiffeHeader(),
 	}
 }

Also consider renaming to CreateAuthMiddlewares for clarity (optional; would be breaking).

🧹 Nitpick comments (6)
middleware/middleware_test.go (3)

12-18: Parallelize test and keep count assertion stable over time

Run in parallel and avoid hard-coding the base count to reduce churn if base middlewares change later.

Apply this diff:

-func TestCreateMiddleware_WithoutAuth(t *testing.T) {
-	log := testlogger.New()
-	middlewares := CreateMiddleware(log.Logger, false)
+func TestCreateMiddleware_WithoutAuth(t *testing.T) {
+	t.Parallel()
+	log := testlogger.New()
+	middlewares := CreateMiddleware(log.Logger, false)
 
-	// Should return 5 middlewares when auth is false
-	assert.Len(t, middlewares, 5)
+	// Should return only base middlewares when auth is false
+	assert.GreaterOrEqual(t, len(middlewares), 1)

43-53: Derive expected length instead of hard-coding 8

Compute expected count from the base chain + CreateAuthMiddleware() so the test won’t break when the list evolves.

Apply this diff:

-func TestCreateMiddleware_WithAuth(t *testing.T) {
-	log := testlogger.New()
-	middlewares := CreateMiddleware(log.Logger, true)
+func TestCreateMiddleware_WithAuth(t *testing.T) {
+	t.Parallel()
+	log := testlogger.New()
+	middlewares := CreateMiddleware(log.Logger, true)
 
-	// Should return 8 middlewares when auth is true (5 base + 3 auth)
-	assert.Len(t, middlewares, 8)
+	// Should return base + auth middlewares
+	base := CreateMiddleware(log.Logger, false)
+	expected := len(base) + len(CreateAuthMiddleware())
+	assert.Len(t, middlewares, expected)
 
 	// Each middleware should be a valid function
 	for _, mw := range middlewares {
 		assert.NotNil(t, mw)
 	}

55-72: Add a panic‑recovery assertion to verify SentryRecoverer works in the composed chain

Small, focused test ensures recovery behavior stays intact if order changes.

Add this new test (outside this hunk):

func TestCreateMiddleware_RecoversFromPanic(t *testing.T) {
	t.Parallel()
	log := testlogger.New()
	middlewares := CreateMiddleware(log.Logger, false)

	panicHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		panic("boom")
	})

	var final http.Handler = panicHandler
	for i := len(middlewares) - 1; i >= 0; i-- {
		final = middlewares[i](final)
	}

	req := httptest.NewRequest("GET", "http://testing", nil)
	rec := httptest.NewRecorder()
	final.ServeHTTP(rec, req)

	assert.Equal(t, http.StatusInternalServerError, rec.Code)
}
middleware/middleware.go (3)

9-12: Document ordering contract

Call out that the first element becomes the outermost wrapper when applying right-to-left, to prevent accidental misuse by consumers composing differently.

Proposed tweak:

-// CreateMiddleware creates a middleware chain with logging, tracing, and optional authentication.
+// CreateMiddleware creates a middleware chain with logging, tracing, and optional authentication.
+// Order matters: the first function in the returned slice is intended to be applied last
+// so it becomes the outermost wrapper when composing from right to left.

13-19: Make SentryRecoverer the outermost middleware

Place SentryRecoverer first so it wraps everything and reliably catches panics in all subsequent middleware, including tracing.

Apply this diff:

 func CreateMiddleware(log *logger.Logger, auth bool) []func(http.Handler) http.Handler {
 	mws := []func(http.Handler) http.Handler{
-		SetOtelTracingContext(),
-		SentryRecoverer,
+		SentryRecoverer,
+		SetOtelTracingContext(),
 		StoreLoggerMiddleware(log),
 		SetRequestId(),
 		SetRequestIdInLogger(),
 	}

12-24: Consider an options pattern instead of a boolean flag

A boolean auth doesn’t scale. Options allow future toggles (e.g., custom auth set, request ID strategy) without signature churn.

Example sketch:

type Options struct {
	Auth bool
}
func CreateMiddlewareWithOpts(log *logger.Logger, opts Options) []func(http.Handler) http.Handler { /* ... */ }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6915f5 and 780c52c.

📒 Files selected for processing (3)
  • middleware/authzMiddlewares.go (1 hunks)
  • middleware/middleware.go (1 hunks)
  • middleware/middleware_test.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
middleware/middleware.go (5)
middleware/otel.go (1)
  • SetOtelTracingContext (18-25)
middleware/sentry.go (1)
  • SentryRecoverer (19-36)
middleware/logger.go (1)
  • StoreLoggerMiddleware (11-21)
middleware/requestid.go (2)
  • SetRequestId (18-33)
  • SetRequestIdInLogger (40-50)
middleware/authzMiddlewares.go (1)
  • CreateAuthMiddleware (9-15)
middleware/middleware_test.go (1)
middleware/middleware.go (1)
  • CreateMiddleware (12-25)
⏰ 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: pipe / lint / lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
middleware/middleware.go (1)

9-25: Verify repo-wide call sites updated to new signature

Definition found at middleware/middleware.go:12 and two callers in middleware/middleware_test.go:14 and 45 — both use CreateMiddleware(log.Logger, ...). No matches for type Middleware or []Middleware.

@nexus49 nexus49 merged commit 1a219bf into main Sep 15, 2025
9 checks passed
@nexus49 nexus49 deleted the feat/make-it-easier-to-confgure-all-middlewares branch September 15, 2025 08:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants