Skip to content

Fix: Serve the viewer's pprof on loopback only and share the guard in httpx - #1611

Merged
huang195 merged 4 commits into
mainfrom
feat/agentop-pprof-loopback
Oct 30, 2026
Merged

huang195 merged 4 commits into
mainfrom
feat/agentop-pprof-loopback

Conversation

@huang195

@huang195 huang195 commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

What

Follow-up to #1608, which merged at its original head three minutes after clawgenti's approve-with-comments landed — before any of the review's findings could. Two commits:

1. Fix: Serve the viewer's pprof on loopback only, announcing the bound address — the three review comments:

  • The bind address was never checked to be loopback. AGENTOP_PPROF_ADDR=:47603 or 0.0.0.0:47603 listened on every interface, and the Host and Origin guards stop browsers only: anyone on the LAN could curl -H 'Host: localhost' the heap — which holds the session content the viewer is displaying — plus argv, and start CPU/trace profiling. startPprof now refuses a bind that did not land on loopback, checked on ln.Addr() rather than the string (so a name that resolves to loopback still works), riding the existing stderr-and-continue path. Feat: Serve pprof on the stats server when loopback-only #1603 gates its pprof the same way, on the stats port's bind_loopback_only.
  • The startup announce prints the bound address, so :0 shows its real port instead of a port nobody can use.
  • startPprof gained the tests it lacked: a real-socket 403/200 pair pinning that the server serves the guarded mux (never DefaultServeMux), and the loopback refusal. Both written red-first — they fail on Feat: Serve pprof from the agentop viewer #1608's merged head.

2. Refactor: Judge loopback Hosts and mount pprof through shared httpx helpers — the should-fix from #1608's pre-merge review: loopbackHost existed as three unexported copies (sessionapi's erase guards, observe's stats server, the agentop viewer) and the guarded pprof mount as two. core/listener/httpx now owns LoopbackHost and RegisterPprof, byte-identical to the copies they replace. The guard table is pinned once in httpx's own tests — the union of the three sites' cases plus hardening cases (0177.0.0.1, 127.1, localhost., [::ffff:127.0.0.1]) — and observe's and sessionapi's existing end-to-end guard tests keep pinning their wiring.

Verified

  • Red-first: the new tests fail on Feat: Serve pprof from the agentop viewer #1608's merged head (compile error on the old startPprof signature; the refusal test against code that accepted 0.0.0.0:0).
  • Green at head: core (listener/httpx, sessionapi, observe) and the agentop pprof tests pass; the full cmd/agentop package suite passes (~7 min, env -u SSL_CERT_FILE); go vet, gofmt and go mod tidy -diff clean in both modules.
  • Two independent headless reviews of the round, both approving: behavior parity of the dedupe (surviving predicate byte-identical to every deleted copy), the reader sweep (no missed consumer of the predicate or of startPprof's signature; agentop's two broader isLoopbackHost helpers are deliberately different predicates and correctly untouched), and the DefaultServeMux claim (no module that links httpx serves it).

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • Bug Fixes
    • Profiling requests are refused when they include a browser Origin header or use a non-loopback Host.
    • Profiling servers now refuse to start when bound to a non-loopback address.
    • Session-clearing requests continue to require an accepted loopback Host, and are refused when an Origin header is present or clearing is not allowed.
  • Documentation
    • Updated profiling guidance to describe the request checks and rejected non-loopback bind addresses.

…elpers

The loopback-Host predicate existed as three unexported copies (the
session API's erase guards, the stats server's pprof endpoints, the
agentop viewer) and the guarded pprof mounting as two. core/listener/
httpx now owns both: LoopbackHost and RegisterPprof, with the guard
table and heap-profile shape pinned once in httpx's own tests. agentop
keeps one wiring test; observe's and sessionapi's existing tests now
exercise the shared code through their own servers.

Also merges main into the branch: the PR branched before #1603 landed,
so the observe half of this dedupe had no code to change without it.

