Skip to content

Let embedders control the audit logger, source, request id - #7486

Open
tgrunnagle wants to merge 7 commits into
mainfrom
tgrunnagle/audit-caller-logger-source
Open

tgrunnagle wants to merge 7 commits into
mainfrom
tgrunnagle/audit-caller-logger-source

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Stacked PR. This depends on #7485 (the toolhive-core v0.0.64 bump) and is opened against that PR's branch. It will be retargeted to main after #7485 merges. Only the commits after the bump (ea8a55594..HEAD) belong to this PR.

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.

  • Alias audit.AuditEvent, audit.EventMetadata and audit.EventSource to the toolhive-core types, and have NewAuditEvent and the event constants delegate to core. OutcomeApplicationError stays local. The serialized event is unchanged apart from key order.
  • Default maxDelegationDepth to toolhive-core's DefaultMaxDelegationDepth (16) instead of 10, including the kubebuilder default on the CRD field.
  • Add an audit.WithLogger(*slog.Logger) option on both auditor constructors. Without it, the auditors write through toolhive-core's HandlerMiddleware, so every line they write carries level AUDIT and logger=audit. The OBO token-exchange events keep their own logger and are not covered by either. For vMCP, add AuditLogger to server.Config, server.ServerConfig and core.Config.
  • Take source.value from the connection's remote address only, and take the request id from the request context (ContextWithRequestID) instead of the X-Request-ID header.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

task test exits 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, including pkg/audit, pkg/auth, pkg/vmcp/server and pkg/vmcp/core.

Verification run at 94d9f0f9f (the later commits change tests, comments and docs/middleware.md only, and were checked with task lint-fix and the pkg/audit, pkg/vmcp/server and pkg/vmcp/core tests):

  • task lint: exit 0, "0 issues." (golangci-lint), go vet clean
  • task operator-manifests && task crdref-gen && task docs: exit 0, git status --short empty afterwards (no generated-file drift)
  • task test: exit 201, only failure pkg/networking TestValidateCallbackPort/valid_port_with_client_ID ("OAuth callback port 8090 is already in use"), also failing on the base

Behavior covered by new or changed tests:

  • Event types are identical to core's: TestAuditEvent_IsCoreType
  • Serialized event matches a golden fixture captured from the old type before the change: TestAuditEvent_SerializationMatchesGolden (pkg/audit/testdata/audit_event_golden.json)
  • 12 hops recorded in full, 20 hops recorded as 16 with truncated: true and omitted: 4: TestAuditor_DelegationDepthDefaultIsCore
  • WithLogger receives every event, including stream-open and all workflow and step events: TestAuditor_WithLoggerWritesThroughCallerLogger, TestWorkflowAuditor_WithLoggerWritesThroughCallerLogger
  • Default logger stamps level AUDIT and logger=audit, to stdout or the log file: TestAuditor_DefaultLoggerStampsAuditMarker
  • logFile together with WithLogger fails construction and opens no file, in the auditors and in the vMCP: TestAuditor_WithLoggerAndLogFileRejected, TestServer_AuditLoggerWithLogFileRejected
  • WithLogger(nil) falls back to the default logger, and a nil config with a logger uses the logger: TestWithLogger_NilInputs
  • vMCP AuditLogger reaches both the request auditor and the workflow auditor: TestServer_AuditLoggerReachesBothAuditors
  • RemoteAddr 192.0.2.7:4431 with X-Forwarded-For and X-Real-IP set gives source.value 192.0.2.7, for normal and stream-open events: TestAuditor_SourceIgnoresForwardedHeaders
  • Request id from an outer middleware reaches metadata.extra.request_id, including for a 401 written inside the auditor; a client X-Request-ID header is ignored; workflow and step events carry the context's request id: TestAuditor_RequestIDFromOuterMiddleware, TestAuditor_IgnoresClientRequestIDHeader, TestWorkflowAuditor_RequestIDFromContext
  • Existing TestGetClientIP and TestExtractSourceWithHeaders cases that asserted forwarded addresses or a header request id were changed to the new rule, not deleted.

API Compatibility

  • This PR does not break the v1beta1 API, OR the api-break-allowed label is applied and the migration guidance is described above.

The only CRD change is the kubebuilder default of the audit config's maxDelegationDepth as embedded in the VirtualMCPServer CRD (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

File Change
pkg/audit/event.go Replace the forked event types with aliases of toolhive-core's; delegate NewAuditEvent and constants
pkg/audit/config.go Delegation depth default and kubebuilder default now 16
pkg/audit/options.go New WithLogger option; Option moved here from subject_enricher.go; default logger built on HandlerMiddleware; logFile plus WithLogger rejected
pkg/audit/auditor.go, workflow_auditor.go, mcp_events.go Use the shared logger construction; source from remote address only; request id from context
pkg/vmcp/server/{server,serve,derive}.go, pkg/vmcp/core/{core,core_vmcp}.go AuditLogger field on the three configs, passed to both auditors with audit.WithLogger
deploy/charts/operator-crds/**, docs/operator/crd-api.md, docs/server/**, sdk/go/** Regenerated for the new default
docs/middleware.md Document the log format (and that OBO token-exchange events are not marked or routed), embedder-supplied logger, source rule, request id rule and depth default
pkg/audit/*_test.go, testdata/, pkg/vmcp/server/*_test.go New and updated tests listed above

Does this introduce a user-facing change?

Yes. All four are described in docs/middleware.md.

  1. Audit log lines are marked.
    • Before: lines written by the default logger had no logger attribute.
    • After: every line of the audit middleware and the workflow auditor carries logger=audit and level AUDIT, because their default logger is built on toolhive-core's HandlerMiddleware. Consumers that match audit lines by shape should check for the marker. The obo_token_exchange events are unchanged: level AUDIT, no logger key.
  2. Event source behind a proxy.
    • Before: source.value was taken from X-Forwarded-For, then X-Real-IP, then the remote address.
    • After: source.value is always the remote address of the connection (the host part of RemoteAddr). Behind a reverse proxy or load balancer it is the proxy's address, and X-Forwarded-For and X-Real-IP are not read.
  3. Request id.
    • Before: a request id from the request headers was written to source.extra.request_id.
    • After: source.extra.request_id is not written. The request id appears only in metadata.extra.request_id, and only when a middleware outside the auditor set it with toolhive-core's ContextWithRequestID. A client-supplied X-Request-ID header is ignored. thv, the proxy runner and the vMCP set no request id themselves, so their events carry none.
  4. Default delegation depth.
    • Before: with maxDelegationDepth unset, at most 10 act hops were recorded and longer chains were marked truncated.
    • After: the default is 16 (CRD default 16). A 12-hop chain is recorded in full; a 20-hop chain is recorded as 16 hops with truncated: true and omitted: 4. Explicitly configured values are unaffected. The API server stores a CRD default when an object is written, so an existing VirtualMCPServer with an audit block keeps a stored 10 until the field is edited or removed.

New Go API for embedders: audit.WithLogger(*slog.Logger), and AuditLogger *slog.Logger on vMCP server.Config, server.ServerConfig and core.Config. It is set from Go only, has no effect when AuditConfig is nil, and is rejected together with AuditConfig.LogFile.

Special notes for reviewers

  • Source address is a deliberate trade-off. A client can set X-Forwarded-For and X-Real-IP, so the audit record uses the one address the server itself observed. Deployments behind a proxy get the proxy's address as source.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.
  • Delegation depth default and the signal it carries. The audit default (16) is now above ToolHive's own minting cap, 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 configured maxDelegationDepth of 10 or less removes that signal.
  • DefaultConfig() leaves MaxDelegationDepth nil. Nil already resolves to 16 through MaxDelegationDepthOrDefault. Setting a pointer in DefaultConfig() would be persisted into the run configs built from it and freeze the value.
  • OBO events are out of scope. The On-Behalf-Of middleware and the vMCP OBO strategy log through audit.NewAuditLogger, which stays toolhive-core's logger: their lines carry no logger=audit, are not routed by WithLogger or AuditLogger, and carry no request id. Routing NewAuditLogger through the handler middleware would change the output the golden-fixture test pins.
  • logFile and WithLogger are mutually exclusive. The logger decides where events go, so a config that sets both fails at construction, before any file is opened. With WithLogger, Close releases nothing.
  • Constructor error logging. The auditor constructor no longer logs slog.Error on a log-file open failure before returning the error; the error is wrapped as failed to create audit logger: ..., so the failure is reported once.
  • Test detail. TestAuditEvent_IsCoreType uses typed function signatures rather than var x core.T = local, because revive's var-declaration rule strips the explicit type in the latter and would void the compile-time identity check.
  • Dependencies. The toolhive-core, go-sdk and golang-jwt updates, and the related test and loopback-host fixes, are in Bump toolhive-core to v0.0.64 #7485 and not repeated here.

🤖 Generated with Claude Code

tgrunnagle and others added 5 commits December 3, 2026 15:19
v0.0.64 adds the audit handler middleware and the request id context
helpers that the audit package will build on. Its go.mod raises
several shared dependencies, among them go-sdk to v1.9.0 and
golang-jwt to v5.4.0.

go-sdk v1.9.0 matches the "localhost" Host case-insensitively in its
DNS-rebinding protection. The vMCP loopback Host guard mirrors that
rule so Legacy and Modern requests get the same decision, and its
parity test caught the drift. The guard now matches "localhost" in
any case too.

golang-jwt v5.4.0 appends the elapsed time to its expired-token error
("token is expired by 1m3s"), which reaches the error_description of
the 401 for an expired token. The expired-token admission test
compares two such 401s byte for byte and failed whenever a second
passed between them; it now ignores the elapsed time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Trey <tgrunnagle@gmail.com>
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>
@github-actions github-actions Bot added the size/XL Extra large PR: 1000+ lines changed label Dec 3, 2026

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 in pkg/auth/obo and pkg/vmcp/auth/strategies still use audit.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 with ContextWithRequestID. 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 test for pkg/audit, pkg/vmcp/server, and pkg/vmcp/core should pass. The pkg/networking callback-port failure the PR describes is unrelated.
  • Break the source rule: restore the X-Forwarded-For read in getClientIP and confirm TestAuditor_SourceIgnoresForwardedHeaders and TestAuditor_StreamOpenSourceIgnoresForwardedHeaders fail.
  • Break request-id stamping: remove the stampRequestID call in WorkflowAuditor.logEvent and confirm TestWorkflowAuditor_RequestIDFromContext fails.
  • Break the default logger: build the default logger with coreaudit.NewAuditLogger instead of HandlerMiddleware and confirm the logger=audit assertions in the log-file subtests of TestAuditor_DefaultLoggerStampsAuditMarker fail.
  • Run a vMCP with an OBO backend and an AuditLogger set, and check that the OBO exchange events do not reach it.

Documentation updates

  • Narrow the "every audit line carries logger=audit" wording in docs/middleware.md, or route the OBO events through the new logger.
  • Note that existing VirtualMCPServer objects keep a stored maxDelegationDepth of 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.

Comment thread pkg/vmcp/server/server.go Resolved
Comment thread pkg/audit/auditor.go Resolved
Comment thread pkg/audit/config.go Resolved
Comment thread pkg/audit/auditor.go Resolved
Comment thread pkg/audit/event.go Resolved
Comment thread pkg/audit/options_test.go Resolved
Comment thread pkg/audit/options_test.go Resolved
Comment thread pkg/audit/options_test.go Resolved
Comment thread pkg/audit/source_test.go Resolved
Comment thread pkg/audit/workflow_auditor.go Resolved
@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.22642% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.06%. Comparing base (ea8a555) to head (948782d).
⚠️ Report is 1 commits behind head on tgrunnagle/bump-toolhive-core-0.0.64.

Files with missing lines Patch % Lines
pkg/audit/auditor.go 92.85% 1 Missing ⚠️
pkg/audit/options.go 93.75% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

tgrunnagle and others added 2 commits December 3, 2026 16:29
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>
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Dec 4, 2026
@tgrunnagle
tgrunnagle marked this pull request as ready for review December 4, 2026 01:24

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  • AuditLogger and the docs claimed every audit event is routed and marked, but OBO events are not (pkg/vmcp/server/server.go): AuditLogger, audit.WithLogger, audit.NewAuditLogger and docs/middleware.md now say they cover the request and workflow auditors only, and that obo_token_exchange events go to stdout at level AUDIT with no logger key and no request id.
  • Request id is never set by ToolHive (pkg/audit/auditor.go): docs/middleware.md and the PR body now say thv, 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.md and the PR body now say existing VirtualMCPServer objects keep a stored 10.
  • Orphan comment in extractSource, stale nolint reason on AuditEvent, and the split WorkflowAuditor doc comment are fixed.
  • Test findings are fixed: the stdout subtest is renamed to match what it asserts, TestWithLogger_NilInputs and TestServer_AuditLoggerWithLogFileRejected cover 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 test for pkg/audit and pkg/vmcp/server should pass.
  • Break the rejection path: remove the LogFile check in auditLoggerFor and confirm TestServer_AuditLoggerWithLogFileRejected and TestAuditor_WithLoggerAndLogFileRejected fail.
  • Break the source rule: restore the X-Forwarded-For read in getClientIP and confirm both cases of TestAuditor_SourceIgnoresForwardedHeaders fail.

Reviewed by dev:review-pr (finders: correctness, documentation). Generated with Claude Code.

Base automatically changed from tgrunnagle/bump-toolhive-core-0.0.64 to main December 4, 2026 07:56

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant