Repository navigation
Let embedders control the audit logger, source, request id - #7486
tgrunnagle wants to merge 6 commits into
Conversation
tgrunnagle
left a comment
There was a problem hiding this comment.
Review
This is a refactor plus a behavior change on a stacked branch: it aliases pkg/audit's event types to toolhive-core's, adds audit.WithLogger and a vMCP AuditLogger field, builds the default logger on HandlerMiddleware, takes source.value from RemoteAddr only, takes the request id from the context instead of X-Request-ID, and moves the default delegation depth from 10 to 16. The approach is sound. The golden-fixture test pins the serialization, the new options are validated at construction, and the observable changes are documented in docs/middleware.md and the PR body. The trade-offs to weigh are that the "every audit line" wording is wider than the code (OBO events), and that dropping the client-supplied request id leaves default deployments with no request id at all.
Cross-cutting observations
- Coverage of the audit path. The request auditor and workflow auditor are routed through the new logger and marked with
logger=audit. The OBO token-exchange events inpkg/auth/oboandpkg/vmcp/auth/strategiesstill useaudit.NewAuditLogger(nil), so they bypass an embedder's logger and lack the marker and the request id. - Request id and source. Nothing in
thv, the proxyrunner, or vMCP sets a request id withContextWithRequestID. Behind an ingress the audit record now has the proxy's address and no join key to the proxy's access log. - Default change. The CRD default only applies to objects written after the CRD upgrade; existing objects with an audit block keep a stored
10. - Stacking. The base is
tgrunnagle/bump-toolhive-core-0.0.64(#7485), so the diff is only the four audit commits. It stays under the size guideline once generated CRD, swagger, and SDK files are excluded.
Findings
| # | Severity | Finding | Location | Raised by |
|---|---|---|---|---|
| 1 | MEDIUM | AuditLogger and the docs claim every audit event is routed and marked, but OBO events are not |
pkg/vmcp/server/server.go:243 |
correctness, documentation, api-design |
| 2 | LOW | Request id is never set by ToolHive, so the documented way to recover the client behind a proxy does not exist by default | pkg/audit/auditor.go:776 |
security |
| 3 | LOW | CRD default 10 to 16 does not reach existing VirtualMCPServer objects | pkg/audit/config.go:61 |
api-design |
| 4 | LOW | Orphan comment explains a removed code path | pkg/audit/auditor.go:501-503 |
readability |
| 5 | LOW | Stale nolint justification on the AuditEvent alias |
pkg/audit/event.go:17 |
readability |
| 6 | LOW | Subtest name claims more than it asserts | pkg/audit/options_test.go:141-156 |
readability, tests |
| 7 | LOW | Defensive branches of the WithLogger / AuditLogger contract have no test |
pkg/audit/options_test.go:159 |
tests |
| 8 | LOW | Reuse the existing request and handler helpers | pkg/audit/options_test.go:55 |
readability |
| 9 | LOW | Merge the two near-identical source tests into one table | pkg/audit/source_test.go:67-87 |
readability |
| 10 | LOW | Type summary is split by the new request-id sentences | pkg/audit/workflow_auditor.go:18-22 |
readability |
How to test
task testforpkg/audit,pkg/vmcp/server, andpkg/vmcp/coreshould pass. Thepkg/networkingcallback-port failure the PR describes is unrelated.- Break the source rule: restore the
X-Forwarded-Forread ingetClientIPand confirmTestAuditor_SourceIgnoresForwardedHeadersandTestAuditor_StreamOpenSourceIgnoresForwardedHeadersfail. - Break request-id stamping: remove the
stampRequestIDcall inWorkflowAuditor.logEventand confirmTestWorkflowAuditor_RequestIDFromContextfails. - Break the default logger: build the default logger with
coreaudit.NewAuditLoggerinstead ofHandlerMiddlewareand confirm thelogger=auditassertions in the log-file subtests ofTestAuditor_DefaultLoggerStampsAuditMarkerfail. - Run a vMCP with an OBO backend and an
AuditLoggerset, and check that the OBO exchange events do not reach it.
Documentation updates
- Narrow the "every audit line carries
logger=audit" wording indocs/middleware.md, or route the OBO events through the new logger. - Note that existing
VirtualMCPServerobjects keep a storedmaxDelegationDepthof 10. - Say that ToolHive does not generate a request id by default, with the follow-up.
Reviewed by dev:review-pr (finders: correctness, readability, security, api design, tests, documentation). Generated with Claude Code.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## tgrunnagle/bump-toolhive-core-0.0.64 #7486 +/- ##
========================================================================
- Coverage 83.07% 83.06% -0.01%
========================================================================
Files 957 957
Lines 100612 100574 -38
========================================================================
- Hits 83584 83546 -38
Misses 17023 17023
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The audit logger option and the logger=audit marker cover the request and workflow auditors only; the OBO token-exchange events keep their own logger. Say so, note that ToolHive sets no request id itself, and that existing VirtualMCPServer objects keep a stored depth of 10. Addresses #7486 review comments: - MEDIUM pkg/vmcp/server/server.go:243 (4793338242): scope AuditLogger, WithLogger and docs to the auditors, document OBO events - LOW pkg/audit/auditor.go:776 (4793338249): document that ToolHive sets no request id - LOW pkg/audit/config.go:61 (4793338254): document the stored depth of existing objects - LOW pkg/audit/auditor.go:503 (4793338262): drop the orphan comment - LOW pkg/audit/event.go:17 (4793338268): reword the nolint reason - LOW pkg/audit/workflow_auditor.go:22 (4793338304): keep the type summary together Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
Cover the nil inputs of WithLogger and the vMCP rejection of an audit logger with a log file, name the stdout subtest after what it asserts, and reuse the shared request, handler and workflow helpers. Addresses #7486 review comments: - LOW pkg/audit/options_test.go:156 (4793338277): rename the stdout subtest - LOW pkg/audit/options_test.go:159 (4793338284): test nil logger, nil config and the vMCP rejection - LOW pkg/audit/options_test.go:55 (4793338292): reuse request, handler and workflow helpers - LOW pkg/audit/source_test.go:87 (4793338298): merge the source tests into a table Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
tgrunnagle
left a comment
There was a problem hiding this comment.
Review
Incremental review of the two commits since the last review (81a504256 and 948782d71). They narrow the audit-logger docs and Go doc comments to the two auditors, document the missing default request id and the stored depth of existing VirtualMCPServer objects, and tighten the tests. The code behavior is unchanged; the changes are documentation, comments, and tests. No new findings at MEDIUM or above.
Resolved since the last review
AuditLoggerand the docs claimed every audit event is routed and marked, but OBO events are not (pkg/vmcp/server/server.go):AuditLogger,audit.WithLogger,audit.NewAuditLoggeranddocs/middleware.mdnow say they cover the request and workflow auditors only, and thatobo_token_exchangeevents go to stdout at level AUDIT with nologgerkey and no request id.- Request id is never set by ToolHive (
pkg/audit/auditor.go):docs/middleware.mdand the PR body now saythv, the proxy runner and the vMCP set no request id, and list the middleware that generates one as a follow-up. - CRD default 10 to 16 does not reach existing objects (
pkg/audit/config.go):docs/middleware.mdand the PR body now say existingVirtualMCPServerobjects keep a stored 10. - Orphan comment in
extractSource, stalenolintreason onAuditEvent, and the splitWorkflowAuditordoc comment are fixed. - Test findings are fixed: the stdout subtest is renamed to match what it asserts,
TestWithLogger_NilInputsandTestServer_AuditLoggerWithLogFileRejectedcover the nil inputs and the vMCP rejection, the shared request, handler and workflow helpers are reused, and the two source tests are one table.
How to test
task testforpkg/auditandpkg/vmcp/servershould pass.- Break the rejection path: remove the
LogFilecheck inauditLoggerForand confirmTestServer_AuditLoggerWithLogFileRejectedandTestAuditor_WithLoggerAndLogFileRejectedfail. - Break the source rule: restore the
X-Forwarded-Forread ingetClientIPand confirm both cases ofTestAuditor_SourceIgnoresForwardedHeadersfail.
Reviewed by dev:review-pr (finders: correctness, documentation). Generated with Claude Code.
rdimitrov
left a comment
There was a problem hiding this comment.
The core alignment looks good: the type aliases, the golden fixture, WithLogger with the logFile conflict check, and the vMCP plumbing. Taking source.value from RemoteAddr alone also makes sense. One problem with the request-id half of the change, inline below.
| // | ||
| // X-Forwarded-For and X-Real-IP are never read: a client can set both, so they | ||
| // cannot be trusted as the source of an audit event. To find the original | ||
| // client, join the event's request id (metadata.extra.request_id) to the |
There was a problem hiding this comment.
This join can't work, now or after the planned follow-up. A proxy's access log holds the id the proxy generated and forwarded (nginx $request_id, Envoy x-request-id, and so on). An id that ToolHive generates behind the proxy never appears in that log. The only value both sides share is the incoming X-Request-ID header, and this PR stops recording it.
So for any deployment behind an ingress, which is the normal operator setup, this PR removes both ways to trace an audit event back to the client: source.value becomes the ingress address, and source.extra.request_id is gone. Before, at least the proxy-set request id survived.
Dropping the header isn't needed to follow core, either. toolhive-core's audit package docs (doc.go, the request-id paragraph) say a component may still record the client's X-Request-ID in its source extra keys, as the client's claim, kept apart from metadata.extra.request_id. That is how this package already treats user_agent, which is equally client-chosen and still recorded.
Suggest keeping source.extra.request_id from the header, marked as client-asserted in docs/middleware.md. Keep metadata.extra.request_id for the context id as this PR does. Then fix this comment and the matching source.value text in docs/middleware.md to say the join key is source.extra.request_id.
pkg/audit kept its own copy of the toolhive-core audit event types, and the copy had already drifted: it logged delegation before target, where core logs it last. An event built here could not be passed to toolhive-core code without a conversion. AuditEvent, EventMetadata and EventSource are now aliases of the toolhive-core types. NewAuditEvent and the outcome, source type and component constants delegate to core. OutcomeApplicationError stays a ToolHive constant. A golden fixture captured from the old type pins that the logged record is unchanged apart from key order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
With maxDelegationDepth unset, the auditors recorded delegation chains up to 10 hops, ToolHive's own minting cap, while toolhive-core and its other adopters record up to 16. The same token produced a different audit record depending on which library wrote it. The audit default is now toolhive-core's DefaultMaxDelegationDepth (16), in MaxDelegationDepthOrDefault and in the kubebuilder default, with the CRDs, CRD API docs and OpenAPI/SDK output regenerated. auth.DefaultMaxDelegationDepth, the cap ToolHive mints and parses identities at, stays 10. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
Both auditors built their own logger on stdout or the log file, with no way to pass a caller's *slog.Logger, so a program embedding ToolHive could not route ToolHive's audit events through its own audit handler. Their lines also carried no marker a log pipeline could select them by. A WithLogger option on NewAuditorWithTransport and NewWorkflowAuditor makes the auditor log every event to the caller's logger at LevelAudit. The auditor then owns no writer, and a config that also sets logFile fails construction with an error naming both, before any file is opened. Without the option, each auditor builds its logger with toolhive-core's audit.HandlerMiddleware, so every line carries level AUDIT and logger=audit. The vMCP gains AuditLogger on server.Config, server.ServerConfig and core.Config, passed to the request auditor and the workflow auditor, so an embedder of the vMCP server reaches the option without building either auditor itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
The Auditor recorded the event source from X-Forwarded-For, then X-Real-IP, and copied the client's X-Request-ID into source.extra.request_id. A client can set all three headers, so it could choose the source address and the request id written to the audit trail. The source is now the connection's remote address only. The request id is never read from the request: both auditors record the id the context carries, set with toolhive-core's ContextWithRequestID, as metadata.extra.request_id. The Auditor logs with the context it was given, so the embedder sets the id in a middleware that wraps it, and the id also lands on events for requests an inner middleware refused. Workflow and step events carry the id of the context they are logged with. Behind a proxy the source is now the proxy's address; the request id joins the event to the proxy's access log, which holds the client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
The audit logger option and the logger=audit marker cover the request and workflow auditors only; the OBO token-exchange events keep their own logger. Say so, note that ToolHive sets no request id itself, and that existing VirtualMCPServer objects keep a stored depth of 10. Addresses #7486 review comments: - MEDIUM pkg/vmcp/server/server.go:243 (4793338242): scope AuditLogger, WithLogger and docs to the auditors, document OBO events - LOW pkg/audit/auditor.go:776 (4793338249): document that ToolHive sets no request id - LOW pkg/audit/config.go:61 (4793338254): document the stored depth of existing objects - LOW pkg/audit/auditor.go:503 (4793338262): drop the orphan comment - LOW pkg/audit/event.go:17 (4793338268): reword the nolint reason - LOW pkg/audit/workflow_auditor.go:22 (4793338304): keep the type summary together Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
Cover the nil inputs of WithLogger and the vMCP rejection of an audit logger with a log file, name the stdout subtest after what it asserts, and reuse the shared request, handler and workflow helpers. Addresses #7486 review comments: - LOW pkg/audit/options_test.go:156 (4793338277): rename the stdout subtest - LOW pkg/audit/options_test.go:159 (4793338284): test nil logger, nil config and the vMCP rejection - LOW pkg/audit/options_test.go:55 (4793338292): reuse request, handler and workflow helpers - LOW pkg/audit/source_test.go:87 (4793338298): merge the source tests into a table Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Trey <tgrunnagle@gmail.com>
948782d to
c8beb25
Compare
Summary
ToolHive keeps its own copy of the audit event types, writes audit lines through a logger it builds itself, reads the event source and request id from client-supplied headers, and caps delegation chains at a different depth than toolhive-core. Programs that embed ToolHive cannot route its audit events through their own handler, and ToolHive's audit records differ from those of other toolhive-core users. This PR makes ToolHive's audit output follow toolhive-core and lets an embedder control where events go and which request id they carry.
audit.AuditEvent,audit.EventMetadataandaudit.EventSourceto the toolhive-core types, and haveNewAuditEventand the event constants delegate to core.OutcomeApplicationErrorstays local. The serialized event is unchanged apart from key order.maxDelegationDepthto toolhive-core'sDefaultMaxDelegationDepth(16) instead of 10, including the kubebuilder default on the CRD field.audit.WithLogger(*slog.Logger)option on both auditor constructors. Without it, the auditors write through toolhive-core'sHandlerMiddleware, so every line they write carries levelAUDITandlogger=audit. The OBO token-exchange events keep their own logger and are not covered by either. For vMCP, addAuditLoggertoserver.Config,server.ServerConfigandcore.Config.source.valuefrom the connection's remote address only, and take the request id from the request context (ContextWithRequestID) instead of theX-Request-IDheader.Type of change
Test plan
task test)task test-e2e)task lint-fix)task testexits 201 on one failure that is also present on the base:pkg/networking TestValidateCallbackPort/valid_port_with_client_ID("OAuth callback port 8090 is already in use"), caused by a local process holding the port. Every other package passes, includingpkg/audit,pkg/auth,pkg/vmcp/serverandpkg/vmcp/core.Verification run at the branch tip (
c8beb25b9, rebased onmain):task lint: exit 0, "0 issues." (golangci-lint),go vetcleantask operator-manifests && task crdref-gen && task docs: exit 0,git status --shortempty afterwards (no generated-file drift)task test: exit 201, only failurepkg/networking TestValidateCallbackPort/valid_port_with_client_ID("OAuth callback port 8090 is already in use"), also failing on the baseBehavior covered by new or changed tests:
TestAuditEvent_IsCoreTypeTestAuditEvent_SerializationMatchesGolden(pkg/audit/testdata/audit_event_golden.json)truncated: trueandomitted: 4:TestAuditor_DelegationDepthDefaultIsCoreWithLoggerreceives every event, including stream-open and all workflow and step events:TestAuditor_WithLoggerWritesThroughCallerLogger,TestWorkflowAuditor_WithLoggerWritesThroughCallerLoggerAUDITandlogger=audit, to stdout or the log file:TestAuditor_DefaultLoggerStampsAuditMarkerlogFiletogether withWithLoggerfails construction and opens no file, in the auditors and in the vMCP:TestAuditor_WithLoggerAndLogFileRejected,TestServer_AuditLoggerWithLogFileRejectedWithLogger(nil)falls back to the default logger, and a nil config with a logger uses the logger:TestWithLogger_NilInputsAuditLoggerreaches both the request auditor and the workflow auditor:TestServer_AuditLoggerReachesBothAuditorsRemoteAddr192.0.2.7:4431withX-Forwarded-ForandX-Real-IPset givessource.value192.0.2.7, for normal and stream-open events:TestAuditor_SourceIgnoresForwardedHeadersmetadata.extra.request_id, including for a 401 written inside the auditor; a clientX-Request-IDheader is ignored; workflow and step events carry the context's request id:TestAuditor_RequestIDFromOuterMiddleware,TestAuditor_IgnoresClientRequestIDHeader,TestWorkflowAuditor_RequestIDFromContextTestGetClientIPandTestExtractSourceWithHeaderscases that asserted forwarded addresses or a header request id were changed to the new rule, not deleted.API Compatibility
v1beta1API, OR theapi-break-allowedlabel is applied and the migration guidance is described above.The only CRD change is the kubebuilder default of the audit config's
maxDelegationDepthas embedded in theVirtualMCPServerCRD (10 to 16). Changing a default is not a schema break: no field, type or validation changes. The regenerated CRD YAML,docs/operator/crd-api.md, and the swagger and SDK files are included.Changes
pkg/audit/event.goNewAuditEventand constantspkg/audit/config.gopkg/audit/options.goWithLoggeroption;Optionmoved here fromsubject_enricher.go; default logger built onHandlerMiddleware;logFileplusWithLoggerrejectedpkg/audit/auditor.go,workflow_auditor.go,mcp_events.gopkg/vmcp/server/{server,serve,derive}.go,pkg/vmcp/core/{core,core_vmcp}.goAuditLoggerfield on the three configs, passed to both auditors withaudit.WithLoggerdeploy/charts/operator-crds/**,docs/operator/crd-api.md,docs/server/**,sdk/go/**docs/middleware.mdpkg/audit/*_test.go,testdata/,pkg/vmcp/server/*_test.goDoes this introduce a user-facing change?
Yes. All four are described in
docs/middleware.md.loggerattribute.logger=auditand levelAUDIT, because their default logger is built on toolhive-core'sHandlerMiddleware. Consumers that match audit lines by shape should check for the marker. Theobo_token_exchangeevents are unchanged: levelAUDIT, nologgerkey.source.valuewas taken fromX-Forwarded-For, thenX-Real-IP, then the remote address.source.valueis always the remote address of the connection (the host part ofRemoteAddr). Behind a reverse proxy or load balancer it is the proxy's address, andX-Forwarded-ForandX-Real-IPare not read.source.extra.request_id.source.extra.request_idis not written. The request id appears only inmetadata.extra.request_id, and only when a middleware outside the auditor set it with toolhive-core'sContextWithRequestID. A client-suppliedX-Request-IDheader is ignored.thv, the proxy runner and the vMCP set no request id themselves, so their events carry none.maxDelegationDepthunset, at most 10acthops were recorded and longer chains were marked truncated.truncated: trueandomitted: 4. Explicitly configured values are unaffected. The API server stores a CRD default when an object is written, so an existingVirtualMCPServerwith anauditblock keeps a stored 10 until the field is edited or removed.New Go API for embedders:
audit.WithLogger(*slog.Logger), andAuditLogger *slog.Loggeron vMCPserver.Config,server.ServerConfigandcore.Config. It is set from Go only, has no effect whenAuditConfigis nil, and is rejected together withAuditConfig.LogFile.Special notes for reviewers
X-Forwarded-ForandX-Real-IP, so the audit record uses the one address the server itself observed. Deployments behind a proxy get the proxy's address assource.value. Since ToolHive sets no request id itself, those deployments have no join key to the proxy's access log either; a middleware that generates a server-side id ahead of the audit middleware is a follow-up.auth.DefaultMaxDelegationDepth(10), which is unchanged. With the default, every recorded chain longer than 10 hops, and so every truncated chain, was not minted by ToolHive. A configuredmaxDelegationDepthof 10 or less removes that signal.DefaultConfig()leavesMaxDelegationDepthnil. Nil already resolves to 16 throughMaxDelegationDepthOrDefault. Setting a pointer inDefaultConfig()would be persisted into the run configs built from it and freeze the value.audit.NewAuditLogger, which stays toolhive-core's logger: their lines carry nologger=audit, are not routed byWithLoggerorAuditLogger, and carry no request id. RoutingNewAuditLoggerthrough the handler middleware would change the output the golden-fixture test pins.logFileandWithLoggerare mutually exclusive. The logger decides where events go, so a config that sets both fails at construction, before any file is opened. WithWithLogger,Closereleases nothing.slog.Erroron a log-file open failure before returning the error; the error is wrapped asfailed to create audit logger: ..., so the failure is reported once.TestAuditEvent_IsCoreTypeuses typed function signatures rather thanvar x core.T = local, becauserevive's var-declaration rule strips the explicit type in the latter and would void the compile-time identity check.🤖 Generated with Claude Code