Fixes review: PR #1608 review finding 1 — a security predicate copied
per binary drifts when one copy is fixed and the others are not.
Files: cmd/agentop/pprof.go, cmd/agentop/pprof_test.go,
core/listener/httpx/pprof.go, core/listener/httpx/pprof_test.go,
core/listener/httpx/render.go, core/observe/statserver.go,
core/sessionapi/clear.go, core/sessionapi/delete_test.go

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
…address

The Host and Origin guards stop browsers, not a curl that sets
Host: localhost, so AGENTOP_PPROF_ADDR=:47603 or 0.0.0.0:47603 would
hand the heap — the session content the viewer is displaying — to
anyone on the network. startPprof now refuses a bind that did not land
on loopback, checked on the bound address rather than the string, and
returns the address it landed on so a :0 port is announced as its real
port. #1603 gates its pprof the same way, on the stats port's
bind_loopback_only.

Fixes review: clawgenti's approve-with-comments on #1608 — the
unguarded bind address, the :0 announce, and the missing startPprof
test, which the returned address makes possible over a real socket.
Files: cmd/agentop/pprof.go, cmd/agentop/pprof_test.go,
cmd/agentop/README.md

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 requested a review from a team as a code owner October 30, 2026 15:03
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 24 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 024acfc3-39d0-404d-9680-e8f8057a29e3
Commits

Reviewing files that changed from the base of the PR and between c9f1018 and 1f3df07.

Files selected for processing: 11
  • cmd/agentop/README.md
  • cmd/agentop/pprof.go
  • cmd/agentop/pprof_test.go
  • core/listener/httpx/loopback.go
  • core/listener/httpx/loopback_test.go
  • core/listener/httpx/pprofx/pprof.go
  • core/listener/httpx/pprofx/pprof_test.go
  • core/listener/httpx/render.go
  • core/observe/statserver.go
  • core/sessionapi/clear.go
  • core/sessionapi/delete_test.go

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1894b658-0f4c-450d-bc9c-1362c4694f50
Commits

Reviewing files that changed from the base of the PR and between b798ce1 and c9f1018.

Files selected for processing: 9
  • cmd/agentop/README.md
  • cmd/agentop/pprof.go
  • cmd/agentop/pprof_test.go
  • core/listener/httpx/pprof.go
  • core/listener/httpx/pprof_test.go
  • core/listener/httpx/render.go
  • core/observe/statserver.go
  • core/sessionapi/clear.go
  • core/sessionapi/delete_test.go

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

The change centralizes loopback-host validation and guarded pprof handler registration in httpx. Agentop rejects profiling listeners that bind outside loopback and logs the resolved address. Statserver and session clear checks use the shared helper.

Changes: Loopback guards and pprof registration

Layer / File(s) Summary
Shared host validation and pprof handlers
core/listener/httpx/pprof.go, core/listener/httpx/pprof_test.go, core/listener/httpx/render.go
httpx adds LoopbackHost and RegisterPprof. Tests cover accepted hosts, rejected requests, and heap-profile responses.
Agentop pprof listener and registration
cmd/agentop/pprof.go, cmd/agentop/pprof_test.go, cmd/agentop/README.md
Agentop rejects pprof listeners that bind outside loopback, registers handlers through httpx, and logs the bound address. Tests cover listener binding and Host handling. The README describes the guards.
Statserver and session-clear integration
core/observe/statserver.go, core/sessionapi/clear.go, core/sessionapi/delete_test.go
Statserver registers pprof through httpx. Session clear checks use httpx.LoopbackHost. Both files remove local loopback-host implementations.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

  • rossoctl/cortex issue 1579: This PR consolidates the loopback-host predicate in agentop, observe, and sessionapi, but does not update the other copies named in the issue.

Suggested labels: ready-for-ai-review

Suggested reviewers: clawgenti, alan-cha, evaline-ju

Merge Risk: Minimal · previous review c9f10

The supplied evidence identifies no issue requiring correction before merge; proceed with normal checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main changes: restricting the viewer's pprof server to loopback and sharing the guard in httpx.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 11 functions across 8 files. (1 skipped: 1 unsupported.)

Finishing Touches: 💡 1
⚔️ Resolve merge conflicts: 💡
  • Resolve merge conflict in branch feat/agentop-pprof-loopback
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

This is a clean follow-up to #1608. startPprof now checks the bound address with ln.Addr().(*net.TCPAddr).IP.IsLoopback(), which is the right test: it doesn't depend on the string, it rejects :47603 and 0.0.0.0:…, and a name that resolves to loopback still works. The announce prints the real port, and the new real-socket test pins that the server never falls back to DefaultServeMux. The dedupe holds up: httpx.LoopbackHost and httpx.RegisterPprof match all three deleted copies byte for byte (I diffed them), and the union guard table plus the hardening cases is a better place to pin this than three per-binary tables. I re-ran go test for core/listener/httpx, core/observe, core/sessionapi and the agentop Pprof tests at head, plus go vet and gofmt, and all are clean.

One thing to do before merge: the branch conflicts with main in core/observe/statserver.go. #1609 landed runtime.SetBlockProfileRate(1) / SetMutexProfileFraction(1) inside the same if o.pprof block this PR collapses (inline note). The other two comments are optional.

Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (core/listener/httpx, core/observe, core/sessionapi, cmd/agentop), Docs, Security
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (mergeable state: CONFLICTING against main)

Comment thread core/observe/statserver.go Outdated
mux.HandleFunc("/debug/pprof/profile", pprofGuard(pprof.Profile))
mux.HandleFunc("/debug/pprof/symbol", pprofGuard(pprof.Symbol))
mux.HandleFunc("/debug/pprof/trace", pprofGuard(pprof.Trace))
httpx.RegisterPprof(mux)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion (rebase needed): this conflicts with #1609 (19ee6dad), which added this to the same block:

runtime.SetBlockProfileRate(1)
runtime.SetMutexProfileFraction(1)

resolve it as:

if o.pprof {
	// (keep #1609's comment)
	runtime.SetBlockProfileRate(1)
	runtime.SetMutexProfileFraction(1)
	httpx.RegisterPprof(mux)
}

and keep the "runtime" import while dropping "net/http/pprof". I'd leave the rate calls here rather than moving them into RegisterPprof. They set process-global runtime state, and the stats server is the caller that wants them. If agentop wants contention profiles later, it can opt in on its own side. TestStatServerPprofEnablesContentionProfiles will catch a resolution that drops them.

Comment thread core/listener/httpx/pprof.go Outdated
import (
"net"
"net/http"
"net/http/pprof"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

suggestion: the side-effect import now reaches every module that links httpx, which means forwardproxy, reverseproxy, extproc and sessionapi, not only the two places that mount pprof. For the cortex binaries nothing changes, since they already linked it through observe. scripts/readme-demo is different: go list -deps shows net/http/pprof going from 0 to 1 there at head, because it links sessionapi. It doesn't serve an HTTP server, so nothing is exposed today. Still, the doc's invariant ("nothing serves DefaultServeMux, none may be") now has to hold in every program that touches the listener helpers.

Moving RegisterPprof (and only that) into a leaf package such as core/listener/httpx/pprofx would keep the init registration limited to binaries that actually mount pprof. LoopbackHost is pure, so it can stay in httpx for sessionapi. Not blocking. If you keep it here, a loopback.go home for LoopbackHost would also read better than pprof.go, now that sessionapi uses it for erase guards.

Comment thread cmd/agentop/pprof_test.go
// viewer is displaying — to anyone on the network. Checked on the bound
// address, not the string, so a name that resolves to loopback still works.
func TestStartPprofRefusesANonLoopbackBind(t *testing.T) {
if _, _, err := startPprof("0.0.0.0:0"); err == nil || !strings.Contains(err.Error(), "loopback") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: the doc and this comment both promise "checked on the bound address, not the string, so a name that resolves to loopback still works", but only the refusal half is tested. A startPprof("localhost:0") case that expects success (and a 127. prefix on bound) would pin the other half, so a later move to a string check like strings.HasPrefix(addr, "127.0.0.1") fails red. Minor, and separate: on a host with no IPv4 stack, net.Listen("tcp", "0.0.0.0:0") fails with an error that doesn't mention "loopback", so this test would fail spuriously there. It's unlikely on CI, so feel free to ignore.

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review. This PR follows up on my approve-with-comments on #1608, which merged before any of the findings could land. All three are fixed:

  • suggestion: the loopback bind was not enforced. Fixed. startPprof now checks ln.Addr() after binding and refuses anything that is not loopback, using the existing stderr-and-continue path. So :port and 0.0.0.0:port are rejected, and a name that resolves to loopback still works. The README now says so.
  • nit: the announce showed the configured address. Fixed. startPprof returns ln.Addr().String(), and maybeServePprof prints that, so :0 shows the real port.
  • nit: startPprof had no tests. Fixed. TestStartPprofServesTheGuardedMux uses a real socket and checks a 403 for a rebound Host, a 200 for a loopback Host, and that the returned address has a resolved port. That pins that the server uses the guarded mux and not DefaultServeMux. TestStartPprofRefusesANonLoopbackBind covers the refusal.

The refactor commit also handles the should-fix from #1608. httpx.LoopbackHost and httpx.RegisterPprof match the copies they replace (three of loopbackHost, two of the guarded mount). No loopbackHost copy is left in the tree. The guard table now lives once in httpx and adds the hardening cases (0177.0.0.1, 127.1, localhost., [::ffff:127.0.0.1]). sessionapi's clear_test.go still pins the erase guards end to end.

I also checked the side effect of moving the net/http/pprof import into httpx. All four binaries (cortex, cortex-envoy, cortex-praxis, agentop) already linked net/http/pprof at base, so DefaultServeMux has no new exposure. Every non-demo http.Server in core/ and cmd/ sets an explicit Handler. The demos are separate modules and do not import httpx.

I ran these locally at c9f1018 (Go 1.26.10, workspace mode): the tests in core/listener/httpx, core/observe and core/sessionapi pass, as do the pprof/loopback tests in cmd/agentop. gofmt and go vet are clean on the touched packages. One cmd/agentop test, TestReportSessionInterruption, fails in my sandbox, but it fails the same way on base b798ce1, so the cause is my environment and not this PR.

One optional nit is inline.

Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go, Tests, Docs, Security
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: no failures; DCO, CodeQL (python), Trivy, cortex/cortex-envoy/cortex-praxis Go CI and the module-tidy check pass; Go CI (core, agentop, cortex), CodeQL (go) and some image builds still pending

Comment thread cmd/agentop/pprof.go
// Handler is set, never nil: net/http/pprof's init also registers
// /debug/pprof/* on http.DefaultServeMux, which a nil Handler would serve
// ungated.
srv := &http.Server{Handler: pprofMux()}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit (pre-existing, optional): the stats server and session API both set ReadHeaderTimeout: 10 * time.Second, but this server sets none, so gosec G112 / Slowloris applies. It matters little now that the bind is loopback-only. Adding the timeout would match the other two servers, and it would not limit /debug/pprof/profile or /trace, which stream for ?seconds=N, because it covers only the request headers.

RegisterPprof moves from httpx to httpx/pprofx, and LoopbackHost stays in
httpx (now loopback.go) where sessionapi's erase guards read it. The
net/http/pprof import registers /debug/pprof/* on http.DefaultServeMux at
init, so living in httpx handed that registration to every consumer of the
listener helpers — forwardproxy, reverseproxy, extproc, sessionapi — that
never serves pprof; in pprofx it reaches only the two mounters (observe's
stats server, the agentop viewer). Verified with go list -deps:
scripts/readme-demo, which links sessionapi, goes from linking
net/http/pprof to not linking it.

Fixes review: #1611 — the suggestion to split RegisterPprof out of httpx;
the nit to pin the success half of startPprof's bound-address check (a
localhost:0 bind succeeds and lands on a loopback IP, not a string prefix).
Files: cmd/agentop/pprof.go cmd/agentop/pprof_test.go core/listener/httpx/loopback.go core/listener/httpx/loopback_test.go core/listener/httpx/pprof.go core/listener/httpx/pprofx/pprof.go core/listener/httpx/pprofx/pprof_test.go core/observe/statserver.go

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 merged commit 8ab08ac into main Oct 30, 2026
40 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 30, 2026
@huang195
huang195 deleted the feat/agentop-pprof-loopback branch October 30, 2026 15:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants