Skip to content

[management] Propagate context changes to upstream middleware#5956

Merged
bcmmbaga merged 5 commits intomainfrom
debug-logging-ctx
Apr 21, 2026
Merged

[management] Propagate context changes to upstream middleware#5956
bcmmbaga merged 5 commits intomainfrom
debug-logging-ctx

Conversation

@bcmmbaga
Copy link
Copy Markdown
Contributor

@bcmmbaga bcmmbaga commented Apr 21, 2026

Describe your changes

Issue ticket number and link

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__

Summary by CodeRabbit

  • Refactor
    • Optimized authentication middleware request handling with improved context propagation
    • Enhanced telemetry metrics collection for more accurate request context tracking

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 21, 2026

📝 Walkthrough

Walkthrough

This PR refactors the authentication middleware to mutate requests in-place via context propagation instead of returning modified request objects, while adjusting telemetry middleware to preserve and capture context changes made during request handling.

Changes

Cohort / File(s) Summary
Auth Middleware Refactoring
management/server/http/middleware/auth_middleware.go
Changed checkJWTFromRequest and checkPATFromRequest signatures from returning (*http.Request, error) to error, with in-place request mutation via context propagation instead of returning modified copies.
Telemetry Middleware Updates
management/server/telemetry/http_api_metrics.go
Modified to preserve request object by assigning r.WithContext(ctx) and updating ctx from req.Context() after handler execution, removing prior logic that extracted user auth from context.
Dependency Addition
management/server/store/sql_store.go
Added import alias nbutil for github.com/netbirdio/netbird/util with no corresponding code changes in the provided diff.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • crn4

Poem

🐰 A rabbit hops through middleware code,
Where requests once returned, now mutate the load,
Context flows deeper, in-place they transform,
No copies returned, just the truth in a form! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete; the 'Describe your changes' section is empty, lacking explanation of what context changes are being propagated and why this refactor is necessary. Fill in the 'Describe your changes' section with details about how context changes are now propagated to upstream middleware and the rationale for this refactor.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main refactoring change: propagating context changes to upstream middleware in the management module.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch debug-logging-ctx

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
Copy Markdown
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: 1

🧹 Nitpick comments (2)
management/server/telemetry/http_api_metrics.go (1)

196-201: LGTM — context propagation correctly aligned with auth middleware.

Retaining req across ServeHTTP and re-reading req.Context() after the handler returns is the correct counterpart to auth_middleware.go's in-place *r = *... mutation: because both sides operate on the same *http.Request, the ctx populated with UserAuth becomes visible to this middleware's subsequent logging/metrics. The context.AfterFunc at line 187 correctly captures the pre-mutation ctx variable, so cancellation semantics are unchanged.

One optional readability tweak: since r is no longer used after line 197 other than through req, you could drop the new name:

🧹 Optional readability tweak
-		// Hold on to req so auth's in-place ctx update is visible after ServeHTTP.
-		req := r.WithContext(ctx)
-		h.ServeHTTP(w, req)
+		// Hold on to r so auth's in-place ctx update is visible after ServeHTTP.
+		r = r.WithContext(ctx)
+		h.ServeHTTP(w, r)
 		close(handlerDone)
 
-		ctx = req.Context()
+		ctx = r.Context()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/telemetry/http_api_metrics.go` around lines 196 - 201, The
code creates a new local variable req := r.WithContext(ctx) only to call
h.ServeHTTP(w, req) and then read ctx = req.Context(); simplify by reusing r
instead of introducing req: replace the local req usage so that you call
h.ServeHTTP with the updated request (r = r.WithContext(ctx) or equivalent) and
then read ctx = r.Context() after ServeHTTP; update references to handlerDone
and the surrounding context.AfterFunc usage to ensure behavior is unchanged
(ServeHTTP, handlerDone, and auth_middleware.go remain the relevant symbols).
management/server/http/middleware/auth_middleware.go (1)

167-171: Duplication of in-place request mutation warrants encapsulation.

The pattern *r = *nbcontext.SetUserAuthInRequest(r, userAuth) at lines 169 and 220 is necessary and correct—the outer telemetry middleware (in management/server/telemetry/http_api_metrics.go:201) reads req.Context() after ServeHTTP returns, so context updates must mutate in-place to be observable upstream. However, the pattern is duplicated identically in both checkJWTFromRequest and checkPATFromRequest, with only a terse comment explaining the rationale.

Consider extracting a small helper:

♻️ Proposed helper
// setUserAuthOnRequest replaces *r with a shallow copy whose context carries userAuth.
// The in-place replacement is deliberate: outer middleware retains the same *http.Request
// and must observe the updated context after ServeHTTP returns.
func setUserAuthOnRequest(r *http.Request, userAuth auth.UserAuth) {
	*r = *nbcontext.SetUserAuthInRequest(r, userAuth)
}

Then at both call sites:

-	// propagates ctx change to upstream middleware
-	*r = *nbcontext.SetUserAuthInRequest(r, userAuth)
+	setUserAuthOnRequest(r, userAuth)

This removes duplication and clarifies intent for future maintainers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/http/middleware/auth_middleware.go` around lines 167 - 171,
Extract the duplicated in-place request mutation into a small helper (e.g.,
setUserAuthOnRequest) to replace the repeated pattern "*r =
*nbcontext.SetUserAuthInRequest(r, userAuth)" used in checkJWTFromRequest and
checkPATFromRequest; implement setUserAuthOnRequest(r *http.Request, userAuth
auth.UserAuth) to perform the deliberate in-place replacement and call that
helper from both checkJWTFromRequest and checkPATFromRequest so the intent and
rationale are encapsulated and duplication removed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@management/server/store/sql_store.go`:
- Line 48: The import alias nbutil (nbutil "github.com/netbirdio/netbird/util")
is unused in sql_store.go and will break compilation; remove the unused import
line or use the intended symbol from the util package where needed (update
functions in this file that should call util methods to reference nbutil, or
simply delete the nbutil import statement) so the compiler no longer reports an
unused import.

---

Nitpick comments:
In `@management/server/http/middleware/auth_middleware.go`:
- Around line 167-171: Extract the duplicated in-place request mutation into a
small helper (e.g., setUserAuthOnRequest) to replace the repeated pattern "*r =
*nbcontext.SetUserAuthInRequest(r, userAuth)" used in checkJWTFromRequest and
checkPATFromRequest; implement setUserAuthOnRequest(r *http.Request, userAuth
auth.UserAuth) to perform the deliberate in-place replacement and call that
helper from both checkJWTFromRequest and checkPATFromRequest so the intent and
rationale are encapsulated and duplication removed.

In `@management/server/telemetry/http_api_metrics.go`:
- Around line 196-201: The code creates a new local variable req :=
r.WithContext(ctx) only to call h.ServeHTTP(w, req) and then read ctx =
req.Context(); simplify by reusing r instead of introducing req: replace the
local req usage so that you call h.ServeHTTP with the updated request (r =
r.WithContext(ctx) or equivalent) and then read ctx = r.Context() after
ServeHTTP; update references to handlerDone and the surrounding
context.AfterFunc usage to ensure behavior is unchanged (ServeHTTP, handlerDone,
and auth_middleware.go remain the relevant symbols).
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 90a2e34c-3caf-4139-8729-22b45a3c4f03

📥 Commits

Reviewing files that changed from the base of the PR and between 1165058 and 6119ce7.

📒 Files selected for processing (3)
  • management/server/http/middleware/auth_middleware.go
  • management/server/store/sql_store.go
  • management/server/telemetry/http_api_metrics.go

Comment thread management/server/store/sql_store.go Outdated
@sonarqubecloud
Copy link
Copy Markdown

@bcmmbaga bcmmbaga merged commit 57b23c5 into main Apr 21, 2026
43 of 44 checks passed
@bcmmbaga bcmmbaga deleted the debug-logging-ctx branch April 21, 2026 20:06
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