From 2d59788c1ca3573e008ca85ef0c583fa197da560 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 14:19:41 -0800 Subject: [PATCH 1/6] Alias audit event types to toolhive-core 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 Signed-off-by: Trey --- pkg/audit/event.go | 214 ++------------------- pkg/audit/event_golden_test.go | 115 +++++++++++ pkg/audit/testdata/audit_event_golden.json | 55 ++++++ 3 files changed, 191 insertions(+), 193 deletions(-) create mode 100644 pkg/audit/event_golden_test.go create mode 100644 pkg/audit/testdata/audit_event_golden.json diff --git a/pkg/audit/event.go b/pkg/audit/event.go index 446248807b..c8d9950775 100644 --- a/pkg/audit/event.go +++ b/pkg/audit/event.go @@ -1,113 +1,29 @@ -// Package audit provides audit logging functionality for ToolHive. -// This package includes audit event structures and utilities based on -// the auditevent library from metal-toolbox/auditevent to ensure -// NIST SP 800-53 compliance. +// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + package audit import ( - "context" - "encoding/json" - "log/slog" - "time" - - "github.com/google/uuid" - coreaudit "github.com/stacklok/toolhive-core/audit" ) -// The following code is adapted from github.com/metal-toolbox/auditevent -// Original copyright notice: -/* -Copyright 2022 Equinix, Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// AuditEvent represents an audit event. -// It provides the minimal information needed to audit an event, as well as -// a uniform format to persist the events in audit logs. +// AuditEvent represents an audit event. It is the toolhive-core audit event +// type, so a value built here can be passed to toolhive-core and back without +// conversion. // // It is highly recommended to use the NewAuditEvent function to create // audit events and set the required fields. // //nolint:revive // AuditEvent name is intentional for compatibility with auditevent library -type AuditEvent struct { - Metadata EventMetadata `json:"metadata"` - // Type: Defines the type of event that occurred - // This is a small identifier to quickly determine what happened. - // e.g. UserLogin, UserLogout, UserCreate, UserDelete, etc. - Type string `json:"type"` - // LoggedAt: determines when the event occurred. - // Note that this should have sufficient information to authoritatively - // determine the exact time the event was logged at. The output must be in - // Coordinated Universal Time (UTC) format, a modern continuation of - // Greenwich Mean Time (GMT), or local time with an offset from UTC to satisfy - // NIST SP 800-53 requirement AU-8. - LoggedAt time.Time `json:"loggedAt"` - // Source: determines the source of the event. - // Normally, using the IP address of the client, or pod name is sufficient. - // One must be careful of the data that's added here as we don't want to - // leak Personally Identifiable Information. - Source EventSource `json:"source"` - // Outcome: determines whether the event was successful or not, e.g. successful login - // It may also determine if the event was approved or denied. - Outcome string `json:"outcome"` - // Subject: is the identity of the subject of the event. - // e.g. who triggered the event? Additional information - // may be added, such as group membership and/or role - Subjects map[string]string `json:"subjects"` - // DelegationChain: when the caller authenticated with an RFC 8693 - // delegated token, this records the full chain of acting parties - // (outermost/most recent first) extracted from the token's "act" claim. - // The type and the "delegation" wire key are toolhive-core's canonical - // delegation-chain schema. - DelegationChain *coreaudit.DelegationChain `json:"delegation,omitempty"` - // Component: allows to determine in which component the event occurred - // (Answering the "Where" question of section c in the NIST SP 800-53 - // Revision 5.1 Control AU-3). - Component string `json:"component"` - // Target: Defines where the target of the operation. e.g. the path of - // the REST resource - // (Answering the "Where" question of section c in the NIST SP 800-53 - // Revision 5.1 Control AU-3 as well as indicating an entity - // associated for section f). - Target map[string]string `json:"target,omitempty"` - // Data: enhances the audit event with extra information that may be - // useful for forensic analysis. - Data *json.RawMessage `json:"data,omitempty"` -} +type AuditEvent = coreaudit.AuditEvent -// EventMetadata contains metadata about the audit event. -type EventMetadata struct { - // AuditID: is a unique identifier for the audit event. - AuditID string `json:"auditId"` - // Extra allows for including additional information about the event - // that aids in tracking, parsing or auditing - Extra map[string]any `json:"extra,omitempty"` -} +// EventMetadata contains metadata about the audit event. It is the +// toolhive-core type. +type EventMetadata = coreaudit.EventMetadata -// EventSource represents the source of an audit event. -type EventSource struct { - // Type indicates the source type. e.g. Network, File, local, etc. - // The intent is to determine where a request came from. - Type string `json:"type"` - // Value aims to indicate the source of the event. e.g. IP address, - // hostname, etc. - Value string `json:"value"` - // Extra allows for including additional information about the event - // source that aids in tracking, parsing or auditing - Extra map[string]any `json:"extra,omitempty"` -} +// EventSource represents the source of an audit event. It is the +// toolhive-core type. +type EventSource = coreaudit.EventSource // NewAuditEvent returns a new AuditEvent with an appropriately set AuditID and logging time. func NewAuditEvent( @@ -117,107 +33,19 @@ func NewAuditEvent( subjects map[string]string, component string, ) *AuditEvent { - return &AuditEvent{ - Metadata: EventMetadata{ - AuditID: uuid.New().String(), - }, - Type: eventType, - LoggedAt: time.Now().UTC(), - Source: source, - Outcome: outcome, - Subjects: subjects, - Component: component, - } -} - -// WithDelegationChain sets the RFC 8693 delegation chain of the event. -// A nil or zero chain (no hops, no truncation, no malformation — see -// [coreaudit.DelegationChain.IsZero]) clears any previously set chain. A -// hopless but malformed chain is kept: "the caller asserted delegation we -// could not read" is audit-relevant and distinct from "no delegation". -func (e *AuditEvent) WithDelegationChain(chain *coreaudit.DelegationChain) *AuditEvent { - if chain.IsZero() { - e.DelegationChain = nil - return e - } - e.DelegationChain = chain - return e -} - -// WithTarget sets the target of the event. -func (e *AuditEvent) WithTarget(target map[string]string) *AuditEvent { - e.Target = target - return e -} - -// WithData sets the data of the event. -func (e *AuditEvent) WithData(data *json.RawMessage) *AuditEvent { - e.Data = data - return e -} - -// WithDataFromString sets the data of the event from a string. -// Note that validating that this is properly JSON-formatted -// is the responsibility of the caller. -func (e *AuditEvent) WithDataFromString(data string) *AuditEvent { - rawMsg := json.RawMessage(data) - return e.WithData(&rawMsg) -} - -// LogTo logs the audit event to the provided slog.Logger using the custom audit level. -func (e *AuditEvent) LogTo(ctx context.Context, logger *slog.Logger, level slog.Level) { - // Create slog attributes for the audit event - attrs := []slog.Attr{ - slog.String("audit_id", e.Metadata.AuditID), - slog.String("type", e.Type), - slog.Time("logged_at", e.LoggedAt), - slog.String("outcome", e.Outcome), - slog.String("component", e.Component), - slog.Group("source", - slog.String("type", e.Source.Type), - slog.String("value", e.Source.Value), - slog.Any("extra", e.Source.Extra), - ), - slog.Any("subjects", e.Subjects), - } - - // Add delegation chain if present and non-zero. The chain resolves through - // coreaudit's [log/slog.LogValuer] implementation, which mirrors its JSON - // shape (so the slog and JSON wire forms are structurally identical) and - // never exposes the per-hop in-memory extra claims (PII guard). - if !e.DelegationChain.IsZero() { - attrs = append(attrs, slog.Any("delegation", e.DelegationChain)) - } - - // Add target if present - if e.Target != nil { - attrs = append(attrs, slog.Any("target", e.Target)) - } - - // Add metadata extra if present - if e.Metadata.Extra != nil { - attrs = append(attrs, slog.Group("metadata", slog.Any("extra", e.Metadata.Extra))) - } - - // Add data if present - if e.Data != nil { - attrs = append(attrs, slog.Any("data", e.Data)) - } - - // Log with the specified level - logger.LogAttrs(ctx, level, "audit_event", attrs...) + return coreaudit.NewAuditEvent(eventType, source, outcome, subjects, component) } // Common event outcomes const ( // OutcomeSuccess indicates the event was successful - OutcomeSuccess = "success" + OutcomeSuccess = coreaudit.OutcomeSuccess // OutcomeFailure indicates the event failed - OutcomeFailure = "failure" + OutcomeFailure = coreaudit.OutcomeFailure // OutcomeError indicates the event resulted in an error - OutcomeError = "error" + OutcomeError = coreaudit.OutcomeError // OutcomeDenied indicates the event was denied (e.g., by authorization) - OutcomeDenied = "denied" + OutcomeDenied = coreaudit.OutcomeDenied // OutcomeApplicationError indicates the HTTP transport succeeded but the // JSON-RPC response body contained an application-level error (e.g., // expired tokens, backend failures, invalid parameters). @@ -227,9 +55,9 @@ const ( // Common source types const ( // SourceTypeNetwork indicates the event came from a network request - SourceTypeNetwork = "network" + SourceTypeNetwork = coreaudit.SourceTypeNetwork // SourceTypeLocal indicates the event came from a local source - SourceTypeLocal = "local" + SourceTypeLocal = coreaudit.SourceTypeLocal ) // Component name for ToolHive @@ -237,5 +65,5 @@ const ( // ComponentToolHive is the component name for ToolHive API audit events. // Note that events directed for an MCP server will have the name of the // MCP server as the component instead. - ComponentToolHive = "toolhive-api" + ComponentToolHive = coreaudit.ComponentToolHive ) diff --git a/pkg/audit/event_golden_test.go b/pkg/audit/event_golden_test.go new file mode 100644 index 0000000000..a210e93d4f --- /dev/null +++ b/pkg/audit/event_golden_test.go @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package audit + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + + coreaudit "github.com/stacklok/toolhive-core/audit" +) + +// goldenEventFixture is the audit record of goldenEvent, captured from the +// AuditEvent type this package defined before it became an alias of the +// toolhive-core type. +const goldenEventFixture = "testdata/audit_event_golden.json" + +// goldenEvent returns an event with every field set to a fixed value. +func goldenEvent() *AuditEvent { + data := json.RawMessage(`{"request":{"location":"New York"},"response":{"temperature":"22C"}}`) + return &AuditEvent{ + Metadata: EventMetadata{ + AuditID: "01be8d47-3ab0-4aa9-ad14-bd5bb408005d", + Extra: map[string]any{ + MetadataExtraKeyDuration: 150, + MetadataExtraKeyTransport: "http", + }, + }, + Type: EventTypeMCPToolCall, + LoggedAt: time.Date(2025, 12, 15, 10, 38, 32, 164124000, time.UTC), + Source: EventSource{ + Type: SourceTypeNetwork, + Value: "192.0.2.7", + Extra: map[string]any{SourceExtraKeyUserAgent: "mcp-client/1.0"}, + }, + Outcome: OutcomeSuccess, + Subjects: map[string]string{ + SubjectKeyUser: "jane.doe@example.com", + SubjectKeyUserID: "user-123", + }, + Component: "example-server", + Target: map[string]string{ + TargetKeyEndpoint: "/mcp", + TargetKeyMethod: "tools/call", + TargetKeyType: TargetTypeTool, + TargetKeyName: "weather", + }, + Data: &data, + DelegationChain: &coreaudit.DelegationChain{ + Chain: []coreaudit.DelegatedActor{ + {Issuer: "https://auth.example.com", Subject: "agent-1"}, + {Subject: "agent-2"}, + }, + Truncated: true, + Omitted: 1, + Malformed: true, + MalformedReason: coreaudit.MalformedReasonSubNotString, + }, + } +} + +// decodeAuditRecord decodes one audit log line, dropping the slog time key, +// which is the wall clock of the write rather than part of the event. +func decodeAuditRecord(t *testing.T, line []byte) map[string]any { + t.Helper() + var record map[string]any + require.NoError(t, json.Unmarshal(line, &record)) + delete(record, "time") + return record +} + +// TestAuditEvent_SerializationMatchesGolden pins the audit record shape: an +// event with every field set, logged through NewAuditLogger, decodes to the +// same JSON object as the fixture. Only the order of keys may differ. +func TestAuditEvent_SerializationMatchesGolden(t *testing.T) { + t.Parallel() + + var buf bytes.Buffer + goldenEvent().LogTo(context.Background(), NewAuditLogger(&buf), LevelAudit) + + want, err := os.ReadFile(filepath.Clean(goldenEventFixture)) + require.NoError(t, err) + require.Equal(t, decodeAuditRecord(t, want), decodeAuditRecord(t, buf.Bytes())) +} + +// TestAuditEvent_IsCoreType pins that the event types are the toolhive-core +// types. Two separately defined struct types are never assignable to each +// other, so these conversion-free calls compile only while each pair is one +// type. +func TestAuditEvent_IsCoreType(t *testing.T) { + t.Parallel() + + toCore := func(e AuditEvent, m EventMetadata, s EventSource) ( + coreaudit.AuditEvent, coreaudit.EventMetadata, coreaudit.EventSource, + ) { + return e, m, s + } + fromCore := func(e coreaudit.AuditEvent, m coreaudit.EventMetadata, s coreaudit.EventSource) ( + AuditEvent, EventMetadata, EventSource, + ) { + return e, m, s + } + + event, metadata, source := fromCore(toCore(*goldenEvent(), EventMetadata{AuditID: "id"}, EventSource{Value: "v"})) + require.Equal(t, goldenEvent().Metadata.AuditID, event.Metadata.AuditID) + require.Equal(t, "id", metadata.AuditID) + require.Equal(t, "v", source.Value) +} diff --git a/pkg/audit/testdata/audit_event_golden.json b/pkg/audit/testdata/audit_event_golden.json new file mode 100644 index 0000000000..ead3abe5cc --- /dev/null +++ b/pkg/audit/testdata/audit_event_golden.json @@ -0,0 +1,55 @@ +{ + "level": "AUDIT", + "msg": "audit_event", + "audit_id": "01be8d47-3ab0-4aa9-ad14-bd5bb408005d", + "type": "mcp_tool_call", + "logged_at": "2025-12-15T10:38:32.164124Z", + "outcome": "success", + "component": "example-server", + "source": { + "type": "network", + "value": "192.0.2.7", + "extra": { + "user_agent": "mcp-client/1.0" + } + }, + "subjects": { + "user": "jane.doe@example.com", + "user_id": "user-123" + }, + "delegation": { + "chain": [ + { + "iss": "https://auth.example.com", + "sub": "agent-1" + }, + { + "sub": "agent-2" + } + ], + "truncated": true, + "omitted": 1, + "malformed": true, + "malformedReason": "sub_not_string" + }, + "target": { + "endpoint": "/mcp", + "method": "tools/call", + "name": "weather", + "type": "tool" + }, + "metadata": { + "extra": { + "duration_ms": 150, + "transport": "http" + } + }, + "data": { + "request": { + "location": "New York" + }, + "response": { + "temperature": "22C" + } + } +} From d855eba9c59398995048ebeb8e3d390366d3a892 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 14:32:54 -0800 Subject: [PATCH 2/6] Use toolhive-core's audit delegation depth default 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 Signed-off-by: Trey --- ...olhive.stacklok.dev_virtualmcpservers.yaml | 8 +-- ...olhive.stacklok.dev_virtualmcpservers.yaml | 8 +-- docs/middleware.md | 8 +-- docs/operator/crd-api.md | 2 +- docs/server/docs.go | 2 +- docs/server/swagger.json | 2 +- docs/server/swagger.yaml | 4 +- pkg/audit/auditor.go | 2 +- pkg/audit/auditor_test.go | 54 +++++++++++++++++++ pkg/audit/config.go | 27 ++++++---- pkg/audit/config_test.go | 10 ++-- sdk/go/client/oas_schemas_gen.go | 4 +- sdk/go/openapi.json | 2 +- sdk/go/openapi.yaml | 4 +- 14 files changed, 100 insertions(+), 37 deletions(-) diff --git a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml index 75e7b9010c..cc279b60b9 100644 --- a/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/files/crds/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -3053,11 +3053,11 @@ spec: data included in audit logs (in bytes). type: integer maxDelegationDepth: - default: 10 + default: 16 description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. minimum: 1 type: integer type: object @@ -8908,11 +8908,11 @@ spec: data included in audit logs (in bytes). type: integer maxDelegationDepth: - default: 10 + default: 16 description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. minimum: 1 type: integer type: object diff --git a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml index ee4acab56b..988d1675e3 100644 --- a/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml +++ b/deploy/charts/operator-crds/templates/toolhive.stacklok.dev_virtualmcpservers.yaml @@ -3056,11 +3056,11 @@ spec: data included in audit logs (in bytes). type: integer maxDelegationDepth: - default: 10 + default: 16 description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. minimum: 1 type: integer type: object @@ -8911,11 +8911,11 @@ spec: data included in audit logs (in bytes). type: integer maxDelegationDepth: - default: 10 + default: 16 description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. minimum: 1 type: integer type: object diff --git a/docs/middleware.md b/docs/middleware.md index 1dde4fc021..d80ee24cd9 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -760,9 +760,11 @@ Audit events are logged as structured JSON objects: (data minimization per RFC 8693 §6); per OpenID Connect Core §5.7 the (`iss`, `sub`) pair is the stable actor identifier - `truncated`: `true` when the chain exceeded the configured maximum depth - (`maxDelegationDepth` in the audit config, default 10) and inner hops - were dropped; the outermost hops — including `chain[0]`, the current - actor — are always kept. Always present + (`maxDelegationDepth` in the audit config, default 16, toolhive-core's + default) and inner hops were dropped; the outermost hops — including + `chain[0]`, the current actor — are always kept. Always present. The + default is above ToolHive's own minting cap of 10 hops, so a recorded + chain longer than 10 hops was not minted by ToolHive - `omitted`: Number of well-formed hops dropped due to the depth cap. Always present; `0` when nothing was dropped - `malformed`: `true` when the token's `act` claim violated RFC 8693 diff --git a/docs/operator/crd-api.md b/docs/operator/crd-api.md index 8813d65464..de643fc426 100644 --- a/docs/operator/crd-api.md +++ b/docs/operator/crd-api.md @@ -44,7 +44,7 @@ _Appears in:_ | `includeResponseData` _boolean_ | IncludeResponseData determines whether to include response data in audit logs. | false | Optional: \{\}
| | `detectApplicationErrors` _boolean_ | DetectApplicationErrors controls whether the audit middleware inspects
JSON-RPC response bodies for application-level errors when the HTTP
status code indicates success (2xx). When enabled, a small prefix of
the response body is buffered to detect JSON-RPC error fields,
independent of the IncludeResponseData setting. | true | Optional: \{\}
| | `maxDataSize` _integer_ | MaxDataSize limits the size of request/response data included in audit logs (in bytes). | 1024 | Optional: \{\}
| -| `maxDelegationDepth` _integer_ | MaxDelegationDepth caps how many nested RFC 8693 "act" entries are
recorded in an audit event's delegation chain. Deeper chains are
truncated (marked with truncated=true). Defaults to 10 when unset. | 10 | Minimum: 1
Optional: \{\}
| +| `maxDelegationDepth` _integer_ | MaxDelegationDepth caps how many nested RFC 8693 "act" entries are
recorded in an audit event's delegation chain. Deeper chains are
truncated (marked with truncated=true). Defaults to 16 when unset. | 16 | Minimum: 1
Optional: \{\}
| | `logFile` _string_ | LogFile specifies the file path for audit logs. If empty, logs to stdout. | | Optional: \{\}
| diff --git a/docs/server/docs.go b/docs/server/docs.go index 5bf367ffae..a1fa6fb0ee 100644 --- a/docs/server/docs.go +++ b/docs/server/docs.go @@ -56,7 +56,7 @@ const docTemplate = `{ "type": "integer" }, "maxDelegationDepth": { - "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 16 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=16\n+optional", "type": "integer" } }, diff --git a/docs/server/swagger.json b/docs/server/swagger.json index 8499e403a0..42b046bb83 100644 --- a/docs/server/swagger.json +++ b/docs/server/swagger.json @@ -49,7 +49,7 @@ "type": "integer" }, "maxDelegationDepth": { - "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 16 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=16\n+optional", "type": "integer" } }, diff --git a/docs/server/swagger.yaml b/docs/server/swagger.yaml index 9765176000..e880052ba3 100644 --- a/docs/server/swagger.yaml +++ b/docs/server/swagger.yaml @@ -71,9 +71,9 @@ components: description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. +kubebuilder:validation:Minimum=1 - +kubebuilder:default=10 + +kubebuilder:default=16 +optional type: integer type: object diff --git a/pkg/audit/auditor.go b/pkg/audit/auditor.go index 23cc39b061..6c625ddd47 100644 --- a/pkg/audit/auditor.go +++ b/pkg/audit/auditor.go @@ -592,7 +592,7 @@ func extractDelegationChainFromIdentity(identity *auth.Identity, maxDepth int) * // dropped by this re-binding. func rebindDelegationChain(chain *coreaudit.DelegationChain, maxDepth int) *coreaudit.DelegationChain { if maxDepth <= 0 { - maxDepth = auth.DefaultMaxDelegationDepth + maxDepth = coreaudit.DefaultMaxDelegationDepth } bound := *chain if len(bound.Chain) > maxDepth { diff --git a/pkg/audit/auditor_test.go b/pkg/audit/auditor_test.go index eec4e4a878..61ac723057 100644 --- a/pkg/audit/auditor_test.go +++ b/pkg/audit/auditor_test.go @@ -2024,3 +2024,57 @@ func TestAddMetadataAdmittedAfterExpiry(t *testing.T) { }) } } + +// TestAuditor_DelegationDepthDefaultIsCore pins that, with maxDelegationDepth +// unset, the Auditor records delegation chains up to toolhive-core's default +// depth (16), not ToolHive's minting cap (10) the identity layer parses at. +func TestAuditor_DelegationDepthDefaultIsCore(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + hops int + wantHops int + wantTruncated bool + wantOmitted int + }{ + {name: "12-hop chain is recorded in full", hops: 12, wantHops: 12}, + {name: "20-hop chain is cut at 16", hops: 20, wantHops: 16, wantTruncated: true, wantOmitted: 4}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + subs := make([]string, tt.hops) + for i := range subs { + subs[i] = fmt.Sprintf("agent-%d", i+1) + } + act := nestedActClaim(subs...) + // Shaped like auth.claimsToIdentity's output: the identity layer + // parses at ToolHive's minting cap and keeps the raw claim. + identity := &auth.Identity{PrincipalInfo: auth.PrincipalInfo{ + Subject: "user-123", + Claims: map[string]any{"act": act}, + DelegationChain: coreaudit.ParseDelegationChain(act, auth.DefaultMaxDelegationDepth), + }} + + auditor, logBuf := newBufferAuditor(t) + handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }) + req := newToolsCallRequest() + req = req.WithContext(auth.WithIdentity(req.Context(), identity)) + auditor.Middleware(handler).ServeHTTP(httptest.NewRecorder(), req) + + events := decodeAuditEvents(t, logBuf) + require.Len(t, events, 1) + chain, ok := events[0]["delegation"].(map[string]any) + require.True(t, ok, "event must carry the delegation chain") + hops, ok := chain["chain"].([]any) + require.True(t, ok) + assert.Len(t, hops, tt.wantHops) + assert.Equal(t, tt.wantTruncated, chain["truncated"]) + assert.Equal(t, float64(tt.wantOmitted), chain["omitted"]) + }) + } +} diff --git a/pkg/audit/config.go b/pkg/audit/config.go index 1717cb8e09..4894742b36 100644 --- a/pkg/audit/config.go +++ b/pkg/audit/config.go @@ -12,7 +12,7 @@ import ( "os" "path/filepath" - "github.com/stacklok/toolhive/pkg/auth" + coreaudit "github.com/stacklok/toolhive-core/audit" ) // Config represents the audit logging configuration. @@ -56,9 +56,9 @@ type Config struct { MaxDataSize int `json:"maxDataSize,omitempty" yaml:"maxDataSize,omitempty"` // MaxDelegationDepth caps how many nested RFC 8693 "act" entries are // recorded in an audit event's delegation chain. Deeper chains are - // truncated (marked with truncated=true). Defaults to 10 when unset. + // truncated (marked with truncated=true). Defaults to 16 when unset. // +kubebuilder:validation:Minimum=1 - // +kubebuilder:default=10 + // +kubebuilder:default=16 // +optional MaxDelegationDepth *int `json:"maxDelegationDepth,omitempty" yaml:"maxDelegationDepth,omitempty"` // LogFile specifies the file path for audit logs. If empty, logs to stdout. @@ -103,6 +103,11 @@ func DefaultConfig() *Config { IncludeResponseData: false, // Disabled by default for privacy MaxDataSize: 1024, // 1KB default limit DetectApplicationErrors: &detectErrors, // Enabled by default to surface JSON-RPC errors + // MaxDelegationDepth is deliberately left nil, unlike its kubebuilder + // default of 16: nil resolves to toolhive-core's + // audit.DefaultMaxDelegationDepth (16) through MaxDelegationDepthOrDefault. + // Setting a pointer here would be persisted into the run configs built + // from this default and freeze the value there. } } @@ -116,16 +121,18 @@ func (c *Config) ShouldDetectApplicationErrors() bool { } // MaxDelegationDepthOrDefault returns the configured cap on RFC 8693 -// delegation chain depth, or auth.DefaultMaxDelegationDepth (10) when unset -// or non-positive. +// delegation chain depth, or toolhive-core's audit.DefaultMaxDelegationDepth +// (16) when unset or non-positive. // -// The default is deliberately ToolHive's minting cap (10), NOT toolhive-core's -// audit.DefaultMaxDelegationDepth (16): core's value is a library-wide parse -// ceiling, while passing the mint cap here preserves the signal that a chain -// with truncated=true could not have come from ToolHive's own issuance path. +// The audit default is core's, so ToolHive's audit records match those of +// other toolhive-core adopters. It is higher than ToolHive's minting cap, +// auth.DefaultMaxDelegationDepth (10), so a recorded chain longer than 10 hops, +// and so every chain truncated at the default, could not have been minted by +// ToolHive's own issuance path. A configured MaxDelegationDepth of 10 or less +// removes that signal for truncated chains. func (c *Config) MaxDelegationDepthOrDefault() int { if c == nil || c.MaxDelegationDepth == nil || *c.MaxDelegationDepth <= 0 { - return auth.DefaultMaxDelegationDepth + return coreaudit.DefaultMaxDelegationDepth } return *c.MaxDelegationDepth } diff --git a/pkg/audit/config_test.go b/pkg/audit/config_test.go index cdd9064666..0603e72eb7 100644 --- a/pkg/audit/config_test.go +++ b/pkg/audit/config_test.go @@ -17,7 +17,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/stacklok/toolhive/pkg/auth" + coreaudit "github.com/stacklok/toolhive-core/audit" ) func TestDefaultConfig(t *testing.T) { @@ -490,10 +490,10 @@ func TestMaxDelegationDepthOrDefault(t *testing.T) { cfg *Config want int }{ - {name: "nil receiver", cfg: nil, want: auth.DefaultMaxDelegationDepth}, - {name: "nil MaxDelegationDepth field", cfg: &Config{}, want: auth.DefaultMaxDelegationDepth}, - {name: "zero MaxDelegationDepth", cfg: &Config{MaxDelegationDepth: depth(0)}, want: auth.DefaultMaxDelegationDepth}, - {name: "negative MaxDelegationDepth", cfg: &Config{MaxDelegationDepth: depth(-3)}, want: auth.DefaultMaxDelegationDepth}, + {name: "nil receiver", cfg: nil, want: coreaudit.DefaultMaxDelegationDepth}, + {name: "nil MaxDelegationDepth field", cfg: &Config{}, want: coreaudit.DefaultMaxDelegationDepth}, + {name: "zero MaxDelegationDepth", cfg: &Config{MaxDelegationDepth: depth(0)}, want: coreaudit.DefaultMaxDelegationDepth}, + {name: "negative MaxDelegationDepth", cfg: &Config{MaxDelegationDepth: depth(-3)}, want: coreaudit.DefaultMaxDelegationDepth}, {name: "positive MaxDelegationDepth is honored", cfg: &Config{MaxDelegationDepth: depth(5)}, want: 5}, } diff --git a/sdk/go/client/oas_schemas_gen.go b/sdk/go/client/oas_schemas_gen.go index c15a75c59c..aa09e367e5 100644 --- a/sdk/go/client/oas_schemas_gen.go +++ b/sdk/go/client/oas_schemas_gen.go @@ -68,9 +68,9 @@ type AuditConfig struct { MaxDataSize OptInt `json:"maxDataSize"` // MaxDelegationDepth caps how many nested RFC 8693 "act" entries are // recorded in an audit event's delegation chain. Deeper chains are - // truncated (marked with truncated=true). Defaults to 10 when unset. + // truncated (marked with truncated=true). Defaults to 16 when unset. // +kubebuilder:validation:Minimum=1 - // +kubebuilder:default=10 + // +kubebuilder:default=16 // +optional. MaxDelegationDepth OptInt `json:"maxDelegationDepth"` } diff --git a/sdk/go/openapi.json b/sdk/go/openapi.json index c5b3285fad..aa319f1f2f 100644 --- a/sdk/go/openapi.json +++ b/sdk/go/openapi.json @@ -49,7 +49,7 @@ "type": "integer" }, "maxDelegationDepth": { - "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 10 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=10\n+optional", + "description": "MaxDelegationDepth caps how many nested RFC 8693 \"act\" entries are\nrecorded in an audit event's delegation chain. Deeper chains are\ntruncated (marked with truncated=true). Defaults to 16 when unset.\n+kubebuilder:validation:Minimum=1\n+kubebuilder:default=16\n+optional", "type": "integer" } }, diff --git a/sdk/go/openapi.yaml b/sdk/go/openapi.yaml index 18a556bd45..64839703a3 100644 --- a/sdk/go/openapi.yaml +++ b/sdk/go/openapi.yaml @@ -71,9 +71,9 @@ components: description: |- MaxDelegationDepth caps how many nested RFC 8693 "act" entries are recorded in an audit event's delegation chain. Deeper chains are - truncated (marked with truncated=true). Defaults to 10 when unset. + truncated (marked with truncated=true). Defaults to 16 when unset. +kubebuilder:validation:Minimum=1 - +kubebuilder:default=10 + +kubebuilder:default=16 +optional type: integer type: object From c5c428a02bcf1bb5be88aa2c618017f379414f83 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 15:01:14 -0800 Subject: [PATCH 3/6] Let embedders supply the audit logger 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 Signed-off-by: Trey --- docs/middleware.md | 28 +++- pkg/audit/auditor.go | 32 ++--- pkg/audit/options.go | 77 +++++++++++ pkg/audit/options_test.go | 196 +++++++++++++++++++++++++++ pkg/audit/subject_enricher.go | 17 --- pkg/audit/workflow_auditor.go | 19 ++- pkg/vmcp/core/core.go | 10 +- pkg/vmcp/core/core_vmcp.go | 4 +- pkg/vmcp/server/audit_logger_test.go | 112 +++++++++++++++ pkg/vmcp/server/derive.go | 8 +- pkg/vmcp/server/derive_test.go | 11 ++ pkg/vmcp/server/serve.go | 10 +- pkg/vmcp/server/serve_test.go | 1 + pkg/vmcp/server/server.go | 9 ++ 14 files changed, 486 insertions(+), 48 deletions(-) create mode 100644 pkg/audit/options.go create mode 100644 pkg/audit/options_test.go create mode 100644 pkg/vmcp/server/audit_logger_test.go diff --git a/docs/middleware.md b/docs/middleware.md index d80ee24cd9..cfef701055 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -666,7 +666,13 @@ ToolHive installs no signal handler for this; the embedding program calls `Reope #### Log Output Format -Audit events are logged as structured JSON objects: +Audit events are logged as structured JSON objects, one per line. Each line +also carries `"level": "AUDIT"`, `"logger": "audit"`, `"msg": "audit_event"` +and a `time` key, which the example below leaves out; select audit records in +a log pipeline with `logger=audit`. The lines are written by toolhive-core's +audit handler middleware (`audit.HandlerMiddleware`), unless an embedder routes +the events through its own logger (see +[Embedder-supplied logger](#embedder-supplied-logger) below). ```json { @@ -834,6 +840,26 @@ cfg.AuditSubjectEnricher = func(ctx context.Context) map[string]string { supply them. - With no enricher set, events are unchanged. +#### Embedder-supplied logger + +A program that embeds ToolHive can route every audit event through its own +`*slog.Logger`, for example one whose handler is built with toolhive-core's +`audit.HandlerMiddleware`, so that ToolHive's audit events and its own reach +the same audit handler. Pass `audit.WithLogger(logger)` to +`audit.NewAuditorWithTransport` or `audit.NewWorkflowAuditor`, or, for the +vMCP, set `AuditLogger` on `server.Config`, or on both `server.ServerConfig` +and `core.Config` when it calls `core.New` and `server.Serve` directly. + +- It is set from Go only. It has no key in the audit configuration file. +- Every event, including the `sse_connection` event of a stream and every + composite-tool workflow and step event, is logged to it at + `audit.LevelAudit`. The logger's handler decides where the event is written + and how it is marked: ToolHive adds no `logger=audit` key of its own. +- The auditor then opens no log writer, so closing it releases nothing. +- An audit configuration that sets `logFile` is rejected when a logger is + given, and no file is opened: the logger decides where events go. +- On the vMCP it has no effect when `AuditConfig` is nil. + #### CLI Usage **With audit configuration file**: diff --git a/pkg/audit/auditor.go b/pkg/audit/auditor.go index 6c625ddd47..faa8bbab0e 100644 --- a/pkg/audit/auditor.go +++ b/pkg/audit/auditor.go @@ -8,6 +8,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "log/slog" "net" @@ -70,26 +71,22 @@ type Auditor struct { // NewAuditorWithTransport creates a new Auditor with the given configuration and transport information. // opts set behavior that is configured from Go rather than the serialized Config, -// such as WithSubjectEnricher. +// such as WithSubjectEnricher and WithLogger. +// +// Without WithLogger the auditor writes to stdout, or to config.LogFile, and +// every line carries level AUDIT and logger=audit. With WithLogger every event +// goes to the caller's logger, and a config that sets LogFile is rejected. func NewAuditorWithTransport(config *Config, transportType string, opts ...Option) (*Auditor, error) { - var logWriter io.Writer = os.Stdout // default to stdout - - if config != nil { - w, err := config.GetLogWriter() - if err != nil { - // Log error and fall back to stdout - slog.Error("failed to open audit log file, falling back to stdout", - "error", err) - return nil, err - } - logWriter = w - } - o := buildOptions(opts) + auditLogger, logWriter, err := auditLoggerFor(config, o.logger) + if err != nil { + return nil, fmt.Errorf("failed to create audit logger: %w", err) + } + return &Auditor{ config: config, - auditLogger: NewAuditLogger(logWriter), + auditLogger: auditLogger, transportType: transportType, logWriter: logWriter, subjectEnricher: o.subjectEnricher, @@ -98,14 +95,15 @@ func NewAuditorWithTransport(config *Config, transportType string, opts ...Optio // Close releases the auditor's log writer if it implements io.Closer. For a // log file this releases the auditor's handle; the file itself closes when the -// last auditor writing to that path is closed. +// last auditor writing to that path is closed. An auditor built with +// WithLogger owns no writer, so Close releases nothing. // This should be called when the auditor is no longer needed to properly release resources. func (a *Auditor) Close() error { return closeLogWriter(a.logWriter) } func closeLogWriter(logWriter io.Writer) error { - if logWriter == os.Stdout || logWriter == os.Stderr { + if logWriter == nil || logWriter == os.Stdout || logWriter == os.Stderr { return nil } diff --git a/pkg/audit/options.go b/pkg/audit/options.go new file mode 100644 index 0000000000..c82c1e6f68 --- /dev/null +++ b/pkg/audit/options.go @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package audit + +import ( + "fmt" + "io" + "log/slog" + + coreaudit "github.com/stacklok/toolhive-core/audit" +) + +// Option configures an Auditor or a WorkflowAuditor. +type Option func(*options) + +// options holds the settings both auditor constructors accept. +type options struct { + subjectEnricher SubjectEnricher + logger *slog.Logger +} + +// WithLogger makes the auditor write every audit event to logger, at +// LevelAudit, instead of building its own logger. It lets a program that +// embeds ToolHive route ToolHive's audit events through its own audit handler, +// such as one built with toolhive-core's audit.HandlerMiddleware, which then +// decides where they are written and how they are marked. A nil logger is +// ignored. +// +// With a logger the auditor opens no log writer, so Close releases nothing, and +// a Config that sets LogFile is rejected: the logger decides where events go. +func WithLogger(logger *slog.Logger) Option { + return func(o *options) { + o.logger = logger + } +} + +// buildOptions applies opts to a zero options value. +func buildOptions(opts []Option) options { + var o options + for _, opt := range opts { + opt(&o) + } + return o +} + +// auditLoggerFor returns the logger an auditor writes its events to, and the +// log writer the auditor owns and must release on Close, if any. +// +// With a caller's logger it returns that logger and no writer, and fails when +// config also sets LogFile, before any file is opened. Otherwise it opens the +// configured log writer (stdout, or LogFile) and returns a logger built on +// toolhive-core's audit.HandlerMiddleware, so every line carries level AUDIT and +// logger=audit. +func auditLoggerFor(config *Config, logger *slog.Logger) (*slog.Logger, io.Writer, error) { + if logger != nil { + if config != nil && config.LogFile != "" { + return nil, nil, fmt.Errorf( + "audit config sets logFile %q and WithLogger supplies a logger; set only one", config.LogFile) + } + return logger, nil, nil + } + + logWriter, err := config.GetLogWriter() + if err != nil { + return nil, nil, err + } + return newHandlerAuditLogger(logWriter), logWriter, nil +} + +// newHandlerAuditLogger returns a logger that writes LevelAudit records to w +// through toolhive-core's audit.HandlerMiddleware: one JSON line per record, +// with level AUDIT and logger=audit. The auditors log nothing below LevelAudit, +// so the wrapped handler discards everything. +func newHandlerAuditLogger(w io.Writer) *slog.Logger { + return slog.New(coreaudit.HandlerMiddleware(coreaudit.WithWriter(w))(slog.DiscardHandler)) +} diff --git a/pkg/audit/options_test.go b/pkg/audit/options_test.go new file mode 100644 index 0000000000..fbe8d35c07 --- /dev/null +++ b/pkg/audit/options_test.go @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package audit + +import ( + "bytes" + "context" + "errors" + "io/fs" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newCallerLogger returns a logger standing in for an embedder's audit +// logger, and the buffer it writes to. +func newCallerLogger() (*slog.Logger, *bytes.Buffer) { + var buf bytes.Buffer + return slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: LevelAudit})), &buf +} + +// eventTypes returns the type of each decoded audit event, in order. +func eventTypes(events []map[string]any) []any { + types := make([]any, 0, len(events)) + for _, e := range events { + types = append(types, e["type"]) + } + return types +} + +func TestAuditor_WithLoggerWritesThroughCallerLogger(t *testing.T) { + t.Parallel() + + logger, buf := newCallerLogger() + auditor, err := NewAuditorWithTransport(&Config{Component: "test"}, "streamable-http", WithLogger(logger)) + require.NoError(t, err) + + // The caller's logger is the auditor's only output: it owns no writer, so + // nothing reaches stdout and Close has nothing to release. + assert.Same(t, logger, auditor.auditLogger) + assert.Nil(t, auditor.logWriter) + + handler := auditor.Middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + handler.ServeHTTP(httptest.NewRecorder(), newToolsCallRequest()) + streamReq := httptest.NewRequest(http.MethodGet, "/mcp", nil) + streamReq.Header.Set("Accept", "text/event-stream") + handler.ServeHTTP(httptest.NewRecorder(), streamReq) + + events := decodeAuditEvents(t, buf) + assert.Equal(t, []any{EventTypeHTTPRequest, EventTypeSSEConnection}, eventTypes(events)) + for _, e := range events { + assert.Equal(t, LevelAudit.String(), e["level"], "events are logged at LevelAudit") + } + assert.NoError(t, auditor.Close()) +} + +func TestWorkflowAuditor_WithLoggerWritesThroughCallerLogger(t *testing.T) { + t.Parallel() + + logger, buf := newCallerLogger() + auditor, err := NewWorkflowAuditor(&Config{}, WithLogger(logger)) + require.NoError(t, err) + assert.Same(t, logger, auditor.auditLogger) + assert.Nil(t, auditor.logWriter) + + ctx := context.Background() + auditor.LogWorkflowStarted(ctx, "wf-1", "workflow", nil, time.Minute) + auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "tool-a") + auditor.LogStepCompleted(ctx, "wf-1", "step-1", time.Second, 0) + auditor.LogStepFailed(ctx, "wf-1", "step-2", time.Second, 1, errors.New("boom")) + auditor.LogStepSkipped(ctx, "wf-1", "step-3", "false") + auditor.LogWorkflowCompleted(ctx, "wf-1", "workflow", time.Second, 3, nil) + auditor.LogWorkflowFailed(ctx, "wf-1", "workflow", time.Second, 3, errors.New("boom")) + auditor.LogWorkflowTimedOut(ctx, "wf-1", "workflow", time.Second, 3) + + assert.Equal(t, []any{ + EventTypeWorkflowStarted, + EventTypeWorkflowStepStarted, + EventTypeWorkflowStepCompleted, + EventTypeWorkflowStepFailed, + EventTypeWorkflowStepSkipped, + EventTypeWorkflowCompleted, + EventTypeWorkflowFailed, + EventTypeWorkflowTimedOut, + }, eventTypes(decodeAuditEvents(t, buf))) + assert.NoError(t, auditor.Close()) +} + +func TestAuditor_DefaultLoggerStampsAuditMarker(t *testing.T) { + t.Parallel() + + assertMarked := func(t *testing.T, events []map[string]any) { + t.Helper() + require.NotEmpty(t, events) + for _, e := range events { + assert.Equal(t, "AUDIT", e["level"]) + assert.Equal(t, "audit", e["logger"]) + } + } + + t.Run("log file: request auditor", func(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "audit.log") + auditor, err := NewAuditorWithTransport(&Config{Component: "test", LogFile: path}, "streamable-http") + require.NoError(t, err) + t.Cleanup(func() { _ = auditor.Close() }) + + auditor.Middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })).ServeHTTP(httptest.NewRecorder(), newToolsCallRequest()) + + data, err := os.ReadFile(path) + require.NoError(t, err) + assertMarked(t, decodeAuditEvents(t, bytes.NewBuffer(data))) + }) + + t.Run("log file: workflow auditor", func(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "audit.log") + auditor, err := NewWorkflowAuditor(&Config{LogFile: path}) + require.NoError(t, err) + t.Cleanup(func() { _ = auditor.Close() }) + + auditor.LogWorkflowStarted(context.Background(), "wf-1", "workflow", nil, time.Minute) + + data, err := os.ReadFile(path) + require.NoError(t, err) + assertMarked(t, decodeAuditEvents(t, bytes.NewBuffer(data))) + }) + + t.Run("stdout: both auditors write marked lines to stdout", func(t *testing.T) { + t.Parallel() + auditor, err := NewAuditorWithTransport(&Config{Component: "test"}, "streamable-http") + require.NoError(t, err) + assert.Same(t, os.Stdout, auditor.logWriter) + workflowAuditor, err := NewWorkflowAuditor(nil) + require.NoError(t, err) + assert.Same(t, os.Stdout, workflowAuditor.logWriter) + + // Both are built by newHandlerAuditLogger on that writer; render a + // record through it to see the marked line stdout receives. + var buf bytes.Buffer + NewAuditEvent(EventTypeMCPToolCall, EventSource{}, OutcomeSuccess, nil, "test"). + LogTo(context.Background(), newHandlerAuditLogger(&buf), LevelAudit) + assertMarked(t, decodeAuditEvents(t, &buf)) + }) +} + +func TestAuditor_WithLoggerAndLogFileRejected(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + new func(cfg *Config, opts ...Option) error + }{ + { + name: "request auditor", + new: func(cfg *Config, opts ...Option) error { + _, err := NewAuditorWithTransport(cfg, "streamable-http", opts...) + return err + }, + }, + { + name: "workflow auditor", + new: func(cfg *Config, opts ...Option) error { + _, err := NewWorkflowAuditor(cfg, opts...) + return err + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "audit.log") + logger, _ := newCallerLogger() + + err := tt.new(&Config{LogFile: path}, WithLogger(logger)) + require.Error(t, err) + assert.Contains(t, err.Error(), "logFile") + assert.Contains(t, err.Error(), "WithLogger") + + _, statErr := os.Stat(path) + assert.ErrorIs(t, statErr, fs.ErrNotExist, "no log file is opened") + }) + } +} diff --git a/pkg/audit/subject_enricher.go b/pkg/audit/subject_enricher.go index 9a7fbdf35f..edc7623795 100644 --- a/pkg/audit/subject_enricher.go +++ b/pkg/audit/subject_enricher.go @@ -36,14 +36,6 @@ import ( // subjects. type SubjectEnricher func(ctx context.Context) map[string]string -// Option configures an Auditor or a WorkflowAuditor. -type Option func(*options) - -// options holds the settings both auditor constructors accept. -type options struct { - subjectEnricher SubjectEnricher -} - // WithSubjectEnricher sets the enricher whose subjects are added to every // audit event. A nil enricher is ignored. func WithSubjectEnricher(enricher SubjectEnricher) Option { @@ -52,15 +44,6 @@ func WithSubjectEnricher(enricher SubjectEnricher) Option { } } -// buildOptions applies opts to a zero options value. -func buildOptions(opts []Option) options { - var o options - for _, opt := range opts { - opt(&o) - } - return o -} - // reservedSubjectKeys are the subject keys the auditor itself writes. An // enricher can neither overwrite nor supply them. var reservedSubjectKeys = map[string]struct{}{ diff --git a/pkg/audit/workflow_auditor.go b/pkg/audit/workflow_auditor.go index 3d8269abc1..08bf7617d2 100644 --- a/pkg/audit/workflow_auditor.go +++ b/pkg/audit/workflow_auditor.go @@ -31,15 +31,21 @@ type WorkflowAuditor struct { // NewWorkflowAuditor creates a new workflow auditor. // If config is nil, creates a default configuration with stdout logging. // opts set behavior that is configured from Go rather than the serialized Config, -// such as WithSubjectEnricher. +// such as WithSubjectEnricher and WithLogger. +// +// Without WithLogger the auditor writes to stdout, or to config.LogFile, and +// every line carries level AUDIT and logger=audit. With WithLogger every event +// goes to the caller's logger, and a config that sets LogFile is rejected. func NewWorkflowAuditor(config *Config, opts ...Option) (*WorkflowAuditor, error) { if config == nil { config = DefaultConfig() } - logWriter, err := config.GetLogWriter() + o := buildOptions(opts) + + auditLogger, logWriter, err := auditLoggerFor(config, o.logger) if err != nil { - return nil, fmt.Errorf("failed to create log writer: %w", err) + return nil, fmt.Errorf("failed to create audit logger: %w", err) } // Use configured component or default to vmcp-composer @@ -48,10 +54,8 @@ func NewWorkflowAuditor(config *Config, opts ...Option) (*WorkflowAuditor, error component = "vmcp-composer" } - o := buildOptions(opts) - return &WorkflowAuditor{ - auditLogger: NewAuditLogger(logWriter), + auditLogger: auditLogger, config: config, component: component, logWriter: logWriter, @@ -61,7 +65,8 @@ func NewWorkflowAuditor(config *Config, opts ...Option) (*WorkflowAuditor, error // Close releases the underlying log writer if it owns a closeable resource. // For a log file this releases the auditor's handle; the file itself closes -// when the last auditor writing to that path is closed. +// when the last auditor writing to that path is closed. A workflow auditor +// built with WithLogger owns no writer, so Close releases nothing. // This should be called when the workflow auditor is no longer needed. func (w *WorkflowAuditor) Close() error { return closeLogWriter(w.logWriter) diff --git a/pkg/vmcp/core/core.go b/pkg/vmcp/core/core.go index 59d3f26b1b..9a317fa211 100644 --- a/pkg/vmcp/core/core.go +++ b/pkg/vmcp/core/core.go @@ -21,6 +21,7 @@ package core import ( "context" "errors" + "log/slog" "github.com/stacklok/toolhive/pkg/audit" "github.com/stacklok/toolhive/pkg/auth" @@ -365,7 +366,7 @@ type VMCP interface { // declared here as the contract; New's body (which wires them into a concrete // *coreVMCP) lands in a later change. // -// Cross-cutting TelemetryProvider/AuditConfig/AuditSubjectEnricher are consumed by both New and Serve +// Cross-cutting TelemetryProvider/AuditConfig/AuditSubjectEnricher/AuditLogger are consumed by both New and Serve // (not a clean partition). HealthMonitorConfig is the backend health monitoring // configuration; the core builds, starts, and stops the monitor from it (a nil config // disables monitoring, including all backends — matching today's no-monitor behavior). @@ -418,6 +419,13 @@ type Config struct { // identity passed to CallTool, not any identity the context carries. AuditSubjectEnricher audit.SubjectEnricher + // AuditLogger optionally receives the composite-tool workflow audit events + // instead of the workflow auditor's own stdout or log file logger. Set the + // same logger on the transport's ServerConfig so per-request MCP events go + // to it too. It has no effect when AuditConfig is nil, and is rejected + // together with AuditConfig.LogFile. See audit.WithLogger. + AuditLogger *slog.Logger + // HealthMonitorConfig configures backend health monitoring. The core builds, starts, and // (via Close) stops the monitor from it, filters capabilities with it, and exposes it via // BackendHealth. Nil disables monitoring (no health filtering; all backends included). diff --git a/pkg/vmcp/core/core_vmcp.go b/pkg/vmcp/core/core_vmcp.go index 8fa8f8ee48..9e5830d341 100644 --- a/pkg/vmcp/core/core_vmcp.go +++ b/pkg/vmcp/core/core_vmcp.go @@ -149,7 +149,9 @@ func New(cfg *Config) (VMCP, error) { } var err error workflowAuditor, err = audit.NewWorkflowAuditor( - cfg.AuditConfig, audit.WithSubjectEnricher(cfg.AuditSubjectEnricher)) + cfg.AuditConfig, + audit.WithSubjectEnricher(cfg.AuditSubjectEnricher), + audit.WithLogger(cfg.AuditLogger)) if err != nil { return nil, fmt.Errorf("failed to create workflow auditor: %w", err) } diff --git a/pkg/vmcp/server/audit_logger_test.go b/pkg/vmcp/server/audit_logger_test.go new file mode 100644 index 0000000000..3b8dc253db --- /dev/null +++ b/pkg/vmcp/server/audit_logger_test.go @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package server + +import ( + "bytes" + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + "github.com/stacklok/toolhive/pkg/audit" + "github.com/stacklok/toolhive/pkg/vmcp" + "github.com/stacklok/toolhive/pkg/vmcp/aggregator" + aggmocks "github.com/stacklok/toolhive/pkg/vmcp/aggregator/mocks" + "github.com/stacklok/toolhive/pkg/vmcp/composer" + vmcpmocks "github.com/stacklok/toolhive/pkg/vmcp/mocks" + routermocks "github.com/stacklok/toolhive/pkg/vmcp/router/mocks" + sessionmocks "github.com/stacklok/toolhive/pkg/vmcp/session/mocks" +) + +// syncBuffer is a bytes.Buffer safe for the concurrent writes of workflow +// step goroutines and the request auditor. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// TestServer_AuditLoggerReachesBothAuditors pins that Config.AuditLogger +// reaches both auditors a server builds: the request auditor in Handler and +// the workflow auditor of the core New builds. One composite tool call through +// the handler produces a request event and workflow events, all on the logger. +func TestServer_AuditLoggerReachesBothAuditors(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + target := &vmcp.BackendTarget{WorkloadID: "backend"} + agg := aggmocks.NewMockAggregator(ctrl) + agg.EXPECT().AggregateCapabilities(gomock.Any(), gomock.Any()).Return(&aggregator.AggregatedCapabilities{ + Tools: []vmcp.Tool{{Name: "echo", BackendID: target.WorkloadID}}, + RoutingTable: &vmcp.RoutingTable{Tools: map[string]*vmcp.BackendTarget{"echo": target}}, + }, nil).AnyTimes() + backend := vmcpmocks.NewMockBackendClient(ctrl) + backend.EXPECT().CallTool(gomock.Any(), target, "echo", gomock.Any(), gomock.Any(), gomock.Any()). + Return(&vmcp.ToolCallResult{StructuredContent: map[string]any{"ok": true}}, nil).AnyTimes() + + var logBuf syncBuffer + logger := slog.New(slog.NewJSONHandler(&logBuf, &slog.HandlerOptions{Level: audit.LevelAudit})) + + srv, err := New(t.Context(), &Config{ + Host: "127.0.0.1", + Port: 0, + Aggregator: agg, + SessionFactory: sessionmocks.NewMockMultiSessionFactory(ctrl), + AuditConfig: &audit.Config{Component: "test"}, + AuditLogger: logger, + }, routermocks.NewMockRouter(ctrl), backend, + vmcp.NewImmutableRegistry([]vmcp.Backend{{ID: target.WorkloadID}}), + map[string]*composer.WorkflowDefinition{ + "workflow": {Name: "workflow", Steps: []composer.WorkflowStep{ + {ID: "step", Type: composer.StepTypeTool, Tool: "echo"}, + }}, + }) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, srv.Stop(context.Background())) }) + + handler, err := srv.Handler(t.Context()) + require.NoError(t, err) + + req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader( + `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"workflow","arguments":{},`+ + `"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("MCP-Protocol-Version", "2026-07-28") + req.Header.Set("Mcp-Method", "tools/call") + req.Header.Set("Mcp-Name", "workflow") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + var types []string + for _, line := range strings.Split(strings.TrimSpace(logBuf.String()), "\n") { + var event map[string]any + require.NoError(t, json.Unmarshal([]byte(line), &event), "audit line is not JSON: %s", line) + eventType, _ := event["type"].(string) + types = append(types, eventType) + } + assert.Contains(t, types, audit.EventTypeMCPToolCall, "the request auditor writes to Config.AuditLogger") + assert.Contains(t, types, audit.EventTypeWorkflowStarted, "the workflow auditor writes to Config.AuditLogger") + assert.Contains(t, types, audit.EventTypeWorkflowCompleted, "the workflow auditor writes to Config.AuditLogger") +} diff --git a/pkg/vmcp/server/derive.go b/pkg/vmcp/server/derive.go index 39c26adaee..5a021e9e67 100644 --- a/pkg/vmcp/server/derive.go +++ b/pkg/vmcp/server/derive.go @@ -95,6 +95,7 @@ func deriveServerConfig( TelemetryProvider: cfg.TelemetryProvider, AuditConfig: cfg.AuditConfig, AuditSubjectEnricher: cfg.AuditSubjectEnricher, + AuditLogger: cfg.AuditLogger, CallBinding: cfg.CallBinding, } } @@ -109,9 +110,9 @@ func deriveServerConfig( // legacy HTTP authz path threads through (cli/serve.go passes vmcpCfg.Name). The raw // name is used (not the transport default) so authorization keys on the real // VirtualMCPServer name rather than the synthetic "toolhive-vmcp" fallback. -// - TelemetryProvider / AuditConfig / AuditSubjectEnricher — the cross-cutting fields -// shared with the transport (R3, not a clean partition); deriveServerConfig copies the -// same three. +// - TelemetryProvider / AuditConfig / AuditSubjectEnricher / AuditLogger — the cross-cutting +// fields shared with the transport (R3, not a clean partition); deriveServerConfig copies +// the same four. // - ConnectAnswerer = connectAnswererFor(cfg): the embedder's answerer, else a default // over cfg.AuthServer, else nil. // @@ -146,6 +147,7 @@ func deriveCoreConfig( TelemetryProvider: cfg.TelemetryProvider, AuditConfig: cfg.AuditConfig, AuditSubjectEnricher: cfg.AuditSubjectEnricher, + AuditLogger: cfg.AuditLogger, HealthMonitorConfig: cfg.HealthMonitorConfig, Elicitation: elicitation, ConnectAnswerer: connectAnswererFor(cfg), diff --git a/pkg/vmcp/server/derive_test.go b/pkg/vmcp/server/derive_test.go index a07c1884ed..d5647bf90d 100644 --- a/pkg/vmcp/server/derive_test.go +++ b/pkg/vmcp/server/derive_test.go @@ -5,6 +5,7 @@ package server import ( "context" + "log/slog" "net/http" "reflect" "testing" @@ -55,6 +56,7 @@ func populatedLegacyConfig() *Config { UsageMetricsMiddleware: passthrough, AuditConfig: &audit.Config{}, AuditSubjectEnricher: stubSubjectEnricher, + AuditLogger: testAuditLogger, CallBinding: testCallBinding(), StatusReportingInterval: 11 * time.Second, Watcher: stubWatcher{}, @@ -67,6 +69,10 @@ func populatedLegacyConfig() *Config { // tests; its output is never inspected here. func stubSubjectEnricher(context.Context) map[string]string { return nil } +// testAuditLogger is a non-nil audit logger for the field-mapping tests; it is +// never written to here. +var testAuditLogger = slog.New(slog.DiscardHandler) + func TestDeriveServerConfigProjectsTransportFields(t *testing.T) { t.Parallel() @@ -103,6 +109,7 @@ func TestDeriveServerConfigProjectsTransportFields(t *testing.T) { assert.Same(t, cfg.TelemetryProvider, got.TelemetryProvider) assert.Same(t, cfg.AuditConfig, got.AuditConfig) assert.NotNil(t, got.AuditSubjectEnricher) + assert.Same(t, cfg.AuditLogger, got.AuditLogger) // Collaborators passed in (not on server.Config) — threaded through, not from cfg. assert.Same(t, registry, got.BackendRegistry) @@ -123,6 +130,7 @@ func TestDeriveServerConfigPropagatesNilCrossCutting(t *testing.T) { assert.Nil(t, got.TelemetryProvider) assert.Nil(t, got.AuditConfig) assert.Nil(t, got.AuditSubjectEnricher) + assert.Nil(t, got.AuditLogger) assert.Nil(t, got.BackendRegistry) assert.Nil(t, got.SessionManagerConfig) } @@ -156,6 +164,7 @@ func TestDeriveCoreConfigAssemblesCollaborators(t *testing.T) { TelemetryProvider: &telemetry.Provider{}, AuditConfig: &audit.Config{}, AuditSubjectEnricher: stubSubjectEnricher, + AuditLogger: testAuditLogger, HealthMonitorConfig: &health.MonitorConfig{}, } agg := aggmocks.NewMockAggregator(ctrl) @@ -186,6 +195,7 @@ func TestDeriveCoreConfigAssemblesCollaborators(t *testing.T) { assert.Same(t, cfg.TelemetryProvider, got.TelemetryProvider) assert.Same(t, cfg.AuditConfig, got.AuditConfig) assert.NotNil(t, got.AuditSubjectEnricher) + assert.Same(t, cfg.AuditLogger, got.AuditLogger) } func TestDeriveCoreConfigCopiesConnectAnswerer(t *testing.T) { @@ -253,6 +263,7 @@ func TestDeriveCoreConfigMapsAllFields(t *testing.T) { TelemetryProvider: &telemetry.Provider{}, AuditConfig: &audit.Config{}, AuditSubjectEnricher: stubSubjectEnricher, + AuditLogger: testAuditLogger, HealthMonitorConfig: &health.MonitorConfig{}, ConnectAnswerer: func(context.Context, vmcp.ConnectRequest) (*vmcp.URLElicitationRequiredError, error) { return nil, nil diff --git a/pkg/vmcp/server/serve.go b/pkg/vmcp/server/serve.go index f7500bad82..db3fe1f2f2 100644 --- a/pkg/vmcp/server/serve.go +++ b/pkg/vmcp/server/serve.go @@ -30,7 +30,7 @@ import ( // ServerConfig holds the transport-only runtime configuration for Serve. // // It carries the subset of the legacy server.Config that configures the HTTP/SDK -// runtime, plus the cross-cutting TelemetryProvider/AuditConfig/AuditSubjectEnricher that are consumed +// runtime, plus the cross-cutting TelemetryProvider/AuditConfig/AuditSubjectEnricher/AuditLogger that are consumed // by both the core (core.New) and the transport (Serve) — not a clean partition. // The fields the core exclusively owns (Aggregator, Router, BackendClient, Authz, // composite-tool WorkflowDefs) live on core.Config instead and are absent here. @@ -166,6 +166,13 @@ type ServerConfig struct { // them too. It has no effect when AuditConfig is nil. AuditSubjectEnricher audit.SubjectEnricher + // AuditLogger optionally receives the per-request MCP audit events instead + // of the auditor's own stdout or log file logger. Set the same logger on + // core.Config.AuditLogger so composite-tool workflow events go to it too. + // It has no effect when AuditConfig is nil, and is rejected together with + // AuditConfig.LogFile. See audit.WithLogger. + AuditLogger *slog.Logger + // CallBinding is the enforcement of access tokens bound to one MCP call. // The vMCP always enforces a token that carries an authorization_details // entry of type https://toolhive.dev/mcp_tool_call: with a tool-call entry @@ -517,6 +524,7 @@ func buildServeConfig(cfg *ServerConfig) *Config { UsageMetricsMiddleware: cfg.UsageMetricsMiddleware, AuditConfig: cfg.AuditConfig, AuditSubjectEnricher: cfg.AuditSubjectEnricher, + AuditLogger: cfg.AuditLogger, StatusReportingInterval: cfg.StatusReportingInterval, Watcher: cfg.Watcher, SessionStorage: cfg.SessionStorage, diff --git a/pkg/vmcp/server/serve_test.go b/pkg/vmcp/server/serve_test.go index 2d210605a0..bdfc980979 100644 --- a/pkg/vmcp/server/serve_test.go +++ b/pkg/vmcp/server/serve_test.go @@ -434,6 +434,7 @@ func TestBuildServeConfigMapsSharedFields(t *testing.T) { UsageMetricsMiddleware: func(h http.Handler) http.Handler { return h }, AuditConfig: &audit.Config{}, AuditSubjectEnricher: stubSubjectEnricher, + AuditLogger: testAuditLogger, CallBinding: testCallBinding(), } diff --git a/pkg/vmcp/server/server.go b/pkg/vmcp/server/server.go index f43f24aa1c..65f9a93ca5 100644 --- a/pkg/vmcp/server/server.go +++ b/pkg/vmcp/server/server.go @@ -240,6 +240,14 @@ type Config struct { // AuditConfig is nil. See audit.SubjectEnricher. AuditSubjectEnricher audit.SubjectEnricher + // AuditLogger optionally receives every audit event, both the per-request + // MCP events and the composite-tool workflow events, instead of the + // auditors' own stdout or log file logger. It lets an embedder route them + // through its own audit handler. It is set from Go only, has no effect when + // AuditConfig is nil, and is rejected together with AuditConfig.LogFile. + // See audit.WithLogger. + AuditLogger *slog.Logger + // HealthMonitorConfig is the optional health monitoring configuration. // If nil, health monitoring is disabled. HealthMonitorConfig *health.MonitorConfig @@ -917,6 +925,7 @@ func (s *Server) Handler(_ context.Context) (http.Handler, error) { s.config.AuditConfig, "streamable-http", // vMCP uses streamable HTTP transport audit.WithSubjectEnricher(s.config.AuditSubjectEnricher), + audit.WithLogger(s.config.AuditLogger), ) if err != nil { return nil, fmt.Errorf("failed to create auditor: %w", err) From 94d9f0f9ffab4c87e645a6acaff235354873e872 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 15:04:39 -0800 Subject: [PATCH 4/6] Take audit source and request id from the server 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 Signed-off-by: Trey --- docs/middleware.md | 22 ++++- pkg/audit/auditor.go | 54 ++++++---- pkg/audit/auditor_test.go | 17 ++-- pkg/audit/mcp_events.go | 7 +- pkg/audit/source_test.go | 181 ++++++++++++++++++++++++++++++++++ pkg/audit/workflow_auditor.go | 28 ++++-- 6 files changed, 268 insertions(+), 41 deletions(-) create mode 100644 pkg/audit/source_test.go diff --git a/docs/middleware.md b/docs/middleware.md index cfef701055..1b3b4bd6b3 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -685,8 +685,7 @@ the events through its own logger (see "type": "network", "value": "192.168.1.100", "extra": { - "user_agent": "mcp-client/1.0", - "request_id": "req-12345" + "user_agent": "mcp-client/1.0" } }, "subjects": { @@ -714,7 +713,8 @@ the events through its own logger (see "extra": { "duration_ms": 150, "transport": "streamable-http", - "response_size_bytes": 1024 + "response_size_bytes": 1024, + "request_id": "0b6f6f0e-8f8e-4c1e-9a43-6a1f6f3c2d7b" } }, "data": { @@ -742,8 +742,13 @@ the events through its own logger (see - `component`: Service/component that generated the event - `source`: Information about the request source - `type`: Source type (`network` for HTTP requests) - - `value`: Source identifier (client IP address) - - `extra`: Additional source metadata (user agent, request ID, etc.) + - `value`: Address of the connection the request arrived on (from the + connection's remote address). Behind a proxy or load balancer this is the + proxy's address. `X-Forwarded-For` and `X-Real-IP` are never read, because + a client can set them; to find the original client, join the event's + `metadata.extra.request_id` to the proxy's access log + - `extra`: Additional source metadata (user agent). The client's + `X-Request-ID` header is never recorded - `subjects`: Information about the authenticated user/client - `user_id`: User subject identifier from JWT - `user`: User display name (from `name` claim, `preferred_username`, or `email`) @@ -791,6 +796,13 @@ the events through its own logger (see - `duration_ms`: Request duration in milliseconds - `transport`: Transport type (`sse`, `streamable-http`, `http`) - `response_size_bytes`: Response body size (when capturing response data) + - `request_id`: The request id the request context carries, present only + when one was set. A program that embeds the audit middleware generates it + and stores it with toolhive-core's `audit.ContextWithRequestID` in a + middleware that wraps the audit middleware; an id set inside the audit + middleware is never seen. Composite-tool workflow and step events carry + the request id of the context they are logged with. ToolHive's own proxy + sets none, and a client-sent id is never used - `trace_id`, `span_id`: W3C trace and span IDs of the request (present only when the request carries a valid span context, such as an inbound `traceparent` with tracing enabled) - `denial_reason`: Why an inner check refused the request, when it names a reason (for example a vMCP call-binding refusal: `token_reused` or `token_expired`, answered with 401, or `arguments_mismatch`, answered with 403). A fixed string that never carries request data. Present only on denied events, including the `sse_connection` event of a refused stream-opening GET - `admitted_after_expiry`: `true` when the token validator accepted the request's access token after it expired, as a message of a vMCP call that outlived its token. Present only on such events, whether the vMCP then admitted or refused the request, including the stream-open (`sse_connection`) event of a GET diff --git a/pkg/audit/auditor.go b/pkg/audit/auditor.go index faa8bbab0e..3517bb25ea 100644 --- a/pkg/audit/auditor.go +++ b/pkg/audit/auditor.go @@ -227,6 +227,14 @@ func ensureAuditContext(r *http.Request) *http.Request { } // Middleware creates an HTTP middleware that logs audit events. +// +// Each event is logged with the request context the middleware was given, so it +// carries only a request id set outside it. To record one, generate the id in a +// middleware that wraps this one and store it with toolhive-core's +// audit.ContextWithRequestID; it is then written to metadata.extra.request_id, +// on the events of requests an inner middleware refused too. An id set inside +// this middleware is never seen, and the client's X-Request-ID header is never +// read. func (a *Auditor) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r = ensureAuditContext(r) @@ -490,30 +498,21 @@ func (a *Auditor) extractSource(r *http.Request) EventSource { source.Extra[SourceExtraKeyUserAgent] = userAgent } - // Add request ID if available - if requestID := r.Header.Get("X-Request-ID"); requestID != "" { - source.Extra[SourceExtraKeyRequestID] = requestID - } + // The client's X-Request-ID header is deliberately not recorded: a client + // can set it to any value. The request id comes from the context only (see + // stampRequestID). return source } -// getClientIP extracts the client IP address from the request. +// getClientIP returns the address of the connection the request arrived on, +// from RemoteAddr. Behind a proxy that is the proxy's address. +// +// 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 +// proxy's access log. func (*Auditor) getClientIP(r *http.Request) string { - // Check X-Forwarded-For header first - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { - // Take the first IP in the list - if ips := strings.Split(xff, ","); len(ips) > 0 { - return strings.TrimSpace(ips[0]) - } - } - - // Check X-Real-IP header - if xri := r.Header.Get("X-Real-IP"); xri != "" { - return xri - } - - // Fall back to RemoteAddr if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { return host } @@ -721,6 +720,7 @@ func (a *Auditor) addMetadata(event *AuditEvent, r *http.Request, duration time. stampAdmittedAfterExpiry(r, event) stampTraceContext(r.Context(), event) + stampRequestID(r.Context(), event) } // stampAdmittedAfterExpiry marks the event of a request whose access token the @@ -768,6 +768,21 @@ func stampTraceContext(ctx context.Context, event *AuditEvent) { event.Metadata.Extra[MetadataExtraKeySpanID] = sc.SpanID().String() } +// stampRequestID records the request id ctx carries, set with toolhive-core's +// audit.ContextWithRequestID, as metadata.extra.request_id. It adds nothing +// when ctx carries none. The id is never taken from the request: the program +// that embeds the auditor generates it. +func stampRequestID(ctx context.Context, event *AuditEvent) { + requestID, ok := coreaudit.RequestIDFromContext(ctx) + if !ok { + return + } + if event.Metadata.Extra == nil { + event.Metadata.Extra = make(map[string]any) + } + event.Metadata.Extra[MetadataExtraKeyRequestID] = requestID +} + // addEventData adds request/response data to the audit event if configured. func (a *Auditor) addEventData(event *AuditEvent, _ *http.Request, rw *responseWriter, requestData []byte) { if !a.config.IncludeRequestData && !a.config.IncludeResponseData { @@ -902,6 +917,7 @@ func (a *Auditor) logSSEConnectionEvent(r *http.Request, statusCode int) { } stampAdmittedAfterExpiry(r, event) stampTraceContext(r.Context(), event) + stampRequestID(r.Context(), event) // Log the event event.LogTo(r.Context(), a.auditLogger, LevelAudit) diff --git a/pkg/audit/auditor_test.go b/pkg/audit/auditor_test.go index 61ac723057..7264cf6a17 100644 --- a/pkg/audit/auditor_test.go +++ b/pkg/audit/auditor_test.go @@ -442,14 +442,16 @@ func TestGetClientIP(t *testing.T) { expected string }{ { - name: "X-Forwarded-For header", - headers: map[string]string{"X-Forwarded-For": "192.168.1.100, 10.0.0.1"}, - expected: "192.168.1.100", + name: "X-Forwarded-For header is ignored", + headers: map[string]string{"X-Forwarded-For": "192.168.1.100, 10.0.0.1"}, + remoteAddr: "192.0.2.7:4431", + expected: "192.0.2.7", }, { - name: "X-Real-IP header", - headers: map[string]string{"X-Real-IP": "203.0.113.1"}, - expected: "203.0.113.1", + name: "X-Real-IP header is ignored", + headers: map[string]string{"X-Real-IP": "203.0.113.1"}, + remoteAddr: "192.0.2.7:4431", + expected: "192.0.2.7", }, { name: "RemoteAddr with port", @@ -1112,7 +1114,8 @@ func TestExtractSourceWithHeaders(t *testing.T) { assert.Equal(t, SourceTypeNetwork, source.Type) assert.Equal(t, "192.168.1.100", source.Value) assert.Equal(t, "TestAgent/1.0", source.Extra[SourceExtraKeyUserAgent]) - assert.Equal(t, "req-12345", source.Extra[SourceExtraKeyRequestID]) + assert.NotContains(t, source.Extra, SourceExtraKeyRequestID, + "the client's X-Request-ID header is never recorded") } func TestErrorDetectionBodyCapture(t *testing.T) { diff --git a/pkg/audit/mcp_events.go b/pkg/audit/mcp_events.go index 4d963c8934..2b39c261ec 100644 --- a/pkg/audit/mcp_events.go +++ b/pkg/audit/mcp_events.go @@ -120,7 +120,9 @@ const ( const ( // SourceExtraKeyUserAgent is the key for the user agent in the source extra map SourceExtraKeyUserAgent = coreaudit.SourceExtraKeyUserAgent - // SourceExtraKeyRequestID is the key for the request ID in the source extra map + // SourceExtraKeyRequestID is the key for a client-sent request ID in the + // source extra map. The auditors in this package never write it; they record + // the server-generated request id under MetadataExtraKeyRequestID. SourceExtraKeyRequestID = coreaudit.SourceExtraKeyRequestID // SourceExtraKeySessionID is the key for the session ID in the source extra map SourceExtraKeySessionID = coreaudit.SourceExtraKeySessionID @@ -142,6 +144,9 @@ const ( MetadataExtraKeyStepCount = coreaudit.MetadataExtraKeyStepCount // MetadataExtraKeyTimeout is the key for the workflow timeout in milliseconds MetadataExtraKeyTimeout = coreaudit.MetadataExtraKeyTimeout + // MetadataExtraKeyRequestID is the key for the request id the context + // carries, set with toolhive-core's audit.ContextWithRequestID + MetadataExtraKeyRequestID = coreaudit.MetadataExtraKeyRequestID // MetadataExtraKeyTraceID is the key for the W3C trace ID of the request that produced the event MetadataExtraKeyTraceID = "trace_id" // MetadataExtraKeySpanID is the key for the ID of the span active when the event was recorded diff --git a/pkg/audit/source_test.go b/pkg/audit/source_test.go new file mode 100644 index 0000000000..8b97ff7f3e --- /dev/null +++ b/pkg/audit/source_test.go @@ -0,0 +1,181 @@ +// SPDX-FileCopyrightText: Copyright 2026 Stacklok, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package audit + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + coreaudit "github.com/stacklok/toolhive-core/audit" +) + +// withForwardedHeaders sets the connection address and the client-settable +// forwarding headers the Auditor must ignore. +func withForwardedHeaders(req *http.Request) *http.Request { + req.RemoteAddr = "192.0.2.7:4431" + req.Header.Set("X-Forwarded-For", "203.0.113.9") + req.Header.Set("X-Real-IP", "203.0.113.10") + return req +} + +// newStreamOpenRequest returns a GET that opens an MCP event stream. +func newStreamOpenRequest() *http.Request { + req := httptest.NewRequest(http.MethodGet, "/mcp", nil) + req.Header.Set("Accept", "text/event-stream") + return req +} + +// statusHandler answers every request with status. +func statusHandler(status int) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + }) +} + +// requireOneEvent returns the only event in events. +func requireOneEvent(t *testing.T, events []map[string]any) map[string]any { + t.Helper() + require.Len(t, events, 1) + return events[0] +} + +// sourceValue returns source.value of a decoded event. +func sourceValue(t *testing.T, event map[string]any) any { + t.Helper() + source, ok := event["source"].(map[string]any) + require.True(t, ok, "event has no source object") + return source["value"] +} + +// metadataRequestID returns metadata.extra.request_id of a decoded event, and +// whether it is present. +func metadataRequestID(event map[string]any) (any, bool) { + metadata, _ := event["metadata"].(map[string]any) + extra, _ := metadata["extra"].(map[string]any) + id, ok := extra[MetadataExtraKeyRequestID] + return id, ok +} + +func TestAuditor_SourceIgnoresForwardedHeaders(t *testing.T) { + t.Parallel() + + auditor, logBuf := newBufferAuditor(t) + auditor.Middleware(statusHandler(http.StatusOK)). + ServeHTTP(httptest.NewRecorder(), withForwardedHeaders(newToolsCallRequest())) + + assert.Equal(t, "192.0.2.7", sourceValue(t, requireOneEvent(t, decodeAuditEvents(t, logBuf)))) +} + +func TestAuditor_StreamOpenSourceIgnoresForwardedHeaders(t *testing.T) { + t.Parallel() + + auditor, logBuf := newBufferAuditor(t) + auditor.Middleware(statusHandler(http.StatusOK)). + ServeHTTP(httptest.NewRecorder(), withForwardedHeaders(newStreamOpenRequest())) + + event := requireOneEvent(t, decodeAuditEvents(t, logBuf)) + assert.Equal(t, EventTypeSSEConnection, event["type"]) + assert.Equal(t, "192.0.2.7", sourceValue(t, event)) +} + +func TestAuditor_RequestIDFromOuterMiddleware(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + req func() *http.Request + status int + wantOutcome string + }{ + {name: "normal request", req: newToolsCallRequest, status: http.StatusOK, wantOutcome: OutcomeSuccess}, + {name: "401 written inside the Auditor", req: newToolsCallRequest, status: http.StatusUnauthorized, wantOutcome: OutcomeDenied}, + {name: "stream open", req: newStreamOpenRequest, status: http.StatusOK, wantOutcome: OutcomeSuccess}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + auditor, logBuf := newBufferAuditor(t) + inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // An id set inside the Auditor is never seen by it. + r = r.WithContext(coreaudit.ContextWithRequestID(r.Context(), "inner-id")) + statusHandler(tt.status).ServeHTTP(w, r) + }) + outer := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTP(w, r.WithContext(coreaudit.ContextWithRequestID(r.Context(), "r-1"))) + }) + } + outer(auditor.Middleware(inner)).ServeHTTP(httptest.NewRecorder(), tt.req()) + + event := requireOneEvent(t, decodeAuditEvents(t, logBuf)) + assert.Equal(t, tt.wantOutcome, event["outcome"]) + id, ok := metadataRequestID(event) + require.True(t, ok, "metadata.extra.request_id must be set") + assert.Equal(t, "r-1", id) + }) + } +} + +func TestAuditor_IgnoresClientRequestIDHeader(t *testing.T) { + t.Parallel() + + for name, newReq := range map[string]func() *http.Request{ + "request": newToolsCallRequest, + "stream open": newStreamOpenRequest, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + auditor, logBuf := newBufferAuditor(t) + req := newReq() + req.Header.Set("X-Request-ID", "client-chosen") + auditor.Middleware(statusHandler(http.StatusOK)).ServeHTTP(httptest.NewRecorder(), req) + + requireOneEvent(t, decodeAuditEvents(t, logBuf)) + line := logBuf.String() + assert.NotContains(t, line, "request_id", "no request_id key anywhere in the event") + assert.NotContains(t, line, "client-chosen") + }) + } +} + +func TestWorkflowAuditor_RequestIDFromContext(t *testing.T) { + t.Parallel() + + logger, buf := newCallerLogger() + auditor, err := NewWorkflowAuditor(&Config{}, WithLogger(logger)) + require.NoError(t, err) + + // Every Log* method, including those that set their own metadata. + ctx := coreaudit.ContextWithRequestID(context.Background(), "r-1") + auditor.LogWorkflowStarted(ctx, "wf-1", "workflow", nil, time.Minute) + auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "tool-a") + auditor.LogStepCompleted(ctx, "wf-1", "step-1", time.Second, 0) + auditor.LogStepFailed(ctx, "wf-1", "step-2", time.Second, 1, errors.New("boom")) + auditor.LogStepSkipped(ctx, "wf-1", "step-3", "false") + auditor.LogWorkflowCompleted(ctx, "wf-1", "workflow", time.Second, 3, nil) + auditor.LogWorkflowFailed(ctx, "wf-1", "workflow", time.Second, 3, errors.New("boom")) + auditor.LogWorkflowTimedOut(ctx, "wf-1", "workflow", time.Second, 3) + + // An event logged with a context that carries no id has none. + auditor.LogStepStarted(context.Background(), "wf-2", "step-1", "tool", "tool-a") + + events := decodeAuditEvents(t, buf) + require.Len(t, events, 9) + for _, event := range events[:8] { + id, ok := metadataRequestID(event) + require.True(t, ok, "%v event must carry the request id", event["type"]) + assert.Equal(t, "r-1", id) + } + _, ok := metadataRequestID(events[8]) + assert.False(t, ok) +} diff --git a/pkg/audit/workflow_auditor.go b/pkg/audit/workflow_auditor.go index 08bf7617d2..04f317084f 100644 --- a/pkg/audit/workflow_auditor.go +++ b/pkg/audit/workflow_auditor.go @@ -15,7 +15,9 @@ import ( "github.com/stacklok/toolhive/pkg/auth" ) -// WorkflowAuditor provides audit logging for workflow execution. +// WorkflowAuditor provides audit logging for workflow execution. Each event +// carries the request id of the context it is logged with, set with +// toolhive-core's audit.ContextWithRequestID, as metadata.extra.request_id. // This struct abstracts workflow-specific audit operations from the // HTTP middleware-based Auditor. type WorkflowAuditor struct { @@ -110,7 +112,7 @@ func (w *WorkflowAuditor) LogWorkflowStarted( } } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogWorkflowCompleted logs successful workflow completion. @@ -153,7 +155,7 @@ func (w *WorkflowAuditor) LogWorkflowCompleted( } } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogWorkflowFailed logs workflow failure. @@ -184,7 +186,7 @@ func (w *WorkflowAuditor) LogWorkflowFailed( MetadataExtraKeyStepCount: stepCount, } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogWorkflowTimedOut logs workflow timeout. @@ -214,7 +216,7 @@ func (w *WorkflowAuditor) LogWorkflowTimedOut( MetadataExtraKeyStepCount: stepCount, } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogStepStarted logs the start of step execution. @@ -242,7 +244,7 @@ func (w *WorkflowAuditor) LogStepStarted( } event.WithTarget(target) - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogStepCompleted logs successful step completion. @@ -271,7 +273,7 @@ func (w *WorkflowAuditor) LogStepCompleted( MetadataExtraKeyRetryCount: retryCount, } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogStepFailed logs step failure. @@ -301,7 +303,7 @@ func (w *WorkflowAuditor) LogStepFailed( MetadataExtraKeyRetryCount: retryCount, } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // LogStepSkipped logs conditional step skip. @@ -331,7 +333,7 @@ func (w *WorkflowAuditor) LogStepSkipped( } } - event.LogTo(ctx, w.auditLogger, LevelAudit) + w.logEvent(ctx, event) } // newEvent creates an audit event of the given type and outcome with the @@ -350,6 +352,14 @@ func (w *WorkflowAuditor) newEvent(ctx context.Context, eventType, outcome strin return event } +// logEvent stamps the request id ctx carries on event and logs it. Every Log* +// method MUST log through this helper, after setting its own metadata, so the +// request id is never overwritten or forgotten. +func (w *WorkflowAuditor) logEvent(ctx context.Context, event *AuditEvent) { + stampRequestID(ctx, event) + event.LogTo(ctx, w.auditLogger, LevelAudit) +} + // extractSource extracts source information from context. // For workflows, source is always local since they're internal orchestration. func (*WorkflowAuditor) extractSource(_ context.Context) EventSource { From 81a50425629e8beb5e6ac8c560b376d1e56fc303 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 16:29:22 -0800 Subject: [PATCH 5/6] Narrow audit logger docs to the two auditors 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 stacklok/toolhive#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 Signed-off-by: Trey --- docs/middleware.md | 41 ++++++++++++++++++++++++----------- pkg/audit/auditor.go | 10 ++++----- pkg/audit/event.go | 2 +- pkg/audit/options.go | 6 ++++- pkg/audit/workflow_auditor.go | 7 +++--- pkg/vmcp/server/server.go | 14 +++++++----- 6 files changed, 51 insertions(+), 29 deletions(-) diff --git a/docs/middleware.md b/docs/middleware.md index 1b3b4bd6b3..eb14feb8eb 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -667,13 +667,20 @@ ToolHive installs no signal handler for this; the embedding program calls `Reope #### Log Output Format Audit events are logged as structured JSON objects, one per line. Each line -also carries `"level": "AUDIT"`, `"logger": "audit"`, `"msg": "audit_event"` -and a `time` key, which the example below leaves out; select audit records in -a log pipeline with `logger=audit`. The lines are written by toolhive-core's -audit handler middleware (`audit.HandlerMiddleware`), unless an embedder routes -the events through its own logger (see +the audit middleware and the composite-tool workflow auditor write also +carries `"level": "AUDIT"`, `"logger": "audit"`, `"msg": "audit_event"` and a +`time` key, which the example below leaves out; select those records in a log +pipeline with `logger=audit`. The lines are written by toolhive-core's audit +handler middleware (`audit.HandlerMiddleware`), unless an embedder routes the +events through its own logger (see [Embedder-supplied logger](#embedder-supplied-logger) below). +The `obo_token_exchange` events of the On-Behalf-Of middleware and the vMCP +OBO auth strategy are written by a separate logger: they go to stdout with +`"level": "AUDIT"` but no `logger` key, are not routed to an embedder-supplied +logger, and carry no `metadata.extra.request_id`. Select them with +`level=AUDIT`. + ```json { "audit_id": "01be8d47-3ab0-4aa9-ad14-bd5bb408005d", @@ -745,8 +752,10 @@ the events through its own logger (see - `value`: Address of the connection the request arrived on (from the connection's remote address). Behind a proxy or load balancer this is the proxy's address. `X-Forwarded-For` and `X-Real-IP` are never read, because - a client can set them; to find the original client, join the event's - `metadata.extra.request_id` to the proxy's access log + a client can set them. An embedder that sets a request id (see + `metadata.extra.request_id` below) can find the original client by joining + it to the proxy's access log. `thv`, the proxy runner and the vMCP set no + request id, so their events carry no such join key - `extra`: Additional source metadata (user agent). The client's `X-Request-ID` header is never recorded - `subjects`: Information about the authenticated user/client @@ -775,7 +784,11 @@ the events through its own logger (see default) and inner hops were dropped; the outermost hops — including `chain[0]`, the current actor — are always kept. Always present. The default is above ToolHive's own minting cap of 10 hops, so a recorded - chain longer than 10 hops was not minted by ToolHive + chain longer than 10 hops was not minted by ToolHive. The CRD default was + 10 before; the API server writes a CRD default into the object when it is + created or updated, so an existing `VirtualMCPServer` with an `audit` + block keeps a stored `maxDelegationDepth` of 10 until the field is edited + or removed - `omitted`: Number of well-formed hops dropped due to the depth cap. Always present; `0` when nothing was dropped - `malformed`: `true` when the token's `act` claim violated RFC 8693 @@ -854,8 +867,9 @@ cfg.AuditSubjectEnricher = func(ctx context.Context) map[string]string { #### Embedder-supplied logger -A program that embeds ToolHive can route every audit event through its own -`*slog.Logger`, for example one whose handler is built with toolhive-core's +A program that embeds ToolHive can route the events of the audit middleware +and the composite-tool workflow auditor through its own `*slog.Logger`, for +example one whose handler is built with toolhive-core's `audit.HandlerMiddleware`, so that ToolHive's audit events and its own reach the same audit handler. Pass `audit.WithLogger(logger)` to `audit.NewAuditorWithTransport` or `audit.NewWorkflowAuditor`, or, for the @@ -863,9 +877,10 @@ vMCP, set `AuditLogger` on `server.Config`, or on both `server.ServerConfig` and `core.Config` when it calls `core.New` and `server.Serve` directly. - It is set from Go only. It has no key in the audit configuration file. -- Every event, including the `sse_connection` event of a stream and every - composite-tool workflow and step event, is logged to it at - `audit.LevelAudit`. The logger's handler decides where the event is written +- Every event of those auditors, including the `sse_connection` event of a + stream and every composite-tool workflow and step event, is logged to it at + `audit.LevelAudit`. The `obo_token_exchange` events are not (see + [Log Output Format](#log-output-format)). The logger's handler decides where the event is written and how it is marked: ToolHive adds no `logger=audit` key of its own. - The auditor then opens no log writer, so closing it releases nothing. - An audit configuration that sets `logFile` is rejected when a logger is diff --git a/pkg/audit/auditor.go b/pkg/audit/auditor.go index 3517bb25ea..424ce9c31e 100644 --- a/pkg/audit/auditor.go +++ b/pkg/audit/auditor.go @@ -53,7 +53,11 @@ func BackendInfoFromContext(ctx context.Context) (*BackendInfo, bool) { return info, ok } -// NewAuditLogger creates a new structured audit logger that writes to the specified writer. +// NewAuditLogger creates a new structured audit logger that writes to the +// specified writer, or to stdout when w is nil. It is toolhive-core's +// audit.NewAuditLogger: its lines carry level AUDIT but no logger=audit key, +// unlike the default logger of the Auditor and the WorkflowAuditor, and a +// logger given with WithLogger does not replace it. func NewAuditLogger(w io.Writer) *slog.Logger { return coreaudit.NewAuditLogger(w) } @@ -498,10 +502,6 @@ func (a *Auditor) extractSource(r *http.Request) EventSource { source.Extra[SourceExtraKeyUserAgent] = userAgent } - // The client's X-Request-ID header is deliberately not recorded: a client - // can set it to any value. The request id comes from the context only (see - // stampRequestID). - return source } diff --git a/pkg/audit/event.go b/pkg/audit/event.go index c8d9950775..0f8ce02160 100644 --- a/pkg/audit/event.go +++ b/pkg/audit/event.go @@ -14,7 +14,7 @@ import ( // It is highly recommended to use the NewAuditEvent function to create // audit events and set the required fields. // -//nolint:revive // AuditEvent name is intentional for compatibility with auditevent library +//nolint:revive // name kept for existing audit.AuditEvent callers type AuditEvent = coreaudit.AuditEvent // EventMetadata contains metadata about the audit event. It is the diff --git a/pkg/audit/options.go b/pkg/audit/options.go index c82c1e6f68..fb73ccc2da 100644 --- a/pkg/audit/options.go +++ b/pkg/audit/options.go @@ -20,7 +20,7 @@ type options struct { logger *slog.Logger } -// WithLogger makes the auditor write every audit event to logger, at +// WithLogger makes the auditor write every event it logs to logger, at // LevelAudit, instead of building its own logger. It lets a program that // embeds ToolHive route ToolHive's audit events through its own audit handler, // such as one built with toolhive-core's audit.HandlerMiddleware, which then @@ -29,6 +29,10 @@ type options struct { // // With a logger the auditor opens no log writer, so Close releases nothing, and // a Config that sets LogFile is rejected: the logger decides where events go. +// +// It applies to the Auditor and the WorkflowAuditor only. Events logged through +// a logger from NewAuditLogger, such as the OBO token-exchange events, do not +// reach it. func WithLogger(logger *slog.Logger) Option { return func(o *options) { o.logger = logger diff --git a/pkg/audit/workflow_auditor.go b/pkg/audit/workflow_auditor.go index 04f317084f..a32c07fe6b 100644 --- a/pkg/audit/workflow_auditor.go +++ b/pkg/audit/workflow_auditor.go @@ -15,11 +15,12 @@ import ( "github.com/stacklok/toolhive/pkg/auth" ) -// WorkflowAuditor provides audit logging for workflow execution. Each event -// carries the request id of the context it is logged with, set with -// toolhive-core's audit.ContextWithRequestID, as metadata.extra.request_id. +// WorkflowAuditor provides audit logging for workflow execution. // This struct abstracts workflow-specific audit operations from the // HTTP middleware-based Auditor. +// +// Each event carries the request id of the context it is logged with, set +// with toolhive-core's audit.ContextWithRequestID, as metadata.extra.request_id. type WorkflowAuditor struct { auditLogger *slog.Logger config *Config diff --git a/pkg/vmcp/server/server.go b/pkg/vmcp/server/server.go index 65f9a93ca5..c95e317695 100644 --- a/pkg/vmcp/server/server.go +++ b/pkg/vmcp/server/server.go @@ -240,12 +240,14 @@ type Config struct { // AuditConfig is nil. See audit.SubjectEnricher. AuditSubjectEnricher audit.SubjectEnricher - // AuditLogger optionally receives every audit event, both the per-request - // MCP events and the composite-tool workflow events, instead of the - // auditors' own stdout or log file logger. It lets an embedder route them - // through its own audit handler. It is set from Go only, has no effect when - // AuditConfig is nil, and is rejected together with AuditConfig.LogFile. - // See audit.WithLogger. + // AuditLogger optionally receives the events of both auditors, the + // per-request MCP events and the composite-tool workflow events, instead + // of the auditors' own stdout or log file logger. It lets an embedder route + // them through its own audit handler. It is set from Go only, has no effect + // when AuditConfig is nil, and is rejected together with + // AuditConfig.LogFile. The OBO token-exchange events of the OBO auth + // strategy are written by their own logger and do not reach it. See + // audit.WithLogger. AuditLogger *slog.Logger // HealthMonitorConfig is the optional health monitoring configuration. From 948782d7195b0c6fc1259b433a14b57685c35570 Mon Sep 17 00:00:00 2001 From: Trey Date: Thu, 3 Dec 2026 16:30:34 -0800 Subject: [PATCH 6/6] Tighten audit logger and source tests 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 stacklok/toolhive#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 Signed-off-by: Trey --- pkg/audit/options_test.go | 78 +++++++++++++++++++++------- pkg/audit/source_test.go | 45 +++++++--------- pkg/vmcp/server/audit_logger_test.go | 31 +++++++++++ 3 files changed, 110 insertions(+), 44 deletions(-) diff --git a/pkg/audit/options_test.go b/pkg/audit/options_test.go index fbe8d35c07..fda4888df7 100644 --- a/pkg/audit/options_test.go +++ b/pkg/audit/options_test.go @@ -27,6 +27,19 @@ func newCallerLogger() (*slog.Logger, *bytes.Buffer) { return slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: LevelAudit})), &buf } +// logEveryWorkflowEvent logs one event through each Log* method of auditor, +// in the order of the workflow event types. +func logEveryWorkflowEvent(ctx context.Context, auditor *WorkflowAuditor) { + auditor.LogWorkflowStarted(ctx, "wf-1", "workflow", nil, time.Minute) + auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "tool-a") + auditor.LogStepCompleted(ctx, "wf-1", "step-1", time.Second, 0) + auditor.LogStepFailed(ctx, "wf-1", "step-2", time.Second, 1, errors.New("boom")) + auditor.LogStepSkipped(ctx, "wf-1", "step-3", "false") + auditor.LogWorkflowCompleted(ctx, "wf-1", "workflow", time.Second, 3, nil) + auditor.LogWorkflowFailed(ctx, "wf-1", "workflow", time.Second, 3, errors.New("boom")) + auditor.LogWorkflowTimedOut(ctx, "wf-1", "workflow", time.Second, 3) +} + // eventTypes returns the type of each decoded audit event, in order. func eventTypes(events []map[string]any) []any { types := make([]any, 0, len(events)) @@ -48,13 +61,9 @@ func TestAuditor_WithLoggerWritesThroughCallerLogger(t *testing.T) { assert.Same(t, logger, auditor.auditLogger) assert.Nil(t, auditor.logWriter) - handler := auditor.Middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - })) + handler := auditor.Middleware(statusHandler(http.StatusOK)) handler.ServeHTTP(httptest.NewRecorder(), newToolsCallRequest()) - streamReq := httptest.NewRequest(http.MethodGet, "/mcp", nil) - streamReq.Header.Set("Accept", "text/event-stream") - handler.ServeHTTP(httptest.NewRecorder(), streamReq) + handler.ServeHTTP(httptest.NewRecorder(), newStreamOpenRequest()) events := decodeAuditEvents(t, buf) assert.Equal(t, []any{EventTypeHTTPRequest, EventTypeSSEConnection}, eventTypes(events)) @@ -73,15 +82,7 @@ func TestWorkflowAuditor_WithLoggerWritesThroughCallerLogger(t *testing.T) { assert.Same(t, logger, auditor.auditLogger) assert.Nil(t, auditor.logWriter) - ctx := context.Background() - auditor.LogWorkflowStarted(ctx, "wf-1", "workflow", nil, time.Minute) - auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "tool-a") - auditor.LogStepCompleted(ctx, "wf-1", "step-1", time.Second, 0) - auditor.LogStepFailed(ctx, "wf-1", "step-2", time.Second, 1, errors.New("boom")) - auditor.LogStepSkipped(ctx, "wf-1", "step-3", "false") - auditor.LogWorkflowCompleted(ctx, "wf-1", "workflow", time.Second, 3, nil) - auditor.LogWorkflowFailed(ctx, "wf-1", "workflow", time.Second, 3, errors.New("boom")) - auditor.LogWorkflowTimedOut(ctx, "wf-1", "workflow", time.Second, 3) + logEveryWorkflowEvent(context.Background(), auditor) assert.Equal(t, []any{ EventTypeWorkflowStarted, @@ -115,9 +116,7 @@ func TestAuditor_DefaultLoggerStampsAuditMarker(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { _ = auditor.Close() }) - auditor.Middleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusOK) - })).ServeHTTP(httptest.NewRecorder(), newToolsCallRequest()) + auditor.Middleware(statusHandler(http.StatusOK)).ServeHTTP(httptest.NewRecorder(), newToolsCallRequest()) data, err := os.ReadFile(path) require.NoError(t, err) @@ -138,7 +137,7 @@ func TestAuditor_DefaultLoggerStampsAuditMarker(t *testing.T) { assertMarked(t, decodeAuditEvents(t, bytes.NewBuffer(data))) }) - t.Run("stdout: both auditors write marked lines to stdout", func(t *testing.T) { + t.Run("stdout: both auditors use stdout and the default logger marks lines", func(t *testing.T) { t.Parallel() auditor, err := NewAuditorWithTransport(&Config{Component: "test"}, "streamable-http") require.NoError(t, err) @@ -194,3 +193,44 @@ func TestAuditor_WithLoggerAndLogFileRejected(t *testing.T) { }) } } + +func TestWithLogger_NilInputs(t *testing.T) { + t.Parallel() + + logger, _ := newCallerLogger() + tests := []struct { + name string + config *Config + logger *slog.Logger + wantLogger *slog.Logger // nil: the default logger on stdout + }{ + {name: "nil logger falls back to the default logger", config: &Config{Component: "test"}, logger: nil}, + {name: "nil config with a logger uses the logger", config: nil, logger: logger, wantLogger: logger}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + auditor, err := NewAuditorWithTransport(tt.config, "streamable-http", WithLogger(tt.logger)) + require.NoError(t, err) + workflowAuditor, err := NewWorkflowAuditor(tt.config, WithLogger(tt.logger)) + require.NoError(t, err) + + for _, got := range []struct { + logger *slog.Logger + writer any + }{ + {auditor.auditLogger, auditor.logWriter}, + {workflowAuditor.auditLogger, workflowAuditor.logWriter}, + } { + if tt.wantLogger != nil { + assert.Same(t, tt.wantLogger, got.logger) + assert.Nil(t, got.writer) + } else { + assert.NotNil(t, got.logger) + assert.Same(t, os.Stdout, got.writer) + } + } + }) + } +} diff --git a/pkg/audit/source_test.go b/pkg/audit/source_test.go index 8b97ff7f3e..bb091191eb 100644 --- a/pkg/audit/source_test.go +++ b/pkg/audit/source_test.go @@ -5,11 +5,9 @@ package audit import ( "context" - "errors" "net/http" "net/http/httptest" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -67,23 +65,27 @@ func metadataRequestID(event map[string]any) (any, bool) { func TestAuditor_SourceIgnoresForwardedHeaders(t *testing.T) { t.Parallel() - auditor, logBuf := newBufferAuditor(t) - auditor.Middleware(statusHandler(http.StatusOK)). - ServeHTTP(httptest.NewRecorder(), withForwardedHeaders(newToolsCallRequest())) - - assert.Equal(t, "192.0.2.7", sourceValue(t, requireOneEvent(t, decodeAuditEvents(t, logBuf)))) -} - -func TestAuditor_StreamOpenSourceIgnoresForwardedHeaders(t *testing.T) { - t.Parallel() + tests := []struct { + name string + req func() *http.Request + wantType string + }{ + {name: "request", req: newToolsCallRequest, wantType: EventTypeHTTPRequest}, + {name: "stream open", req: newStreamOpenRequest, wantType: EventTypeSSEConnection}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() - auditor, logBuf := newBufferAuditor(t) - auditor.Middleware(statusHandler(http.StatusOK)). - ServeHTTP(httptest.NewRecorder(), withForwardedHeaders(newStreamOpenRequest())) + auditor, logBuf := newBufferAuditor(t) + auditor.Middleware(statusHandler(http.StatusOK)). + ServeHTTP(httptest.NewRecorder(), withForwardedHeaders(tt.req())) - event := requireOneEvent(t, decodeAuditEvents(t, logBuf)) - assert.Equal(t, EventTypeSSEConnection, event["type"]) - assert.Equal(t, "192.0.2.7", sourceValue(t, event)) + event := requireOneEvent(t, decodeAuditEvents(t, logBuf)) + assert.Equal(t, tt.wantType, event["type"]) + assert.Equal(t, "192.0.2.7", sourceValue(t, event)) + }) + } } func TestAuditor_RequestIDFromOuterMiddleware(t *testing.T) { @@ -157,14 +159,7 @@ func TestWorkflowAuditor_RequestIDFromContext(t *testing.T) { // Every Log* method, including those that set their own metadata. ctx := coreaudit.ContextWithRequestID(context.Background(), "r-1") - auditor.LogWorkflowStarted(ctx, "wf-1", "workflow", nil, time.Minute) - auditor.LogStepStarted(ctx, "wf-1", "step-1", "tool", "tool-a") - auditor.LogStepCompleted(ctx, "wf-1", "step-1", time.Second, 0) - auditor.LogStepFailed(ctx, "wf-1", "step-2", time.Second, 1, errors.New("boom")) - auditor.LogStepSkipped(ctx, "wf-1", "step-3", "false") - auditor.LogWorkflowCompleted(ctx, "wf-1", "workflow", time.Second, 3, nil) - auditor.LogWorkflowFailed(ctx, "wf-1", "workflow", time.Second, 3, errors.New("boom")) - auditor.LogWorkflowTimedOut(ctx, "wf-1", "workflow", time.Second, 3) + logEveryWorkflowEvent(ctx, auditor) // An event logged with a context that carries no id has none. auditor.LogStepStarted(context.Background(), "wf-2", "step-1", "tool", "tool-a") diff --git a/pkg/vmcp/server/audit_logger_test.go b/pkg/vmcp/server/audit_logger_test.go index 3b8dc253db..f1d4f59e71 100644 --- a/pkg/vmcp/server/audit_logger_test.go +++ b/pkg/vmcp/server/audit_logger_test.go @@ -7,9 +7,13 @@ import ( "bytes" "context" "encoding/json" + "io" + "io/fs" "log/slog" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "sync" "testing" @@ -110,3 +114,30 @@ func TestServer_AuditLoggerReachesBothAuditors(t *testing.T) { assert.Contains(t, types, audit.EventTypeWorkflowStarted, "the workflow auditor writes to Config.AuditLogger") assert.Contains(t, types, audit.EventTypeWorkflowCompleted, "the workflow auditor writes to Config.AuditLogger") } + +// TestServer_AuditLoggerWithLogFileRejected pins that a server given both +// Config.AuditLogger and an AuditConfig.LogFile fails to build and opens no +// file. +func TestServer_AuditLoggerWithLogFileRejected(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + path := filepath.Join(t.TempDir(), "audit.log") + logger := slog.New(slog.NewJSONHandler(io.Discard, nil)) + + _, err := New(t.Context(), &Config{ + Host: "127.0.0.1", + Port: 0, + Aggregator: aggmocks.NewMockAggregator(ctrl), + SessionFactory: sessionmocks.NewMockMultiSessionFactory(ctrl), + AuditConfig: &audit.Config{Component: "test", LogFile: path}, + AuditLogger: logger, + }, routermocks.NewMockRouter(ctrl), vmcpmocks.NewMockBackendClient(ctrl), + vmcp.NewImmutableRegistry(nil), nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "logFile") + assert.Contains(t, err.Error(), "WithLogger") + + _, statErr := os.Stat(path) + assert.ErrorIs(t, statErr, fs.ErrNotExist, "no log file is opened") +}