// Copyright 2026 Josh Waldrep // SPDX-License-Identifier: Apache-2.0 package mcp import ( "bytes" "context" "crypto/ed25519" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "runtime" "sort" "strings" "sync" "time" "github.com/luckyPipewrench/pipelock/internal/capture" "github.com/luckyPipewrench/pipelock/internal/config" decide "github.com/luckyPipewrench/pipelock/internal/decide" "github.com/luckyPipewrench/pipelock/internal/envcontrol" "github.com/luckyPipewrench/pipelock/internal/hitl" "github.com/luckyPipewrench/pipelock/internal/jsonscan" "github.com/luckyPipewrench/pipelock/internal/killswitch" "github.com/luckyPipewrench/pipelock/internal/mcp/integrity" "github.com/luckyPipewrench/pipelock/internal/mcp/jsonrpc" "github.com/luckyPipewrench/pipelock/internal/mcp/provenance" "github.com/luckyPipewrench/pipelock/internal/mcp/tools" "github.com/luckyPipewrench/pipelock/internal/mcp/transport" "github.com/luckyPipewrench/pipelock/internal/receipt" "github.com/luckyPipewrench/pipelock/internal/scanner" session "github.com/luckyPipewrench/pipelock/internal/session" "github.com/luckyPipewrench/pipelock/internal/signing" "github.com/luckyPipewrench/pipelock/internal/wsutil" ) // ErrSubprocessExit indicates the wrapped MCP server process exited with a // non-zero status. This is an expected operational event (the MCP server // crashed or was misconfigured), not a pipelock internal error. Callers // should log it but not report it to error tracking services. var ErrSubprocessExit = errors.New("subprocess exited") // syncWriter wraps an io.Writer with a mutex to make concurrent writes safe. // Used in RunProxy where multiple goroutines write to clientOut and logW. type syncWriter struct { mu sync.Mutex w io.Writer } // Compile-time assertion: syncWriter implements transport.MessageWriter. var _ transport.MessageWriter = (*syncWriter)(nil) func (sw *syncWriter) Write(p []byte) (int, error) { sw.mu.Lock() defer sw.mu.Unlock() return sw.w.Write(p) } // WriteMessage writes a JSON-RPC message followed by a newline in a single // Write call under the mutex, preventing interleaving between concurrent // goroutines (e.g., the blocked request drainer and ForwardScanned). func (sw *syncWriter) WriteMessage(msg []byte) error { sw.mu.Lock() defer sw.mu.Unlock() if len(msg) > transport.MaxLineSize { return fmt.Errorf("message too large: %d bytes", len(msg)) } buf := make([]byte, len(msg)+1) copy(buf, msg) buf[len(msg)] = '\n' if _, err := sw.w.Write(buf); err != nil { return fmt.Errorf("writing message: %w", err) } return nil } // drainStderr waits for the wrapped process's stderr copier without allowing // an escaped descendant holding the write end to keep RunProxy alive. Closing // the read end releases io.Copy on timeout and also releases the descriptor // after a normal drain. func drainStderr(stderrDone <-chan struct{}, serverErr io.Closer, grace time.Duration) bool { if grace <= 0 { grace = defaultParentExitGrace } select { case <-stderrDone: _ = serverErr.Close() return true case <-time.After(grace): _ = serverErr.Close() return false } } func emitPendingTimeoutResponses(writer transport.MessageWriter, logW io.Writer, tracker *RequestTracker, opts MCPProxyOpts) { if tracker == nil { return } for _, pending := range tracker.DrainPendingOutcomes() { resp := timeoutErrorResponse(pending.ID) if wErr := writer.WriteMessage(resp); wErr != nil { _, _ = fmt.Fprintf(logW, "pipelock: failed to send timeout response: %v\n", wErr) } pending.Outcome.settle(logW, opts, "error", int64(len(resp)), "response_timeout") } } func emitPendingIncompleteOutcomes(logW io.Writer, tracker *RequestTracker, opts MCPProxyOpts, reason string) { if tracker == nil { return } for _, pending := range tracker.DrainPendingOutcomes() { pending.Outcome.settle(logW, opts, "incomplete", -1, reason) } } // isResponse returns true if msg is a JSON-RPC response (has "result" or "error" // field). Messages with only a "method" field (server-initiated requests) return // false. A message with both "method" and "result" is treated as a response // (security-conservative: if it carries a result payload, validate its ID). func isResponse(msg []byte) bool { var probe struct { Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } if json.Unmarshal(msg, &probe) != nil { return false } return len(probe.Result) > 0 || len(probe.Error) > 0 } // isRequest returns true if msg is a JSON-RPC request (has "method" field and // is not a response). Used to guard tracker.Track so only outbound client // requests are tracked, not client responses to server-initiated calls. func isRequest(msg []byte) bool { var probe struct { Method string `json:"method"` Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } if json.Unmarshal(msg, &probe) != nil { return false } return probe.Method != "" && len(probe.Result) == 0 && len(probe.Error) == 0 } // ForwardScanned reads JSON-RPC 2.0 messages from reader, scans each for prompt // injection and enforceable inbound DLP, and forwards to writer based on the // scanner's configured action (warn, block, strip). Scan verdicts are logged to logW. // When toolCfg is non-nil, tool descriptions in tools/list responses are scanned // for poisoning and tracked for drift (rug pull) detection. Tool scanning runs // independently of general response scanning so a "block" tool action is never // bypassed by a "warn" general action. // When tracker is non-nil, response IDs are validated against previously tracked // request IDs to prevent confused deputy attacks (unsolicited responses). // When rec is non-nil and adaptiveCfg is enabled, threat signals are recorded // and the effective action may be upgraded based on session escalation level. // When ks is non-nil, the kill switch is checked on each message so activation // mid-stream terminates already-open sessions immediately. // Returns true if any response security finding was detected. func ForwardScanned(reader transport.MessageReader, writer transport.MessageWriter, logW io.Writer, tracker *RequestTracker, opts MCPProxyOpts) (bool, error) { opts = opts.snapshotScanPolicy() if opts.ServerIdentityFn != nil { writer = &serverIdentityMessageWriter{writer: writer, opts: opts} } sc := opts.scanner() approver := opts.Approver toolCfg := opts.toolCfg() // A scanner can be supplied independently of the proxy's tool config. // Preserve description checking even for callers that omit the latter. _, descriptionDecider := sc.InjectionCheckers().Decider(config.InjectionSurfaceMCPToolDescription) if toolCfg == nil && (descriptionDecider || sc.InjectionCheckers().Watches(config.InjectionSurfaceMCPToolDescription)) { // ack-exempt: the caller supplied no tool configuration to carry acknowledgments from. toolCfg = &tools.ToolScanConfig{Action: config.ActionWarn} } if toolCfg != nil && (opts.validateToolHeaders || opts.toolContractDiscovery) { copyCfg := *toolCfg copyCfg.RequireHeaderContracts = true copyCfg.ContractDiscovery = opts.toolContractDiscovery toolCfg = ©Cfg } ks := opts.KillSwitch rec := opts.Rec adaptiveCfg := opts.adaptiveCfg() m := opts.Metrics obs := opts.captureObserver() mediaPolicy := opts.mediaPolicy() receiptEmitter := opts.receiptEmitter() provenanceCfg := opts.provenanceCfg() respScanOpts := opts.responseScanOptions() resetFile := opts.AdaptiveResetFile taintOpts := opts taintOpts.TaintCfg = opts.taintCfg() taintOpts.TaintCfgFn = nil // blockAll tracks whether the session is at a critical escalation level // with block_all=true. Checked once up front and refreshed after each // message so mid-stream escalation takes effect immediately. blockAll := rec != nil && decide.UpgradeAction("", rec.EscalationLevel(), adaptiveCfg) == config.ActionBlock if blockAll { _, _ = fmt.Fprintf(logW, "pipelock: session deny — escalation level %s, blocking all responses\n", session.EscalationLabel(rec.EscalationLevel())) } foundInjection := false // lineNum counts non-empty messages, not raw lines. StdioReader skips // empty lines internally, so this is a message index. ScanStream (scan.go) // preserves raw line counting for user-facing diagnostics. lineNum := 0 var claimedOutcome TrackedRequestOutcome settleUndelivered := func() { if claimedOutcome.handle != nil { claimedOutcome.settle(logW, opts, "incomplete", -1, "response_not_delivered") claimedOutcome = TrackedRequestOutcome{} } } defer settleUndelivered() for { settleUndelivered() line, err := reader.ReadMessage() if err != nil { // A clean stream end is io.EOF; a proxy-initiated connection // teardown surfaces net.ErrClosed ("use of closed network // connection"), and a peer drop surfaces as reset/broken-pipe, // from a blocked transport read. All mean "no more traffic to // scan", not a fatal error. IsExpectedCloseErr covers io.EOF too. if wsutil.IsExpectedCloseErr(err) && !errors.Is(err, transport.ErrIncompleteResponse) { break } if opts.sessionExit.inProgress() && isSessionExitCloseErr(err) { break } // Upstream response timeout: return the sentinel so the owning // transport tears down the hung upstream and decides the failure // scope. Returning (not break) is load-bearing: a clean-EOF break // would let RunProxy fall into cmd.Wait() on a still-alive child // (blocking forever) and let the HTTP bridge loop keep accepting // requests against a dead upstream. if errors.Is(err, transport.ErrResponseTimeout) { _, _ = fmt.Fprintf(logW, "pipelock: upstream response timeout\n") return foundInjection, transport.ErrResponseTimeout } return foundInjection, fmt.Errorf("reading input: %w", err) } lineNum++ var denialAudit mcpDenialAudit if err := opts.checkServerIdentity(); err != nil { dropMCPDenial(opts, mcpIdentityMcpResponseDenialAudit(), "response") return foundInjection, &mcpFinalizedDenialError{err: err} } // Parse the inbound frame once per message; every gate below reads // ID / Method / tool fields from this frame instead of re-parsing. frame := ParseMCPFrame(line) // Key rejection must precede tracker consumption, adaptive recovery, // tool drift promotion, inventory reservations and taint observations. if frame.KeyValidationErr != nil { detected, outbound, err := rejectResponseKeys(frame, lineNum, sc, writer, logW, opts) foundInjection = foundInjection || detected if err != nil { return foundInjection, err } emitRejectedResponseOutcome(frame.Raw, outbound, logW, tracker, opts) continue } if opts.OnResponseKeysValidated != nil { opts.OnResponseKeysValidated() } // Kill switch: deny all responses when activated mid-stream. // Checked per message so activation after session start takes effect // immediately on already-open MCP sessions. if ks != nil { if d := ks.IsActiveMCP(line); d.Active { denialAudit = mcpKillMcpResponseDenialAudit() rpcID := frame.ID if rpcID == nil { dropMCPDenial(opts, denialAudit, "response") // Notification: drop silently (no response possible). _, _ = fmt.Fprintf(logW, "pipelock: response line %d: kill switch dropped notification (source=%s)\n", lineNum, d.Source) continue } _, _ = fmt.Fprintf(logW, "pipelock: response line %d: kill switch denied (source=%s)\n", lineNum, d.Source) resp := killswitch.ErrorResponse(rpcID, d.Message) if wErr := writeMCPDenial(opts, denialAudit, writer, resp); wErr != nil { return foundInjection, fmt.Errorf("writing kill switch response: %w", wErr) } continue } } // Private inventory inspection cannot lower the caller's security state. // Ordinary response streams retain their on-entry recovery policy. if !opts.toolContractDiscovery { tryRecoverSession(rec, adaptiveCfg, adaptiveRecoveryContextWithWarnContext(adaptiveRecoveryContext{ sessionKey: opts.adaptiveSessionKey(), reason: adaptiveRecoveryTimer, logger: opts.AuditLogger, metrics: m, }, opts.warnContext())) } // A signed operator delegation is the only path that clears a stdio // airlock. A malformed, expired, replayed, or absent authority leaves // the existing escalation in place. if resetFile != "" && rec != nil && opts.AdaptiveResetAuthority != nil && opts.AdaptiveResetEpoch != nil { if r, ok := rec.(adaptiveResetter); ok { decision := consumeAdaptiveResetFile(resetFile, opts.AdaptiveResetAuthority, opts.AdaptiveResetEpoch, logW) auditResetAuthorityDecision(opts.AuditLogger, opts.AdaptiveResetAuthority.Target(), decision) recordResetAuthorityCapacity(m, decision) if decision.Result == ResetAuthorityAccepted { prevScore, prevLevel := r.Reset() blockAll = false _, _ = fmt.Fprintf(logW, "pipelock: adaptive enforcement reset by operator (score %.1f to 0, level %s to normal)\n", prevScore, session.EscalationLabel(prevLevel)) } } } // block_all enforcement: write a JSON-RPC error for every message when // the session is at an escalation level with block_all=true. Refresh // on each message so mid-stream escalation AND recovery both take // effect immediately on already-open MCP sessions. if rec != nil && adaptiveCfg != nil && adaptiveCfg.Enabled { wasBlocked := blockAll blockAll = decide.UpgradeAction("", rec.EscalationLevel(), adaptiveCfg) == config.ActionBlock if blockAll && !wasBlocked { _, _ = fmt.Fprintf(logW, "pipelock: session deny — escalation level %s, blocking all responses\n", session.EscalationLabel(rec.EscalationLevel())) } } if blockAll { denialAudit = mcpAdaptiveResponseDenialAudit() rpcID := frame.ID // Notifications (no ID) must not receive a response per JSON-RPC spec. // Drop them silently instead of writing an error. if rpcID == nil { dropMCPDenial(opts, denialAudit, "response") continue } resp := blockSessionDenyResponse(rpcID, mcpAdaptiveBlockMessage(rec, adaptiveCfg, "session_deny", logW)) if wErr := writeMCPDenial(opts, denialAudit, writer, resp); wErr != nil { return foundInjection, fmt.Errorf("writing session deny: %w", wErr) } continue } // MCP does not use JSON-RPC batch messages (top-level arrays). // A batch from the server is either malformed or an attempt to // bypass per-message ID validation. Fail closed. Use the parsed // frame: WebSocket and SSE can preserve leading whitespace that // a raw first-byte check would miss. if frame.IsBatch { dropMCPDenial(opts, mcpBatchResponseDenialAudit(), "response") _, _ = fmt.Fprintf(logW, "pipelock: line %d: blocked batch JSON-RPC message (not supported by MCP)\n", lineNum) continue } // Confused deputy: validate response IDs against tracked requests. // Only check actual responses (have "result" or "error"), not // server-initiated requests (have "method") which use their own IDs. // The Seeded() gate defers validation until the first client request // is tracked. This prevents a race where a fast server response // arrives before ForwardScannedInput tracks the outbound request ID // (concurrent goroutines). The window is not exploitable: before any // client request, no valid request ID exists to hijack. var trackedOutcome TrackedRequestOutcome var hasTrackedOutcome bool var trackedMethod string if tracker != nil && tracker.Seeded() && isResponse(line) { rpcID := frame.ID // Once a request has been tracked, every result/error envelope must // carry an ID that can be consumed from the pending set. The unseeded // check above retains the initialization-race exception for a server's // parse error before the first client request is recorded. if canonicalID(rpcID) == "" { _, _ = fmt.Fprintf(logW, "pipelock: line %d: confused deputy: response has no correlatable ID\n", lineNum) denialAudit = mcpCorrelationResponseDenialAudit() resp := blockResponseReason(nil, "response has no correlatable ID (confused deputy)") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing confused deputy block: %w", err) } continue } if rpcID != nil { var valid bool trackedOutcome, valid = tracker.Consume(rpcID) if valid { trackedMethod = trackedOutcome.Method } if !valid { _, _ = fmt.Fprintf(logW, "pipelock: line %d: confused deputy: unsolicited response ID %s\n", lineNum, string(rpcID)) blockID := rpcID if tracker.Strict() { blockID = nil } denialAudit = mcpCorrelationResponseDenialAudit() resp := blockResponseReason(blockID, "unsolicited response ID (confused deputy)") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing confused deputy block: %w", err) } continue } hasTrackedOutcome = trackedOutcome.Receipt.ActionID != "" if !opts.listenerOwnsResponseOutcome { claimedOutcome = trackedOutcome } } } emitTrackedOutcome := func(status, reason string, outbound []byte) { if !hasTrackedOutcome { return } if opts.bufferedResponseOutcome != nil { opts.bufferedResponseOutcome(status, reason, int64(len(outbound))) } else { trackedOutcome.settle(logW, opts, status, int64(len(outbound)), reason) } claimedOutcome = TrackedRequestOutcome{} } blockScanError := func(scanError string) error { _, _ = fmt.Fprintf(logW, "pipelock: line %d: %s\n", lineNum, scanError) denialAudit = mcpResponseInspectionBlockAudit("MCP response scan failed") if frame.ID == nil && frame.Method != "" { dropMCPDenial(opts, denialAudit, "response") return nil // Notifications have no request awaiting a response. } resp := blockResponseReason(frame.ID, "upstream response scan failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return fmt.Errorf("writing scan-error block response: %w", err) } emitTrackedOutcome("error", "response_scan_error", resp) return nil } if err := opts.warnContext().Err(); err != nil { if writeErr := blockScanError("response scan failed: " + err.Error()); writeErr != nil { return foundInjection, writeErr } continue } mediaResult := applyMCPResponseMediaPolicy(line, mediaPolicy, opts.Transport) if len(mediaResult.Exposures) > 0 && opts.AuditLogger != nil { rpcID := frame.ID target := mcpServerResponse if requestID := canonicalID(rpcID); requestID != "" { target = "response:" + requestID } actx := mustMCPAuditContext(opts.AuditLogger, mcpWarnMethod, target) for _, info := range mediaResult.Exposures { opts.AuditLogger.LogMediaExposure(actx, info) } } if mediaResult.Blocked { rpcID := frame.ID requestID := canonicalID(rpcID) target := mcpServerResponse if requestID != "" { target = "response:" + requestID } _, _ = fmt.Fprintf(logW, "pipelock: line %d: media policy blocked MCP response (%s)\n", lineNum, mediaResult.BlockReason) denialAudit = mcpMediaDenialAudit(mediaResult) if m != nil { m.RecordBlocked("mcp", "media_policy", 0, "") } if receiptEmitter != nil || opts.ReceiptGroup != nil { if _, emitErr := opts.emitReceiptDecision(MCPDecision{ Receipt: opts.withReceiptPolicyHash(receipt.EmitOpts{ ActionID: receipt.NewActionID(), Verdict: config.ActionBlock, Transport: opts.Transport, Target: target, RequestID: requestID, Layer: "media_policy", Pattern: mediaResult.BlockReason, Severity: config.SeverityHigh, }), }); emitErr != nil { logReceiptEmitFailure(logW, emitErr, opts.requireReceipts(), config.ActionBlock) } } // The refused media is content the server sent. Keep the block // and record only the zero-point observation. if adaptiveCfg != nil && adaptiveCfg.Enabled { recordMCPAdaptiveSignal(opts, rec, upstreamContentSignal(), decide.EscalationParams{ Threshold: adaptiveCfg.EscalationThreshold, Logger: opts.AuditLogger, Metrics: m, ConsoleWriter: logW, Session: opts.adaptiveSessionKey(), DenialScanner: "media_policy", DenialReason: mediaResult.BlockReason, PolicyHash: opts.receiptPolicyHash(), }) } resp := blockMediaPolicyResponse(rpcID, mediaResult.BlockReason) if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing media policy block: %w", err) } emitTrackedOutcome("error", "media_policy", resp) continue } if mediaResult.Changed { if emitErr := confirmMCPResponseEffect(logW, opts, trackedOutcome.Receipt, receipt.EmitOpts{ActionID: receipt.NewActionID(), Verdict: config.ActionStrip, Layer: "media_policy", Pattern: "image media rewritten", Transport: opts.Transport, Target: "mcp://response", RequestID: canonicalID(frame.ID)}); emitErr != nil { denialAudit = mcpOperationalBlockAudit(scanner.AuditReceiptEmission, "mcp_response", mcpReceiptEmissionReason) resp := blockResponseReason(frame.ID, "receipt emission failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing media receipt-failure block: %w", err) } emitTrackedOutcome("error", "receipt_emission_failed", resp) continue } } line = mediaResult.Line // Tool scanning runs first. tools/list responses contain instructional // text ("you must call this tool") that the general injection scanner // would flag as false positives. The dedicated tool scanner uses // purpose-built poisoning patterns instead. When tool scanning // identifies a message as tools/list, skip the general scan entirely. isToolsList := false var toolResult tools.ToolScanResult toolInventoryResolved := false resolveToolInventory := func(decision string) { if decision == "" { return } if opts.toolInventoryResolution != nil && !opts.toolContractDiscovery { opts.toolInventoryResolution(decision) } else if manager := opts.deferManager(); manager != nil { manager.ResolveToolInventory(captureSessionID(opts.Transport), decision) } toolInventoryResolved = true } // Commit tool names only after the exact response that carried them is // allowed through. A blocked tools/list must not become a trusted // session-binding baseline merely because tool scanning runs before the // response scanner. var toolInventoryReservation *tools.ToolInventoryReservation reserveToolInventory := func() error { if opts.toolContractDiscovery || !isToolsList || toolCfg == nil || toolCfg.Baseline == nil || len(toolResult.ToolNames) == 0 && len(toolResult.ToolDefs) == 0 { return nil } // x-mcp-header contracts belong to the 2026-07-28 tools/list. A // server answering an older revision follows that revision (MCP // 2026-07-28 Streamable HTTP, "Earlier Streamable HTTP Revisions"), // so its inventory records delivery but never the current contract. // Otherwise an unannotated legacy definition would read as a known // contract and let modern calls skip discovery and mirror checks. defs := toolResult.ToolDefs if !opts.validateToolHeaders { defs = nil } var err error toolInventoryReservation, err = toolCfg.Baseline.ReserveToolInventory(toolResult.ToolNames, defs) return err } applyToolInventory := func() { if toolInventoryReservation == nil { return } added := toolInventoryReservation.Commit(toolResult.Clean) decision := "" for _, name := range added { _, _ = fmt.Fprintf(logW, "pipelock: tool %q added post-baseline\n", name) } if len(added) > 0 { decision = config.ActionBlock } else if toolCfg.Baseline.HasBaseline() && !toolCfg.HeaderContractsOnly { // Structural collection never scanned these definitions, so it // cannot be the affirmative inventory signal that releases a hold. decision = config.ActionAllow } if !toolInventoryResolved { resolveToolInventory(decision) } } commitToolInventory := func() { if toolInventoryReservation == nil { return } if opts.toolInventoryDelivery != nil { opts.toolInventoryDelivery(applyToolInventory, toolInventoryReservation.Release) } else { applyToolInventory() } } releaseToolInventory := func() { if toolInventoryReservation != nil { toolInventoryReservation.Release() } } // toolPoisonDetected tracks whether a tool-poisoning finding was raised // for this message (even in warn mode). A message that raised a // tool-poison near-miss signal must not also apply RecordClean: the // same message cannot both raise and decay the session threat score. toolPoisonDetected := false // toolAcknowledged marks a tools/list whose Credential Request // Directive finding a configured acknowledgment lifted. It is not // evidence of clean behavior, so it earns no clean credit either. toolAcknowledged := false if toolCfg != nil { toolResult = tools.ScanToolsForMethodContext(opts.warnContext(), line, sc, toolCfg.WithServerMode(opts.ServerName, opts.ServerBinding, opts.ServerBindingMode, opts.ServerRevision), trackedMethod) if err := opts.warnContext().Err(); err != nil { if writeErr := blockScanError("response scan failed: " + err.Error()); writeErr != nil { return foundInjection, writeErr } continue } isToolsList = toolResult.IsToolsList toolAcknowledged = toolResult.IsToolsList && toolResult.CredentialAckApplied() // Provenance: verify tool signatures BEFORE updating session binding // baseline. A blocked tools/list must not seed known tools. if toolResult.IsToolsList && provenanceCfg != nil && provenanceCfg.Enabled { pv := VerifyToolsListProvenance(line, provenanceCfg) if pv.Block { resolveToolInventory(config.ActionBlock) _, _ = fmt.Fprintf(logW, "pipelock: line %d: tools/list provenance verification failed: %s\n", lineNum, pv.Error) denialAudit = mcpProvenanceDenialAudit() if m != nil { m.RecordBlocked("mcp", "provenance", 0, "") } resp := blockResponseReason(toolResult.RPCID, "tool provenance verification failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing provenance block: %w", err) } emitTrackedOutcome("error", "provenance", resp) continue } if pv.Error != "" { _, _ = fmt.Fprintf(logW, "pipelock: line %d: tools/list provenance warning: %s\n", lineNum, pv.Error) } // Log unsigned tools in warn mode for operator visibility. for _, r := range pv.Results { if r.Status != provenance.StatusVerified { _, _ = fmt.Fprintf(logW, "pipelock: line %d: tool %q unsigned (provenance warn)\n", lineNum, r.ToolName) if opts.AuditLogger != nil { opts.AuditLogger.LogAnomaly(mustMCPAuditContext(opts.AuditLogger, "MCP", r.ToolName), "provenance", "unsigned tool", 0) } } } } // Capture: record tools/list scan verdict. captureToolScan := func(toolCaptureAction string) { obs.ObserveToolScanVerdict(context.Background(), &capture.ToolScanRecord{ Subsurface: "mcp_tools_list", Transport: opts.Transport, SessionID: captureSessionID(opts.Transport), SessionIDOriginal: captureSessionIDOriginal(opts.Transport), ConfigHash: opts.captureConfigHash(), Profile: opts.captureProfile(), ActionClass: captureMCPActionClass("", "tools/list"), Request: capture.CaptureRequest{RPCID: captureRPCID(toolResult.RPCID)}, RawFindings: toolScanResultFindings(toolResult), EffectiveAction: toolCaptureAction, Outcome: captureOutcome(toolCaptureAction, toolResult.Clean && !toolAcknowledged), }) } // An acknowledged list is captured after its receipt decision below, // so the tool-scan record reflects that receipt decision. // Later gates record their own refusals. if toolResult.IsToolsList && (!toolAcknowledged || !toolResult.Clean) { toolCaptureAction := config.ActionAllow if !toolResult.Clean { if toolResult.ResourceLimit != "" || toolResult.CredentialAckRefused() || toolResult.CheckerBlocked() { // Both refuse under every action, so record the block. toolCaptureAction = config.ActionBlock } else if toolCfg.Action != "" { toolCaptureAction = toolCfg.Action } else { toolCaptureAction = config.ActionBlock } } captureToolScan(toolCaptureAction) } // Accepted definition drift is not a finding and does not affect the // verdict, so it is reported here rather than on the block path. An // upstream changing a tool under an approved baseline is something // the operator must be able to see even when it is allowed. if toolResult.IsToolsList && len(toolResult.Observations) > 0 { tools.LogToolObservations(logW, lineNum, toolResult) } if toolResult.IsToolsList && !toolResult.Clean { resolveToolInventory(config.ActionBlock) } if toolResult.IsToolsList && !toolResult.Clean { foundInjection = true toolPoisonDetected = true tools.LogToolFindings(logW, lineNum, toolResult) toolAction := toolCfg.Action if toolResult.ResourceLimit != "" { // A capacity result means the response cannot become a complete // security baseline. Policy warn/strip would forward an // uninspectable definition, so this outcome is always a block. toolAction = config.ActionBlock } if toolResult.CheckerBlocked() { // The selected external checker found injection in block // mode. Its mode, not mcp_tool_scanning.action, decides. toolAction = config.ActionBlock } if toolResult.CredentialAckRefused() { // A configured acknowledgment that no longer matches its // tool is a reviewed exception gone stale. It refuses under // every action rather than quietly becoming a warning. toolAction = config.ActionBlock } // Escalation upgrade for tool poison detection. Hard floors above // keep their own reason even when the configured action is warn. preAdaptiveToolAction := toolAction if rec != nil { toolAction = decide.UpgradeAction(toolAction, rec.EscalationLevel(), adaptiveCfg) if toolAction != preAdaptiveToolAction { // Emit adaptive-upgrade telemetry when escalation changed the action. _, _ = fmt.Fprintf(logW, "pipelock: line %d: adaptive upgrade tool-poison %s->%s (level=%s)\n", lineNum, preAdaptiveToolAction, toolAction, session.EscalationLabel(rec.EscalationLevel())) if m != nil { m.RecordAdaptiveUpgrade(preAdaptiveToolAction, toolAction, session.EscalationLabel(rec.EscalationLevel())) } } } if toolAction == config.ActionBlock { _ = emitMCPToolScanReceipt(logW, opts, toolResult, config.ActionBlock, trackedOutcome.Receipt) blockReason := "tool poisoning detected in tools/list" if toolResult.ResourceLimit != "" { blockReason = "tools/list cannot be safely inspected: " + toolResult.ResourceLimit if m != nil { m.RecordBlocked("mcp", toolResult.ResourceLimit, 0, "") } } else if toolResult.CredentialAckRefused() { blockReason = "tools/list refused: a credential-request acknowledgment no longer matches its tool" } else if toolResult.CheckerBlocked() { blockReason = "tools/list refused: the selected injection checker found injection in a tool description" } else if toolScanHasDrift(toolResult) && toolCfg.DriftRemediation != "" { blockReason = "tool definition drift detected; " + toolCfg.DriftRemediation } // Preserve the resolved enforcement cause before adaptive caller // wording can replace the reply's explanation. denialAudit = mcpToolResultDenialAudit(toolResult.ResourceLimit, blockReason) // A blocked tool definition is content the server sent. Keep the // block and record only the zero-point observation. if adaptiveCfg != nil && adaptiveCfg.Enabled { recordMCPAdaptiveSignal(opts, rec, upstreamContentSignal(), decide.EscalationParams{ Threshold: adaptiveCfg.EscalationThreshold, Logger: opts.AuditLogger, Metrics: m, ConsoleWriter: logW, Session: opts.adaptiveSessionKey(), DenialScanner: "tool_scanning", DenialReason: blockReason, PolicyHash: opts.receiptPolicyHash(), }) } if toolAction != preAdaptiveToolAction { blockReason = strings.TrimPrefix(mcpAdaptiveBlockMessage(rec, adaptiveCfg, "tool_scanning", logW), "pipelock: ") } resp := blockResponseReason(toolResult.RPCID, blockReason) if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing tool block: %w", err) } emitTrackedOutcome("error", "tool_poisoning", resp) continue } if emitErr := emitMCPToolScanReceipt(logW, opts, toolResult, config.ActionWarn, trackedOutcome.Receipt); emitErr != nil && opts.requireReceipts() { denialAudit = mcpOperationalBlockAudit(scanner.AuditReceiptEmission, "mcp_response", mcpReceiptEmissionReason) resp := blockResponseReason(toolResult.RPCID, "receipt emission failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing receipt-failure block: %w", err) } emitTrackedOutcome("error", "receipt_emission_failed", resp) continue } // Warn: preserve the observation without enforcement points. if adaptiveCfg != nil && adaptiveCfg.Enabled { recordMCPAdaptiveSignal(opts, rec, session.SignalWarning, decide.EscalationParams{ Threshold: adaptiveCfg.EscalationThreshold, Logger: opts.AuditLogger, Metrics: m, ConsoleWriter: logW, Session: opts.adaptiveSessionKey(), DenialScanner: "tool_scanning", DenialReason: "tool poisoning detected in tools/list", PolicyHash: opts.receiptPolicyHash(), }) } } if toolAcknowledged && toolResult.Clean { // The tool scanner allowed this list under a reviewed // acknowledgment. The receipt and capture record that scanner // decision with an allow verdict; it is not a near miss and not // a clean event. Later gates (general response scanning, // inventory reservation) can still refuse delivery, and record // that themselves. if emitErr := emitMCPToolScanReceipt(logW, opts, toolResult, config.ActionAllow, trackedOutcome.Receipt); emitErr != nil && opts.requireReceipts() { denialAudit = mcpOperationalBlockAudit(scanner.AuditReceiptEmission, "mcp_response", mcpReceiptEmissionReason) captureToolScan(config.ActionBlock) resolveToolInventory(config.ActionBlock) resp := blockResponseReason(toolResult.RPCID, "receipt emission failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing receipt-failure block: %w", err) } emitTrackedOutcome("error", "receipt_emission_failed", resp) continue } // The tool scanner passed it with a finding present: warned, // never clean. captureToolScan(config.ActionWarn) } } if isToolsList && opts.validateToolHeaders && !opts.toolContractDiscovery { filtered, names, rejected, err := tools.FilterInvalidHeaderTools(line, toolResult.ToolDefs) if err != nil { if writeErr := blockScanError("invalid tool header contract response"); writeErr != nil { return foundInjection, writeErr } continue } if len(rejected) > 0 { // A filtered inventory is not affirmative approval evidence for held // actions, even when the remaining definitions scanned cleanly. resolveToolInventory(config.ActionBlock) } for name, reason := range rejected { _, _ = fmt.Fprintf(logW, "pipelock: tool %q excluded: %q\n", name, reason) } line = filtered toolResult.ToolNames = names } // For tools/list responses, skip general scanning of the result field // (tool descriptions contain instructional text that triggers FPs). // Still scan the error field: injection could hide in non-tool fields. var verdict jsonrpc.ScanVerdict var baselineReceiptErr error // Structural collection is not a dedicated content scan. Preserve the // nil-tool-config full-response scanning contract (ScanResponseDispatch) // rather than exempting tool descriptions that nobody has inspected. if isToolsList && !toolCfg.HeaderContractsOnly { verdict = scanToolsListNonToolFieldsContext(opts.warnContext(), line, sc, respScanOpts) } else { a2aOpts := opts.a2aResponseOpts(respScanOpts) a2aOpts.Method = trackedMethod if opts.requireReceipts() { a2aOpts.ConfirmCardAcceptance = func(candidate AgentCardScanResult) error { selected := trackedOutcome.Receipt if !selected.ShardSelected && opts.ReceiptGroup != nil && opts.ReceiptGroup.Shards != nil { selected = opts.ReceiptGroup.Shards.Admit(selected) } if candidate.SignatureVerified { baselineReceiptErr = confirmMCPResponseEffect(logW, opts, selected, receipt.EmitOpts{ActionID: receipt.NewActionID(), Verdict: config.ActionAllow, Layer: "a2a_card_signature", Pattern: "verified key_id=" + candidate.SignatureKeyID, Transport: opts.Transport, Target: "mcp://response", RequestID: canonicalID(frame.ID)}) if baselineReceiptErr != nil { return baselineReceiptErr } } if !candidate.FirstSeen && !candidate.DriftAdopted { return nil } baselineReceiptErr = confirmMCPResponseEffect(logW, opts, selected, receipt.EmitOpts{ActionID: receipt.NewActionID(), Verdict: config.ActionAllow, Layer: "a2a_card_drift", Pattern: "Agent Card baseline accepted", Transport: opts.Transport, Target: "mcp://response", RequestID: canonicalID(frame.ID)}) return baselineReceiptErr } } a2aOpts.OnCardDriftAdopted = func() { const detail = "a2a: Agent Card descriptive drift adopted" _, _ = fmt.Fprintf(logW, "pipelock: a2a response: %s\n", detail) if opts.AuditLogger != nil { resource := opts.auditTarget() if resource == "" { resource = "mcp://response" } opts.AuditLogger.LogAnomaly( mustMCPAuditContext(opts.AuditLogger, "MCP", resource), "a2a_card_drift", detail, 0, ) } } verdict = ScanResponseA2A(line, sc, a2aOpts) } if baselineReceiptErr != nil { denialAudit = mcpOperationalBlockAudit(scanner.AuditReceiptEmission, "mcp_response", mcpReceiptEmissionReason) resp := blockResponseReason(frame.ID, "receipt emission failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, fmt.Errorf("writing card receipt-failure block: %w", err) } emitTrackedOutcome("error", "receipt_emission_failed", resp) continue } // The transport context owns cancellation even for legacy scanners that // do not accept it. Never forward a result after its request was canceled. if err := opts.warnContext().Err(); err != nil { verdict = jsonrpc.ScanVerdict{ID: extractRPCID(line), Action: config.ActionBlock, Error: "response scan failed: " + err.Error()} } if verdict.Error != "" && verdict.Action == config.ActionBlock { if err := blockScanError(verdict.Error); err != nil { return foundInjection, err } continue } if verdict.Clean { // Clean message: decay threat score. Skip decay when tool-poisoning // was detected for this message - a near-miss signal and a clean // decay on the same message would incorrectly counteract each other. if !opts.toolContractDiscovery && !toolPoisonDetected && !toolAcknowledged { recoveryAssessment := verdict.Assessment if isToolsList { recoveryAssessment = toolsListRecoveryAssessment(recoveryAssessment, toolResult) } recordCleanSession(rec, adaptiveCfg, true, adaptiveRecoveryContextWithWarnContext(adaptiveRecoveryContext{ assessment: recoveryAssessment, sessionKey: opts.adaptiveSessionKey(), reason: adaptiveRecoveryClean, requestID: canonicalID(verdict.ID), logger: opts.AuditLogger, metrics: m, }, opts.warnContext())) } if err := reserveToolInventory(); err != nil { resolveToolInventory(config.ActionBlock) foundInjection = true if writeErr := blockToolInventoryCapacity(writer, logW, opts, lineNum, toolResult.RPCID, emitTrackedOutcome); writeErr != nil { return foundInjection, writeErr } continue } if err := writer.WriteMessage(line); err != nil { releaseToolInventory() return foundInjection, fmt.Errorf("writing line: %w", err) } commitToolInventory() emitTrackedOutcome(mcpResponseStatus(line), "complete", line) observeMCPResponseFindings(taintOpts, toolTaintFindingKinds(toolResult, toolPoisonDetected, toolAcknowledged)) continue } // Parse error: always fail-closed regardless of action setting. // Unparseable responses could hide injection in malformed content. if verdict.Error != "" { detected, resp, err := writeUnparseableResponse(unparseableResponseOptions{frame: frame, detail: verdict.Error, lineNum: lineNum, sc: sc, writer: writer, logW: logW, opts: opts}) foundInjection = foundInjection || detected if err != nil { return foundInjection, err } emitTrackedOutcome("error", "parse_error", resp) continue } // Prompt injection and inbound DLP share response-action enforcement. // Inbound DLP deliberately skips agent-owned env/file secret values; // only generic/enforceable credential findings reach this branch. foundInjection = true action := verdict.Action if action == "" { action = sc.ResponseAction() } originalAction := action names := matchNames(verdict.Matches) for _, match := range verdict.DLPMatches { names = append(names, match.PatternName) } patterns := strings.Join(names, ", ") trustClass := responseScanTrustClass(respScanOpts) serverName := opts.ServerName if serverName == "" { serverName = "unknown" } // Escalation upgrade: may promote warn/ask to block for elevated sessions. numberOnlyDecision := len(verdict.Matches) == 0 && scanner.OnlyInformational(verdict.DLPMatches) if rec != nil && !numberOnlyDecision { action = decide.UpgradeAction(action, rec.EscalationLevel(), adaptiveCfg) } escalationDriven := action != originalAction _, _ = fmt.Fprintf(logW, "pipelock: line %d: %s (%s), server=%s trust=%s action=%s\n", lineNum, responseFindingLabel(verdict), patterns, serverName, trustClass, action) effectiveAction := action var outbound []byte var writeContext string switch action { case config.ActionBlock: writeContext = "writing block response" // Escalation-driven blocks use -32001 (session deny code) to // distinguish them from direct injection blocks (-32000). if escalationDriven { outbound = blockSessionDenyResponse(verdict.ID, mcpAdaptiveBlockMessage(rec, adaptiveCfg, "mcp_response_scan", logW)) } else { outbound = blockResponseReason(verdict.ID, responseFindingBlockReason(verdict, serverName, firstNonEmptyPattern(names), trustClass)) } case config.ActionAsk: if approver == nil { _, _ = fmt.Fprintf(logW, "pipelock: line %d: no HITL approver configured, blocking\n", lineNum) effectiveAction = config.ActionBlock outbound = blockResponseForFinding(verdict) writeContext = "writing block response" } else { preview := "" if len(verdict.Matches) > 0 { preview = verdict.Matches[0].MatchText } d := approver.Ask(&hitl.Request{ URL: "mcp-response", Reason: fmt.Sprintf("%s: %s", responseFindingLabel(verdict), strings.Join(names, ", ")), Patterns: names, Preview: preview, }) switch d { case hitl.DecisionAllow: _, _ = fmt.Fprintf(logW, "pipelock: line %d: operator allowed\n", lineNum) effectiveAction = config.ActionAllow outbound = line writeContext = "writing line" observeMCPResponseFindings(taintOpts, session.MergeFindingKinds(ResponseTaintFindingKinds(verdict), toolTaintFindingKinds(toolResult, toolPoisonDetected, toolAcknowledged))) case hitl.DecisionStrip: _, _ = fmt.Fprintf(logW, "pipelock: line %d: operator chose strip\n", lineNum) if len(verdict.DLPMatches) > 0 && !scanner.OnlyInformational(verdict.DLPMatches) { // The injection stripper has no lossless DLP rewrite for arbitrary // JSON-RPC result shapes. Never forward an unredacted credential. effectiveAction = config.ActionBlock outbound = blockResponseReason(verdict.ID, "inbound DLP finding cannot be safely stripped") writeContext = "writing block response" } else { actualAction, msg := stripOrBlockMessageWithOptions(line, sc, logW, verdict.ID, opts.warnContext(), respScanOpts) effectiveAction = actualAction outbound = msg writeContext = "writing strip/block response" if actualAction == config.ActionStrip { observeMCPResponseFindings(taintOpts, session.MergeFindingKinds(ResponseTaintFindingKinds(verdict), toolTaintFindingKinds(toolResult, toolPoisonDetected, toolAcknowledged))) } } default: // DecisionBlock _, _ = fmt.Fprintf(logW, "pipelock: line %d: operator blocked\n", lineNum) effectiveAction = config.ActionBlock outbound = blockResponseForFinding(verdict) writeContext = "writing block response" } } case config.ActionStrip: if len(verdict.DLPMatches) > 0 && !scanner.OnlyInformational(verdict.DLPMatches) { // The injection stripper has no lossless DLP rewrite for arbitrary // JSON-RPC result shapes. Never forward an unredacted credential. effectiveAction = config.ActionBlock outbound = blockResponseReason(verdict.ID, "inbound DLP finding cannot be safely stripped") writeContext = "writing block response" } else { actualAction, msg := stripOrBlockMessageWithOptions(line, sc, logW, verdict.ID, opts.warnContext(), respScanOpts) effectiveAction = actualAction outbound = msg writeContext = "writing strip/block response" if actualAction == config.ActionStrip { observeMCPResponseFindings(taintOpts, session.MergeFindingKinds(ResponseTaintFindingKinds(verdict), toolTaintFindingKinds(toolResult, toolPoisonDetected, toolAcknowledged))) } } default: // warn outbound = line writeContext = "writing line" observeMCPResponseFindings(taintOpts, session.MergeFindingKinds(ResponseTaintFindingKinds(verdict), toolTaintFindingKinds(toolResult, toolPoisonDetected, toolAcknowledged))) } requestID := canonicalID(verdict.ID) target := "server_response" if requestID != "" { target = "response:" + requestID } pattern := "" if len(names) > 0 { pattern = names[0] } originalActionID := receipt.NewActionID() originalReceiptOpts := opts.withReceiptPolicyHash(receipt.EmitOpts{ ActionID: originalActionID, Verdict: effectiveAction, Transport: opts.Transport, Target: target, RequestID: requestID, Layer: "mcp_response_scan", Pattern: pattern, Severity: config.SeverityHigh, }) originalReceiptOpts = withMCPResponseShard(trackedOutcome.Receipt, originalReceiptOpts) if !originalReceiptOpts.ShardSelected && opts.ReceiptGroup != nil && opts.ReceiptGroup.Shards != nil { originalReceiptOpts = opts.ReceiptGroup.Shards.Admit(originalReceiptOpts) } _, emitErr := opts.emitReceiptDecision(MCPDecision{ Receipt: originalReceiptOpts, RequireReceipt: opts.requireReceipts() && effectiveAction != config.ActionBlock, }) receiptFailureBlock := false originalReceiptPersisted := emitErr != nil && errors.Is(emitErr, errMCPV2ReceiptEmit) if emitErr != nil { logReceiptEmitFailure(logW, emitErr, opts.requireReceipts(), effectiveAction) if opts.requireReceipts() { if effectiveAction != config.ActionBlock { outbound = blockResponseReason(verdict.ID, "receipt emission failed") effectiveAction = config.ActionBlock receiptFailureBlock = true writeContext = "writing block response" } replacementOpts := opts.withReceiptPolicyHash(receipt.EmitOpts{ ActionID: receipt.NewActionID(), Verdict: config.ActionBlock, Transport: opts.Transport, Target: target, RequestID: requestID, Layer: "receipt_emission_failed", Pattern: "mcp_response_scan receipt emission failed", Severity: config.SeverityHigh, }) replacementOpts.ShardIndex = originalReceiptOpts.ShardIndex replacementOpts.ShardSelected = originalReceiptOpts.ShardSelected if originalReceiptPersisted { replacementOpts.ParentActionID = originalActionID } if _, blockEmitErr := opts.emitReceiptDecision(MCPDecision{ Receipt: replacementOpts, RequireReceipt: true, }); blockEmitErr != nil { logReceiptEmitFailure(logW, blockEmitErr, true, config.ActionBlock) } } } if effectiveAction != config.ActionWarn && effectiveAction != config.ActionAllow { resolveToolInventory(config.ActionBlock) } if effectiveAction == config.ActionWarn || effectiveAction == config.ActionAllow { if err := reserveToolInventory(); err != nil { resolveToolInventory(config.ActionBlock) if writeErr := blockToolInventoryCapacity(writer, logW, opts, lineNum, toolResult.RPCID, emitTrackedOutcome); writeErr != nil { return foundInjection, writeErr } continue } } if effectiveAction == config.ActionBlock || opts.AuditLogger != nil { ctx := mustMCPAuditContext(opts.AuditLogger, "MCP", "server_response") switch effectiveAction { case config.ActionBlock: if receiptFailureBlock { denialAudit = mcpOperationalBlockAudit(scanner.AuditReceiptEmission, "mcp_response", mcpReceiptEmissionReason) } else { denialAudit = mcpResponseContentDenialAudit(pattern) } case config.ActionStrip, config.ActionWarn: opts.AuditLogger.LogResponseScan(ctx, effectiveAction, len(names), names, nil) } } if err := writeMCPResponseDisposition(opts, denialAudit, writer, outbound, effectiveAction == config.ActionBlock); err != nil { releaseToolInventory() return foundInjection, fmt.Errorf("%s: %w", writeContext, err) } _, _ = fmt.Fprintf(logW, "pipelock: line %d: response action=%s\n", lineNum, effectiveAction) if effectiveAction == config.ActionWarn || effectiveAction == config.ActionAllow { commitToolInventory() } emitTrackedOutcome(mcpResponseStatus(outbound), "mcp_response_scan", outbound) // Signal recording: informational card warnings do not affect the score. // Injection, inbound DLP, and strip findings in this response are // upstream content. They keep the verdict above and record only the // zero-point observation, on every transport that shares this scorer. if adaptiveCfg != nil && adaptiveCfg.Enabled && !numberOnlyDecision { ep := decide.EscalationParams{ Threshold: adaptiveCfg.EscalationThreshold, Logger: opts.AuditLogger, Metrics: m, ConsoleWriter: logW, Session: opts.adaptiveSessionKey(), DenialScanner: "mcp_response_scan", DenialReason: firstNonEmpty(pattern, "mcp_response_scan"), PolicyHash: opts.receiptPolicyHash(), } recordMCPAdaptiveSignal(opts, rec, upstreamContentSignal(), ep) } // Capture: record response injection verdict. obs.ObserveResponseVerdict(context.Background(), &capture.ResponseVerdictRecord{ Subsurface: "response_mcp", Transport: opts.Transport, SessionID: captureSessionID(opts.Transport), SessionIDOriginal: captureSessionIDOriginal(opts.Transport), ConfigHash: opts.captureConfigHash(), Profile: opts.captureProfile(), ActionClass: captureMCPActionClass("", "resources/read"), Request: capture.CaptureRequest{ RPCID: captureRPCID(verdict.ID), }, RawFindings: append(responseMatchesToFindings(verdict.Matches, effectiveAction), dlpMatchesToFindingsWithAction(verdict.DLPMatches, effectiveAction)...), EffectiveAction: effectiveAction, Outcome: captureOutcome(effectiveAction, false), }) } return foundInjection, nil } // writeUnparseableResponse preserves parse diagnostics without admitting any // response-derived state. The caller owns request correlation and receipts. type unparseableResponseOptions struct { frame MCPFrame detail string lineNum int sc *scanner.Scanner writer transport.MessageWriter logW io.Writer opts MCPProxyOpts } func writeUnparseableResponse(o unparseableResponseOptions) (bool, []byte, error) { frame, detail, lineNum, sc, writer, logW, opts := o.frame, o.detail, o.lineNum, o.sc, o.writer, o.logW, o.opts denialAudit := mcpResponseInspectionBlockAudit("MCP response is unparseable") _, _ = fmt.Fprintf(logW, "pipelock: line %d: %s\n", lineNum, detail) scanCtx := opts.warnContext() rawResult := sc.ScanBufferedInjection(scanCtx, scanner.BufferedInjectionScan{Surface: config.InjectionSurfaceMCPToolResult, Transport: mcpCheckerTransport(scanCtx), Content: string(frame.Raw)}) foundInjection := !rawResult.Clean if rawResult.Failed() && sc.ExternalInjectionSurface(config.InjectionSurfaceMCPToolResult) { foundInjection = false } if foundInjection { _, _ = fmt.Fprintf(logW, "pipelock: line %d: injection in non-JSON content (%s)\n", lineNum, strings.Join(matchNames(rawResult.Matches), ", ")) } _, _ = fmt.Fprintf(logW, "pipelock: line %d: blocking unparseable response\n", lineNum) // Key preflight previously preserved a recoverable request ID even when // the remaining JSON was malformed. Keep that correlation without // consuming the tracker or admitting any response-derived state. var id json.RawMessage if frame.KeyValidationErr != nil { id = frame.ID } resp := blockResponseReason(id, "upstream response is not parseable JSON-RPC") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return foundInjection, resp, fmt.Errorf("writing block response: %w", err) } return foundInjection, resp, nil } // rejectResponseKeys writes diagnostics without consuming correlation or running // any response-derived state updates. Cancellation remains a scan error; valid // but ambiguous messages remain security findings, unlike ordinary malformed JSON. func rejectResponseKeys(frame MCPFrame, lineNum int, sc *scanner.Scanner, writer transport.MessageWriter, logW io.Writer, opts MCPProxyOpts) (bool, []byte, error) { var denialAudit mcpDenialAudit if err := opts.warnContext().Err(); err != nil { denialAudit = mcpResponseInspectionBlockAudit("MCP response scan failed") _, _ = fmt.Fprintf(logW, "pipelock: line %d: response scan failed: %v\n", lineNum, err) resp := blockResponseReason(frame.ID, "upstream response scan failed") if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return false, resp, fmt.Errorf("writing scan-error block response: %w", err) } return false, resp, nil } if !json.Valid(frame.Raw) { verdict := responseKeyErrorVerdict(frame.Raw, frame.KeyValidationErr) return writeUnparseableResponse(unparseableResponseOptions{frame: frame, detail: verdict.Error, lineNum: lineNum, sc: sc, writer: writer, logW: logW, opts: opts}) } _, _ = fmt.Fprintf(logW, "pipelock: line %d: invalid or ambiguous JSON before tool processing: %v\n", lineNum, frame.KeyValidationErr) denialAudit = mcpResponseInspectionBlockAudit("MCP response has ambiguous protocol keys") id := recoverTopLevelJSONRPCID(frame.Raw) reason := "upstream response is not unambiguous JSON" if shape, _ := toolsListShape(frame.Raw); shape == toolsListUninspectable || (shape == toolsListScannable && jsonscan.RejectDuplicateKeys(frame.Raw) == nil) { reason = "tools/list cannot be safely inspected: tool_definition_uninspectable" } resp := blockResponseReason(id, reason) if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return true, resp, fmt.Errorf("writing preflight JSON block: %w", err) } return true, resp, nil } // emitRejectedResponseOutcome preserves receipt evidence using only metadata // from an admitted request. Ambiguous IDs cannot attribute an outcome, and the // rejected response never consumes the outstanding request or admits its state. // A tracker reservation bounds rejection receipts to one per pending request. func emitRejectedResponseOutcome(raw, outbound []byte, logW io.Writer, tracker *RequestTracker, opts MCPProxyOpts) { if !isResponse(raw) { return } var fields map[string]json.RawMessage if err := json.Unmarshal(raw, &fields); err != nil || fields == nil { return } if _, duplicate := jsonscan.TopLevelDuplicateKeys(raw)["id"]; duplicate || jsonscan.HasKeyAlias(fields, "id") { return } if _, request := fields["method"]; request || jsonscan.HasKeyAlias(fields, "method") { return } outcome, ok := tracker.claimRejectedOutcome(fields["id"]) if !ok { return } reason := "response_key_validation" if opts.warnContext().Err() != nil { reason = "response_scan_error" } outcome.settle(logW, opts, "error", int64(len(outbound)), reason) } func toolScanHasDrift(result tools.ToolScanResult) bool { for _, match := range result.Matches { if match.DriftDetected { return true } } return false } func emitMCPToolScanReceipt( logW io.Writer, opts MCPProxyOpts, result tools.ToolScanResult, verdict string, selected receipt.EmitOpts, ) error { serverName := strings.TrimSpace(opts.ServerName) if serverName == "" { serverName = "unknown.invalid" } requestID := canonicalID(result.RPCID) pattern := "tool_poisoning" if result.ResourceLimit != "" { pattern = result.ResourceLimit } else { for _, o := range result.Observations { if o.CredentialAck == tools.CredentialAckAcknowledged && len(o.ToolPoison) > 0 { pattern = o.ToolPoison[0] } } for _, match := range result.Matches { if len(match.ToolPoison) > 0 { pattern = match.ToolPoison[0] break } if match.DriftDetected { pattern = "tool_definition_drift" break } if len(match.Injection) > 0 { pattern = match.Injection[0].PatternName break } } } _, err := opts.emitReceiptDecision(MCPDecision{ Receipt: opts.withReceiptPolicyHash(withMCPResponseShard(selected, receipt.EmitOpts{ ActionID: receipt.NewActionID(), Verdict: verdict, Transport: opts.Transport, Target: "mcp://" + serverName + "/tools/list", RequestID: requestID, MCPMethod: "tools/list", Layer: "mcp_tool_scan", Pattern: pattern, Severity: config.SeverityHigh, })), RequireReceipt: opts.requireReceipts() && verdict != config.ActionBlock, }) if err != nil { logReceiptEmitFailure(logW, err, opts.requireReceipts(), verdict) } return err } // stripOrBlock tries to strip injection from the response. If stripping fails, // it falls back to blocking (fail-closed). Returns the actual enforced action // ("strip" or "block") plus any writer error. func stripOrBlock(line []byte, sc *scanner.Scanner, writer transport.MessageWriter, logW io.Writer, rpcID json.RawMessage) (string, error) { actualAction, msg := stripOrBlockMessage(line, sc, logW, rpcID) return actualAction, writeMCPResponseDisposition(MCPProxyOpts{}, mcpResponseContentDenialAudit(""), writer, msg, actualAction == config.ActionBlock) } func stripOrBlockMessage(line []byte, sc *scanner.Scanner, logW io.Writer, rpcID json.RawMessage) (string, []byte) { return stripOrBlockMessageWithOptions(line, sc, logW, rpcID, context.Background(), ResponseScanOptions{}) } func stripOrBlockMessageWithOptions(line []byte, sc *scanner.Scanner, logW io.Writer, rpcID json.RawMessage, ctx context.Context, opts ResponseScanOptions) (string, []byte) { stripped, sErr := stripResponseWithOptions(line, sc, ctx, opts) if sErr == nil && bytes.Equal(stripped, line) { // Callers strip only a message whose scan reported a finding. When no // supported field changed, the finding is outside what strip rewrites. sErr = fmt.Errorf("no strippable field carried the finding") } if sErr != nil { _, _ = fmt.Fprintf(logW, "pipelock: strip failed (%v), blocking instead\n", sErr) return config.ActionBlock, blockResponse(rpcID) } return config.ActionStrip, stripped } // rpcError is a JSON-RPC 2.0 error response sent when a response is blocked. type rpcError struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` Error rpcErrorDetail `json:"error"` } type rpcErrorDetail struct { Code int `json:"code"` Message string `json:"message"` Data json.RawMessage `json:"data,omitempty"` } // timeoutErrorResponse generates a JSON-RPC 2.0 error response for a request // whose upstream response timed out. Code -32000 is in the server-error range. func timeoutErrorResponse(id json.RawMessage) []byte { resp := rpcError{ JSONRPC: jsonrpc.Version, ID: id, Error: rpcErrorDetail{ Code: -32000, Message: "pipelock: upstream response timeout", }, } data, _ := json.Marshal(resp) return data } // withResponseTimeout wraps an upstream response reader with a per-read // deadline when mcp_input_scanning.response_timeout_seconds is positive. A // wrapped MCP server that accepts a request but never replies then triggers a // fail-closed timeout instead of hanging the agent. Shared by the stdio // subprocess proxy (RunProxy) and the stdio-to-HTTP bridge (RunHTTPForward) so // the knob behaves identically on both stdio-fronted transports. The deadline // is per complete response message (it resets when each message arrives), so a // steady response stream is not severed; it bounds the wait for the next // message. Returns r unchanged when the timeout is disabled. func (o MCPProxyOpts) withResponseTimeout(r transport.MessageReader) transport.MessageReader { if inputCfg := o.inputCfg(); inputCfg != nil && inputCfg.ResponseTimeoutSeconds > 0 { return transport.NewTimeoutReader(r, time.Duration(inputCfg.ResponseTimeoutSeconds)*time.Second) } return r } // blockResponse generates a JSON-RPC 2.0 error response for a blocked message. // Code -32000 is in the implementation-defined error range. // Use this only when the block is genuinely driven by prompt-injection // detection. For other classes of block (unparseable upstream JSON-RPC, // confused-deputy unsolicited response IDs) use blockResponseReason so // operators debugging MCP do not chase a scanner false positive. func blockResponse(id json.RawMessage) []byte { return blockResponseReason(id, "prompt injection detected in MCP response") } func responseFindingLabel(verdict jsonrpc.ScanVerdict) string { if len(verdict.DLPMatches) == 0 { return "prompt injection detected" } if len(verdict.Matches) == 0 { return "inbound DLP detected" } return "prompt injection and inbound DLP detected" } func responseFindingBlockReason(verdict jsonrpc.ScanVerdict, serverName, pattern, trustClass string) string { if len(verdict.DLPMatches) > 0 { return fmt.Sprintf("MCP response security finding (server=%s pattern=%s trust=%s)", serverName, pattern, trustClass) } return fmt.Sprintf("prompt injection detected in MCP response (server=%s pattern=%s trust=%s)", serverName, pattern, trustClass) } func blockResponseForFinding(verdict jsonrpc.ScanVerdict) []byte { if len(verdict.DLPMatches) > 0 { return blockResponseReason(verdict.ID, "MCP response security finding") } return blockResponse(verdict.ID) } func firstNonEmptyPattern(names []string) string { for _, name := range names { if name != "" { return name } } return "unknown" } func mcpResponseStatus(line []byte) string { var response struct { Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } if err := json.Unmarshal(line, &response); err != nil { return "response" } if len(response.Error) > 0 { return "error" } if len(response.Result) > 0 { return "result" } return "response" } // blockResponseReason is like blockResponse but lets the caller supply a // specific reason string. Keeps the -32000 implementation-defined error // code so clients that previously switched on code keep working, while // surfacing the true classification to operators. func blockResponseReason(id json.RawMessage, reason string) []byte { resp := rpcError{ JSONRPC: jsonrpc.Version, ID: id, Error: rpcErrorDetail{ Code: -32000, Message: "pipelock: " + reason, }, } data, _ := json.Marshal(resp) //nolint:errcheck // marshaling known-good struct return data } func blockToolInventoryCapacity( writer transport.MessageWriter, logW io.Writer, opts MCPProxyOpts, lineNum int, rpcID json.RawMessage, emitTrackedOutcome func(string, string, []byte), ) error { const reason = "tool_inventory_capacity" blockReason := "tools/list cannot be safely inspected: " + reason _, _ = fmt.Fprintf(logW, "pipelock: line %d: %s\n", lineNum, blockReason) denialAudit := mcpToolCapacityDenialAudit() if opts.Metrics != nil { opts.Metrics.RecordBlocked("mcp", reason, 0, "") } resp := blockResponseReason(rpcID, blockReason) if err := writeMCPDenial(opts, denialAudit, writer, resp); err != nil { return fmt.Errorf("writing inventory-capacity block: %w", err) } emitTrackedOutcome("error", reason, resp) return nil } // blockMediaPolicyResponse generates a JSON-RPC 2.0 error for media policy // violations. Uses error code -32002 (implementation-defined) with the specific // block reason so operators see a distinct media-policy denial, not the generic // "prompt injection detected" message. func blockMediaPolicyResponse(id json.RawMessage, reason string) []byte { resp := rpcError{ JSONRPC: jsonrpc.Version, ID: id, Error: rpcErrorDetail{ Code: -32002, Message: "pipelock: media policy blocked MCP response: " + reason, }, } data, _ := json.Marshal(resp) //nolint:errcheck // marshaling known-good struct return data } // blockSessionDenyResponse generates a JSON-RPC 2.0 error for block_all session // denial. Uses error code -32001 (implementation-defined) with a session-deny // message. Distinct from blockResponse to distinguish session-level blocks // from per-message injection blocks in logs and client error handling. func blockSessionDenyResponse(id json.RawMessage, detail string) []byte { resp := rpcError{ JSONRPC: jsonrpc.Version, ID: id, Error: rpcErrorDetail{ Code: -32001, Message: detail, }, } data, _ := json.Marshal(resp) //nolint:errcheck // marshaling known-good struct return data } // maxStripDepth limits recursion between stripResponseDepth and stripBatchDepth // to prevent stack overflow from maliciously nested JSON arrays. const maxStripDepth = 4 type stripResponseScanner func(string) scanner.ResponseScanResult // stripResponse rewrites supported fields without discarding the envelope and // returns content only after a whole-message rescan finds no enforcing finding. func stripResponse(line []byte, sc *scanner.Scanner) ([]byte, error) { return stripResponseWithOptions(line, sc, context.Background(), ResponseScanOptions{}) } func stripResponseWithOptions(line []byte, sc *scanner.Scanner, ctx context.Context, opts ResponseScanOptions) ([]byte, error) { scan := stripResponseScanner(func(text string) scanner.ResponseScanResult { return sc.ScanResponseWithSuppress(scanner.WithInjectionSurface(ctx, config.InjectionSurfaceMCPToolResult), text, opts.Target, opts.Suppress) }) out, err := stripResponseDepth(line, scan, 0) if err != nil { return nil, err } // Rescan the outgoing message with the response scan that decided it, so // every view that produced a finding (typed fields, decoded media text, // envelope strings and keys) must have no enforcing finding. The raw view also covers // findings that span fields. Observation callbacks already fired for the // original message and must not fire again for the candidate. checkOpts := opts checkOpts.OnSuppressedResponse = nil checkOpts.OnObservedCoreResponse = nil checkOpts.OnDroppedDLP = nil if verdict := ScanResponseOpts(out, sc, checkOpts); verdict.Error != "" || (!verdict.Clean && (len(verdict.Matches) > 0 || !scanner.OnlyInformational(verdict.DLPMatches))) { return nil, fmt.Errorf("stripped response is not clean") } if checked := scan(string(out)); !checked.Clean || checked.Failed() { return nil, fmt.Errorf("stripped response is not clean") } return out, nil } // stripResponseString rewrites only supported string fields. Object-valued // fields remain intact and are inspected by the whole-message rescan. func stripResponseString(object map[string]json.RawMessage, key string, scan stripResponseScanner) (bool, error) { var text string if raw, ok := object[key]; !ok || json.Unmarshal(raw, &text) != nil { return false, nil } result := scan(text) if result.Clean { return false, nil } if result.Failed() || result.TransformedContent == "" { return false, fmt.Errorf("injection detected but not redactable in response string") } rewritten, err := json.Marshal(result.TransformedContent) if err != nil { return false, fmt.Errorf("encoding stripped string: %w", err) } object[key] = rewritten return true, nil } func stripResponseDepth(line []byte, scan stripResponseScanner, depth int) ([]byte, error) { // Handle batch responses (JSON array). Trim so a leading-whitespace // array is classified the same way ParseMCPFrame sets IsBatch. if trimmed := bytes.TrimSpace(line); len(trimmed) > 0 && trimmed[0] == '[' { if depth >= maxStripDepth { return nil, fmt.Errorf("batch nesting too deep (max %d)", maxStripDepth) } return stripBatchDepth(trimmed, scan, depth+1) } if err := jsonscan.RejectDuplicateKeys(line); err != nil { return nil, fmt.Errorf("parsing response for strip: %w", err) } var rpc map[string]json.RawMessage if err := json.Unmarshal(line, &rpc); err != nil { return nil, fmt.Errorf("parsing response for strip: %w", err) } if rpc == nil { return nil, fmt.Errorf("strip requires a response object") } changed := false if raw, ok := rpc["result"]; ok && len(raw) > 0 && string(raw) != "null" { var result map[string]json.RawMessage if err := json.Unmarshal(raw, &result); err != nil || result == nil { return nil, fmt.Errorf("strip requires a result object") } if rawContent, ok := result["content"]; ok { var content []map[string]json.RawMessage if err := json.Unmarshal(rawContent, &content); err != nil { return nil, fmt.Errorf("parsing content for strip: %w", err) } contentChanged := false for _, block := range content { c, err := stripResponseString(block, "text", scan) if err != nil { return nil, err } contentChanged = contentChanged || c } if contentChanged { rewritten, err := json.Marshal(content) if err != nil { return nil, fmt.Errorf("encoding stripped content: %w", err) } result["content"] = rewritten rewritten, err = json.Marshal(result) if err != nil { return nil, fmt.Errorf("encoding stripped result: %w", err) } rpc["result"] = rewritten changed = true } } } if raw, ok := rpc["error"]; ok && len(raw) > 0 && string(raw) != "null" { var errorObject map[string]json.RawMessage if err := json.Unmarshal(raw, &errorObject); err != nil || errorObject == nil { return nil, fmt.Errorf("strip requires an error object") } errorChanged := false for _, key := range []string{"message", "data"} { c, err := stripResponseString(errorObject, key, scan) if err != nil { return nil, err } errorChanged = errorChanged || c } if errorChanged { rewritten, err := json.Marshal(errorObject) if err != nil { return nil, fmt.Errorf("encoding stripped error: %w", err) } rpc["error"] = rewritten changed = true } } if !changed { return line, nil } return json.Marshal(rpc) } // stripBatchDepth handles stripping injection from batch (array) JSON-RPC responses. func stripBatchDepth(line []byte, scan stripResponseScanner, depth int) ([]byte, error) { var batch []json.RawMessage if err := json.Unmarshal(line, &batch); err != nil { return nil, fmt.Errorf("parsing batch for strip: %w", err) } result := make([]json.RawMessage, len(batch)) for i, elem := range batch { stripped, err := stripResponseDepth(elem, scan, depth) if err != nil { // A blocked element is not a successful strip of the batch. return nil, fmt.Errorf("stripping batch element %d: %w", i, err) } result[i] = json.RawMessage(stripped) } return json.Marshal(result) } // matchNames extracts pattern names from a list of response matches. func matchNames(matches []scanner.ResponseMatch) []string { names := make([]string, 0, len(matches)) for _, m := range matches { names = append(names, m.PatternName) } return names } // AdaptiveConfigFunc returns the current adaptive enforcement config. // Used by long-lived listeners (RunHTTPListenerProxy) so they read the // live config after each hot-reload instead of a stale startup snapshot. // Returns nil when adaptive enforcement is disabled. type AdaptiveConfigFunc func() *config.AdaptiveEnforcement // InputScanConfig holds the settings for MCP input scanning. // Passed to RunProxy to control request scanning behavior. type InputScanConfig struct { Enabled bool Action string // warn, block OnParseError string // block, forward // ResponseTimeoutSeconds is an optional per-read timeout (in seconds) for // the upstream MCP server's response stream. When positive, the proxy // emits a JSON-RPC error if no response data arrives within this window. // Default 0 = disabled (no timeout). ResponseTimeoutSeconds int } // RunProxy launches an MCP server subprocess and proxies stdio through // the scanner. Client input is scanned for DLP/injection (if enabled) before // forwarding to the server's stdin. Server stdout is scanned and forwarded // to the client. Server stderr is forwarded to logW. // When toolCfg is non-nil with a non-empty Action, tool description scanning // and drift detection are enabled for this proxy session. // Both clientOut and logW are wrapped in mutex adapters to prevent concurrent // write races between the input scanning goroutine, blocked request drainer, // child process stderr, and the main goroutine's response scanning. // When store is non-nil, a per-invocation session recorder is created and used // for adaptive enforcement signal recording across both input and response scanning. // adaptiveCfg provides escalation thresholds and upgrade rules; it is only consulted // when store is non-nil and rec is created. // RunProxy starts an MCP server subprocess and proxies stdin/stdout with // bidirectional scanning. onChildReady is called after the child process // starts and its PID is registered with the lineage tracker; callers use // this to start the file sentry event loop after attribution is ready. func RunProxy(ctx context.Context, clientIn io.Reader, clientOut io.Writer, logW io.Writer, command []string, opts MCPProxyOpts, extraEnv ...string) error { // Capture before integrity preparation, pipe setup, and child startup to // narrow the time later startup work can hide a parent death. A launcher can // still die before this first syscall; PPID watching cannot close that race. startupParentWatch := parentWatchOpts{startPPID: os.Getppid()} var cmd *exec.Cmd var prepared *integrity.PreparedCommand if icfg := opts.IntegrityCfg; icfg != nil && icfg.Enabled { var err error prepared, err = prepareBinaryIntegrity(command, icfg, logW) if err != nil { if icfg.Action != config.ActionWarn || icfg.RequireSignature { return err } _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: %v; using unpinned platform launch\n", err) cmd = exec.CommandContext(ctx, command[0], command[1:]...) } else { if opts.afterIntegrityPreparedForTest != nil { opts.afterIntegrityPreparedForTest() } cmd, err = descriptorCommand(ctx, command, prepared) if err != nil { _ = prepared.Close() prepared = nil if icfg.Action != config.ActionWarn { return fmt.Errorf("binary integrity: preparing descriptor launch: %w", err) } // Warn is explicitly non-enforcing. Unsupported descriptor exec is // noisy here; block/default action denies above and never downgrades. _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: descriptor launch unavailable: %v; using unpinned platform launch\n", err) cmd = exec.CommandContext(ctx, command[0], command[1:]...) } } } if cmd == nil { cmd = exec.CommandContext(ctx, command[0], command[1:]...) } if prepared != nil { defer func() { _ = prepared.Close() }() } // Set transport for capture records if not already set by caller. if opts.Transport == "" { opts.Transport = "mcp_stdio" } if opts.ContractServer == "" { opts.ContractServer = mcpContractServerFromCommand(command) } if opts.AuthorityDestination == "" { opts.AuthorityDestination = opts.ContractServer } // Per-invocation adaptive enforcement recorder. Nil when Store is nil // (adaptive enforcement disabled), so all downstream callers are nil-safe. var rec session.Recorder if opts.Store != nil { invocationKey := session.NextInvocationKey("mcp-stdio") rec = opts.Store.GetOrCreate(invocationKey) if rec == nil { dropMCPDenial(opts, mcpStartupDenialAudit(mcpListenerCapacityDenialAudit()), "startup") return session.ErrCapacity } defer opts.Store.Delete(invocationKey) opts.taskSubject = invocationKey session.BindTaskSubject(rec, opts.taskSubject) } defer recordMCPBaselineSample(opts, rec) // Wrap shared writers in mutex adapters. Multiple goroutines write to // clientOut (blocked request drainer + response scanner) and logW // (input scanner + response scanner + child stderr). safeClientOut := &syncWriter{w: clientOut} safeLogW := &syncWriter{w: logW} // Restrict child process environment to safe variables only. // Prevents leaking secrets from the proxy's environment to the MCP server. // Extra env vars from --env flags are appended (user explicitly opted in). cmd.Env = mergeChildEnv(safeEnv(), extraEnv) serverIn, err := cmd.StdinPipe() if err != nil { return fmt.Errorf("creating stdin pipe: %w", err) } serverOut, err := cmd.StdoutPipe() if err != nil { return fmt.Errorf("creating stdout pipe: %w", err) } // Own the stderr pipe rather than assigning cmd.Stderr directly. The // os/exec convenience path waits for its private copier inside cmd.Wait; // a descendant that escapes the child group while holding stderr open // would therefore make the adopted-descendant sweep unreachable. Owning // the read end lets session teardown release it before Wait. serverErr, serverErrW, err := os.Pipe() if err != nil { return fmt.Errorf("creating stderr pipe: %w", err) } cmd.Stderr = serverErrW // Put the child in its own process group so pipelock can tear down // any grandchildren the MCP server spawned when the child exits. // Without this, a malicious (or misbehaving) server that detaches // aggressive descendants leaves them reparented to PID 1 - the // pre-tag gate round-4 finding. setupChildProcessGroup is a no-op // on Windows builds where process groups do not apply. setupChildProcessGroup(cmd) // Ask the kernel to SIGTERM the direct child if pipelock itself // dies (e.g. operator runs `timeout 5s pipelock mcp proxy -- ...` // or systemd kills the unit). Without this, the direct child // survives pipelock's death long enough to spawn or re-adopt // grandchildren that bypass the normal post-Wait teardown. Linux // only - macOS/other Unix are no-op. setPdeathsig(cmd) // Enable PR_SET_CHILD_SUBREAPER (Linux) so orphaned grandchildren // reparent to pipelock instead of PID 1 when the direct child exits. // Without this, a grandchild that calls setsid() or double-forks // escapes our pgid-based SIGKILL because its pgid differs from the // direct child's. With subreaper active, any such descendant becomes // our child, and killAdoptedDescendants after Wait can clean it up. // round-7 of the pre-tag gate finding reproduced exactly this case (grandchild // PPID=1, pgid != direct-child pgid). // // cleanupCapability arms the subreaper once for the life of the process // (idempotent and process-wide) and caches the verdict, so a startup // report and this per-child arming probe the kernel once between them. // Non-fatal on error - the later pgid-kill backstop still handles the // common case. The warning is suppressed when the caller already reported // the capability at startup so the operator sees it once, not per child. if c := cleanupCapability(); c.State != CleanupAvailable && !opts.StartupCleanupReported { writeCleanupReport(logW, c, false) } // Enable subreaper before starting the child so we adopt orphaned // grandchildren. This lets the lineage tracker attribute file writes // to the agent's process tree. // // PR_SET_CHILD_SUBREAPER needs no capability (not CAP_SYS_RESOURCE); a // failure here means a seccomp filter blocked prctl or the kernel is too // old to know the option. Either way PID attribution is unreliable, so // warn and disable the lineage tracker rather than silently producing // wrong results. File sentry DLP scanning still runs - only process-tree // attribution is affected. lineage := opts.Lineage if lineage != nil { if err := lineage.EnableSubreaper(); err != nil { _, _ = fmt.Fprintf(logW, "pipelock: warning: subreaper setup failed, disabling PID attribution: %v\n", err) lineage = nil } } // Start and claim as one step, so no sweep can see this child before its // owner has registered it. The reaper started further down registers the // same claim; the registry counts, so both releases are safe. Without this // the window between fork and that reaper start is wide, and a concurrent // session's sweep can reap this child and take the exit status Wait needs. unlockStart := lockChildStart() if err := cmd.Start(); err != nil { unlockStart() _ = serverErr.Close() _ = serverErrW.Close() return fmt.Errorf("starting MCP server %q: %w", command[0], err) } releaseChild := protectDirectChild(cmd.Process.Pid) unlockStart() defer releaseChild() _ = serverErrW.Close() stderrDone := make(chan struct{}) go func() { _, _ = io.Copy(safeLogW, serverErr) close(stderrDone) }() if prepared != nil { startedPreparation := prepared prepared = nil if err := startedPreparation.Close(); err != nil { _, _ = fmt.Fprintf(logW, "pipelock: warning: closing parent integrity descriptors: %v\n", err) } } // Capture the child's process group ID immediately after Start, while // the direct child is known live. Setpgid=true above guarantees pgid==pid // at spawn time on Unix. This is only safe to signal before cmd.Wait // begins: once Wait can reap the group leader, the numeric group ID can be // recycled and must never be signalled again. On Windows the helper returns // 0 and the signal helpers below all no-op, matching the no-op // setupChildProcessGroup call above. childPgid := captureChildPgid(cmd.Process.Pid) processExit := &processExitHandoff{} killDirectChild := func() bool { if cmd.Process == nil { return false } return cmd.Process.Kill() == nil } // Drain adopted-descendant zombies live, while the direct child is // still running. Without this, long-running MCP wraps (e.g. a code-assistant // or browser-automation MCP server - multi-hour direct children) accumulate // zombies under pipelock because the post-Wait killAdoptedDescendants // sweep below only fires when the direct child exits. PR_SET_CHILD_SUBREAPER // turned on above causes orphan adoption from minute one; this goroutine // reaps the resulting zombies as they appear. Reaper Wait4's only // PID-specific (never -1) and skips the direct child PID, so // exec.Cmd.Wait()'s ownership of the direct child's exit is preserved. // On non-Linux builds startAdoptedReaper is a no-op. reaperDone := make(chan struct{}) defer close(reaperDone) startAdoptedReaper(cmd.Process.Pid, reaperDone) // Track child PID for file write attribution. if lineage != nil { lineage.TrackPID(cmd.Process.Pid) } // Proactive pgid teardown on context cancellation. exec.CommandContext // delivers SIGKILL to the direct child's PID when ctx cancels, but // that does not reach siblings in the same pgid or descendants that // escaped into a fresh pgid via setsid. Sending SIGTERM to the // negated pgid here gives cooperative descendants a chance to exit // cleanly inside any `timeout`-style grace window, ahead of the // post-Wait SIGKILL backstop that runs once cmd.Wait returns. // pgidDone gates the goroutine's lifetime so it exits as soon as // the post-Wait cleanup path claims ownership of teardown. pgidDone := make(chan struct{}) go func() { select { case <-ctx.Done(): processExit.terminate(func() { signalProcessGroupTerm(childPgid) }, killDirectChild) case <-pgidDone: } }() defer close(pgidDone) // Session-bound exit. A stdio proxy is owned by the interactive agent // session that spawned it: when that session dies, this process and the // MCP server it fronts have no reason to exist, but nothing in the // lifetime handling above notices. Pdeathsig and the subreaper bit are // both armed on the CHILD and answer "what happens when pipelock dies"; // neither answers "what happens when pipelock's own parent dies". The // client stdin reader hitting EOF closes the wrapped server's stdin, and // for a server that ignores stdin close that is not a shutdown at all - // cmd.Wait pins forever and the whole tree leaks for days while still // holding config, compiled pattern sets and credential-bearing children. // // The teardown ordering below is a drain, not a kill: stop intake, let // in-flight responses finish, and only escalate to the process-tree // teardown for a server that will not leave on its own. // // This is defense in depth for an unclean harness exit. A harness-owned // lifetime primitive is needed to cover the remaining launch window and // descendants that create new process groups. waitDone := make(chan struct{}) sessionExit := &sessionExitState{} sessionCtx, sessionStop := context.WithCancel(ctx) defer sessionStop() // The parent PID is captured at function entry to narrow the startup // window, but a launcher that dies before that first syscall remains an // inherent PPID-watch limitation. A harness-owned owner pipe or cgroup is // needed to close that earlier race. sessionOpts := startupParentWatch sessionGrace := defaultParentExitGrace if h := opts.sessionExitForTest; h != nil { sessionOpts = h.watch if h.grace > 0 { sessionGrace = h.grace } } if sessionOpts.startPPID > orphanedPPID { go runSessionBoundExit(sessionCtx, sessionOpts, sessionExitActions{ onSessionExit: sessionExit.begin, stopIntake: func() { if c, ok := clientIn.(io.Closer); ok { _ = c.Close() } }, closeServerStdin: func() { _ = serverIn.Close() }, // Tear down the whole process group, not just the direct child. // // Killing only cmd.Process is not enough and deadlocks: any // sibling the server spawned inherited the stdout pipe, so the // write end stays open after the direct child dies and the // response reader blocks forever on a pipe that will never close. // That reader has to return before cmd.Wait can, and the post-Wait // teardown is what would have killed the pipe holders - so the // shutdown waits on itself and the tree leaks exactly as it did // before this watcher existed. Signaling the group first releases // the descriptor and lets Wait return, after which the normal // teardown reaps detached and adopted descendants the group kill // could not reach. terminateTree: func() bool { // Close response descriptors before either branch. A descendant // can retain stdout or stderr after the direct child exits, and // these closes release forwarding without relying on a numeric // process-group signal. _ = serverOut.Close() _ = serverErr.Close() return processExit.terminate(func() { // A descendant can escape the child group with setsid while // retaining stdout. Close the read ends first to release // ForwardScanned while process-group teardown is in flight. terminateProcessGroup(childPgid) _ = killDirectChild() }, killDirectChild) }, waitDone: waitDone, grace: sessionGrace, logW: safeLogW, }) } // Signal that the child is started and PID is tracked. The file sentry // event loop starts here so attribution is ready before classifying writes. if opts.OnChildReady != nil { opts.OnChildReady() } // Channel for blocked request IDs from input scanning goroutine. // Blocked drainer goroutine writes error responses to safeClientOut, // which is mutex-protected against concurrent writes from ForwardScanned. blockedCh := make(chan BlockedRequest, 16) // Set up tool scanning with a fresh baseline for this proxy session. // The baseline is shared between ForwardScanned (response-side, captures // tools/list) and ForwardScannedInput (request-side, validates tools/call). // Must be created before goroutines that reference it. toolCfg := opts.toolCfg() var fwdToolCfg *tools.ToolScanConfig if toolCfg != nil && toolCfg.Action != "" { fwdToolCfg = &tools.ToolScanConfig{ Baseline: tools.NewToolBaseline(), Action: toolCfg.Action, DetectDrift: toolCfg.DetectDrift, NewToolAdmission: toolCfg.NewToolAdmission, BindingUnknownAction: toolCfg.BindingUnknownAction, BindingNoBaselineAction: toolCfg.BindingNoBaselineAction, ExtraPoison: toolCfg.ExtraPoison, CredentialAcks: toolCfg.CredentialAcks, Now: toolCfg.Now, } } // Build session binding config for input scanning. Shares the same // tools.ToolBaseline so tools/list captures (response-side) are visible to // tools/call validation (request-side). var bindingCfg *SessionBindingConfig if fwdToolCfg != nil && fwdToolCfg.BindingUnknownAction != "" { bindingCfg = &SessionBindingConfig{ Baseline: fwdToolCfg.Baseline, UnknownToolAction: fwdToolCfg.BindingUnknownAction, NoBaselineAction: fwdToolCfg.BindingNoBaselineAction, } } // Request tracker for confused deputy protection. Always created so // response ID validation is active regardless of which input scanning // features are enabled. tracker := NewRequestTracker() // Build per-invocation opts with session-specific recorder and tool baseline. inputOpts := opts inputOpts.Rec = rec inputOpts.WarnContext = ctx inputOpts.sessionExit = sessionExit // Forward client input to server stdin (with optional input scanning). inputDone := make(chan struct{}) go func() { defer close(inputDone) defer serverIn.Close() //nolint:errcheck // best-effort close on stdin forward inputCfg := opts.inputCfg() if inputCfg != nil && inputCfg.Enabled { clientReader := transport.NewStdioReader(clientIn) serverWriter := transport.NewStdioWriter(serverIn) ForwardScannedInput(clientReader, serverWriter, safeLogW, inputCfg.Action, inputCfg.OnParseError, blockedCh, bindingCfg, tracker, inputOpts) } else if opts.policyCfg() != nil || bindingCfg != nil || opts.chainMatcher() != nil { // Policy checking, session binding, or chain detection enabled but content scanning disabled. // Route through ForwardScannedInput with pass-through content scanning. // Use onParseError="block" (fail-closed) so malformed JSON can't bypass policy. clientReader := transport.NewStdioReader(clientIn) serverWriter := transport.NewStdioWriter(serverIn) disabledInputOpts := inputOpts disabledInputOpts.stdioInputScanDisabled = true ForwardScannedInput(clientReader, serverWriter, safeLogW, config.ActionWarn, config.ActionBlock, blockedCh, bindingCfg, tracker, disabledInputOpts) } else { // No content scanning, but still route through ForwardScannedInput // so request IDs are tracked for confused deputy protection. // ActionWarn = pass-through, ActionBlock on parse error = fail-closed. clientReader := transport.NewStdioReader(clientIn) serverWriter := transport.NewStdioWriter(serverIn) noScanOpts := inputOpts noScanOpts.PolicyCfg = nil noScanOpts.PolicyCfgFn = nil noScanOpts.ChainMatcher = nil noScanOpts.ChainMatcherFn = nil noScanOpts.stdioInputScanDisabled = true ForwardScannedInput(clientReader, serverWriter, safeLogW, config.ActionWarn, config.ActionBlock, blockedCh, nil, tracker, noScanOpts) } }() // Drain blocked request channel and write error responses to client. // Runs in a separate goroutine so ForwardScanned can proceed concurrently. blockedDone := make(chan struct{}) go func() { defer close(blockedDone) for blocked := range blockedCh { if blocked.IsNotification { // Notifications have no ID - silently drop (no error response per JSON-RPC spec). // Log the block for audit trail - silent drops with zero logging aid attacker reconnaissance. _, _ = fmt.Fprintf(safeLogW, "pipelock: blocked notification (no response sent): %s\n", blocked.LogMessage) continue } if wErr := deliverMCPInputResult(opts, blocked, safeClientOut); wErr != nil { _, _ = fmt.Fprintf(safeLogW, "pipelock: failed to send block response: %v\n", wErr) } } }() // Scan and forward server output to client. Apply the optional per-read // response timeout (no-op when disabled) so a dead upstream that accepts a // request but never replies fails closed instead of hanging the agent. serverReader := opts.withResponseTimeout(transport.NewStdioReader(serverOut)) fwdOpts := opts fwdOpts.Rec = rec fwdOpts.WarnContext = ctx // Session teardown closes serverOut to release a descendant holding the // pipe. ForwardScanned must see that ownership marker so os.ErrClosed is a // clean shutdown instead of an upstream scanner error. fwdOpts.sessionExit = sessionExit fwdOpts.ToolCfg = fwdToolCfg // session-specific baseline fwdOpts.ToolCfgFn = nil if opts.outputForwardStartedForTest != nil { opts.outputForwardStartedForTest() } _, scanErr := ForwardScanned(serverReader, safeClientOut, safeLogW, tracker, fwdOpts) timedOut := errors.Is(scanErr, transport.ErrResponseTimeout) // On an upstream response timeout the child is still alive (it accepted a // request and never replied). Stop request intake before emitting pending // timeout responses below, then terminate the child so cmd.Wait() returns // instead of blocking forever on the hung process. The pgid teardown after // Wait() then reaps any descendants. if timedOut && cmd.Process != nil { _, _ = fmt.Fprintf(safeLogW, "pipelock: terminating MCP subprocess after upstream response timeout\n") if c, ok := clientIn.(io.Closer); ok { _ = c.Close() } _ = serverIn.Close() _ = cmd.Process.Kill() } // A numeric process-group teardown is deliberately NOT performed here. // // Moving it before Wait was tried, to keep the group identifier tied to a // live child so it could not have been recycled. It is wrong: reaching this // point is the ORDINARY exit path, and terminateProcessGroup signals the // group and then escalates to SIGKILL, so every clean shutdown would kill a // server that was still finishing. Reproduced by a sibling proxy test that // passes alone and fails once the package runs together. // // After Wait is also unavailable: the kernel may reuse the group id as soon // as the leader is reaped, so a late signal can land on an unrelated group. // // That leaves parentage-based cleanup, which needs no numeric identifier. // It is complete on Linux whenever the subreaper is active, and its absence // on other platforms is a real limitation rather than something this // signal could safely close. // cmd.Wait permanently retires raw numeric process identifiers from the // handoff. A concurrent session or context teardown can still use the Go // process handle for the direct child, but can never signal its PID or PGID. waitErr := processExit.wait(cmd.Wait) // Release the session watcher's drain wait. A server that exited on its // own after stdin close must not sit through the remaining grace window // before the teardown below claims ownership. close(waitDone) // After the direct child exits, sweep any descendants it spawned that the // Linux subreaper adopted after an escape from the original process group. // // killAdoptedDescendants sweeps /proc for processes whose PPID // is now pipelock's own PID - any grandchild that escaped the // original pgid via setsid/double-fork should have reparented // to us once PR_SET_CHILD_SUBREAPER fired above. SIGKILL is // best-effort; ESRCH/EPERM are non-fatal. // Numeric process-group cleanup is deliberately absent here: Wait may // already have recycled the group leader's identifier. On Linux, the // subreaper sweep handles descendants without that raw-ID hazard; on other // platforms descendants outside the direct child's lifetime boundary need a // harness-owned containment primitive. killAdoptedDescendants() // A detached descendant can retain stderr after the direct child exits. // Bound the drain so an escaped writer cannot hold the proxy open forever. if !drainStderr(stderrDone, serverErr, sessionGrace) { // Bounded, because reaching this line means the stderr copy is already // stuck. That copy holds the shared writer's lock while it blocks, and // closing the read end cannot interrupt a write already in progress, so // a synchronous diagnostic here would wait on the same lock and stop // teardown from ever completing - failing in exactly the situation it // exists to report. logAsync(safeLogW, "pipelock: timed out draining MCP subprocess stderr after child exit\n") } if timedOut { // Closing a closable clientIn above wakes the usual CLI/pipe readers. // If a custom Reader cannot be interrupted, do not let a request that // already failed closed wedge shutdown forever. drainCtx, drainCancel := context.WithTimeout(ctx, 5*time.Second) defer drainCancel() done := make(chan struct{}) go func() { <-inputDone <-blockedDone close(done) }() select { case <-done: case <-drainCtx.Done(): _, _ = fmt.Fprintf(safeLogW, "pipelock: timed out waiting for MCP input drain after upstream response timeout\n") } emitPendingTimeoutResponses(safeClientOut, safeLogW, tracker, fwdOpts) } else if sessionExit.inProgress() { // An arbitrary io.Reader cannot be interrupted by closing the client // side. Once session teardown has killed the server, do not let one // such reader keep the proxy alive indefinitely. select { case <-inputDone: <-blockedDone case <-time.After(sessionGrace): _, _ = fmt.Fprintf(safeLogW, "pipelock: timed out waiting for MCP input drain after session teardown\n") } // Name the actual cause. Reusing "upstream_closed" here would attribute // a session teardown to the server having closed the connection, so the // receipt would record the wrong reason for an aborted request. emitPendingIncompleteOutcomes(safeLogW, tracker, fwdOpts, "session_exit") } else { // Wait for stdin goroutine to finish (server exit closes pipe, unblocking scanner). <-inputDone // Wait for blocked channel drain to complete. <-blockedDone emitPendingIncompleteOutcomes(safeLogW, tracker, fwdOpts, "upstream_closed") } if scanErr != nil { return fmt.Errorf("scanning: %w", scanErr) } // Subprocess exit codes are expected operational events (MCP server crash, // bad config, missing binary), not pipelock bugs. Wrap in a sentinel so // callers can distinguish and avoid reporting to error tracking. var exitErr *exec.ExitError if errors.As(waitErr, &exitErr) { return fmt.Errorf("%w: %w", ErrSubprocessExit, waitErr) } return waitErr } // safeEnvKeys are environment variables safe to pass to child MCP server processes. // These cannot be overridden via --env to prevent footgun scenarios (e.g. --env PATH=/evil). var safeEnvKeys = []string{"PATH", "HOME", "USER", "LANG", "TERM", "TZ", "TMPDIR", "SHELL"} // safeEnvKeySet mirrors safeEnvKeys as a set for O(1) lookup in IsSafeEnvKey. var safeEnvKeySet = func() map[string]bool { m := make(map[string]bool, len(safeEnvKeys)) for _, k := range safeEnvKeys { m[k] = true } return m }() // dangerousEnvKeys are environment variable names that can inject code or libraries // into child processes. These are blocked even when explicitly requested via --env. // IsDangerousEnvKey also refuses every envcontrol.CodeLoadingNames entry; this // map adds the git, proxy and macOS loader variables that list does not hold. var dangerousEnvKeys = map[string]bool{ // Dynamic linker injection (Linux/macOS). "LD_PRELOAD": true, "LD_LIBRARY_PATH": true, "LD_AUDIT": true, "DYLD_INSERT_LIBRARIES": true, "DYLD_LIBRARY_PATH": true, "DYLD_FRAMEWORK_PATH": true, // The FALLBACK_ variants are consulted when the primary search fails, so // blocking only the primaries leaves a second way to place a library. "DYLD_FALLBACK_LIBRARY_PATH": true, "DYLD_FALLBACK_FRAMEWORK_PATH": true, // Runtime code injection. "NODE_OPTIONS": true, "PYTHONSTARTUP": true, "PYTHONPATH": true, "PERL5OPT": true, "RUBYOPT": true, "BASH_ENV": true, "JAVA_TOOL_OPTIONS": true, "_JAVA_OPTIONS": true, "JDK_JAVA_OPTIONS": true, // Credential helper injection - causes git to execute arbitrary programs. // GIT_ASKPASS was blocked first, but it is one of several variables that // hand git a command line to run, so the siblings belong with it. "GIT_ASKPASS": true, "GIT_SSH": true, "GIT_SSH_COMMAND": true, "GIT_EXTERNAL_DIFF": true, "GIT_PROXY_COMMAND": true, "GIT_EDITOR": true, "GIT_PAGER": true, "GIT_CONFIG_GLOBAL": true, "GIT_CONFIG_SYSTEM": true, "GIT_CONFIG_COUNT": true, "GIT_ALTERNATE_OBJECT_DIRECTORIES": true, // Proxy redirection - the MCP proxy IS the controlled network path. // Both cases listed because Go checks HTTP_PROXY/http_proxy, Node.js // checks case-insensitively, etc. Mixed-case caught by IsDangerousEnvKey. "HTTP_PROXY": true, "HTTPS_PROXY": true, "ALL_PROXY": true, "FTP_PROXY": true, "NO_PROXY": true, "http_proxy": true, "https_proxy": true, "all_proxy": true, "ftp_proxy": true, "no_proxy": true, } // IsSafeEnvKey reports whether the given key is one of the system variables // already provided by safeEnv(). These cannot be overridden via --env. func IsSafeEnvKey(key string) bool { return safeEnvKeySet[key] } // IsDangerousEnvKey reports whether the given environment variable name is // blocked from passthrough because it can inject code or redirect traffic. // Every name is matched case-insensitively: Windows environment names ignore // case, so a child started with pythonpath=... reads it as PYTHONPATH, and // different runtimes (Go, Node.js, Python, curl) honor different proxy casings. func IsDangerousEnvKey(key string) bool { upper := strings.ToUpper(key) if dangerousEnvKeys[upper] || envcontrol.IsCodeLoading(upper) { return true } // Case-insensitive catch-all for proxy vars. Covers mixed-case forms // like Http_Proxy that some runtimes (notably Node.js) honor. return strings.HasSuffix(upper, "_PROXY") } // safeEnv builds a filtered environment from the current process, keeping only // variables in safeEnvKeys. This prevents accidental secret leakage to MCP servers. func safeEnv() []string { var env []string for _, key := range safeEnvKeys { if val, ok := os.LookupEnv(key); ok { env = append(env, key+"="+val) } } return env } func mergeChildEnv(base, overrides []string) []string { return mergeChildEnvForOS(base, overrides, runtime.GOOS) } const windowsOS = "windows" func mergeChildEnvForOS(base, overrides []string, goos string) []string { values := make(map[string]string, len(base)+len(overrides)) for _, entry := range append(append([]string(nil), base...), overrides...) { key, value, ok := splitChildEnvEntry(entry, goos) identity := key if goos == windowsOS { identity = strings.ToUpper(key) } if !ok { identity = entry if goos == windowsOS { identity = strings.ToUpper(entry) } delete(values, identity) continue } values[identity] = identity + "=" + value } keys := make([]string, 0, len(values)) for key := range values { keys = append(keys, key) } sort.Strings(keys) result := make([]string, 0, len(keys)) for _, key := range keys { result = append(result, values[key]) } return result } // ChildEnvOverrideIdentity is the effective result of applying overrides to a // child environment, independent of what the child inherits: for each // variable, in mergeChildEnv's last-wins order and key rules, either // "set:KEY=VALUE" or "unset:KEY". It is what a server's transport binding // covers; inherited variables the operator did not name are not included. func ChildEnvOverrideIdentity(overrides []string) []string { return childEnvOverrideIdentityForOS(overrides, runtime.GOOS) } func childEnvOverrideIdentityForOS(overrides []string, goos string) []string { final := make(map[string]string, len(overrides)) for _, entry := range overrides { key, value, ok := splitChildEnvEntry(entry, goos) if !ok { key = entry } identity := key if goos == windowsOS { identity = strings.ToUpper(key) } if ok { final[identity] = "set:" + identity + "=" + value } else { final[identity] = "unset:" + identity } } out := make([]string, 0, len(final)) for _, v := range final { out = append(out, v) } sort.Strings(out) return out } func splitChildEnvEntry(entry, goos string) (string, string, bool) { if goos == windowsOS && strings.HasPrefix(entry, "=") { if separator := strings.Index(entry[1:], "="); separator >= 0 { separator++ return entry[:separator], entry[separator+1:], true } return entry, "", false } return strings.Cut(entry, "=") } // VerifyBinaryIntegrity checks the command binary against a hash manifest // before subprocess spawn. Fail-closed: a verification failure returns an // error (blocking spawn) UNLESS action is explicitly "warn", in which case the // failure is logged to logW and nil is returned. An empty or unrecognized // action therefore blocks, matching the fail-closed config default. Config // load already constrains action to "warn" or "block" via Validate; treating // only an explicit "warn" as relaxing is defense-in-depth for any in-process // caller that constructs the config without validation. // Returns nil when verification passes. func VerifyBinaryIntegrity(command []string, icfg *config.MCPBinaryIntegrity, logW io.Writer, workDir ...string) error { agentWorkDir := "" if len(workDir) > 0 { agentWorkDir = workDir[0] } intCfg := &integrity.Config{ Enabled: true, ManifestPath: icfg.ManifestPath, Action: icfg.Action, } // Load the manifest. When require_signature is set, the manifest // bytes are read once, the detached signature is verified against // those exact bytes, and the in-memory bytes are parsed. Re-reading // the file after verification would open a TOCTOU window where an // attacker with write access to the manifest path could swap the // file between sig-verify and parse. Fail-closed: load errors are // fatal unless action is explicitly "warn", EXCEPT when // require_signature=true: trust-establishment failures always block // regardless of action. manifest, loadErr := loadMCPIntegrityManifest(icfg) if loadErr != nil { if icfg.RequireSignature || icfg.Action != config.ActionWarn { return fmt.Errorf("binary integrity: loading manifest: %w", loadErr) } _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: %v\n", loadErr) return nil } intCfg.Manifests = manifest.Entries result, verifyErr := integrity.Verify(command, intCfg, agentWorkDir) if verifyErr != nil { if icfg.Action != config.ActionWarn { return fmt.Errorf("binary integrity: %w", verifyErr) } _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: %v\n", verifyErr) return nil } if !result.Verified { reasons := strings.Join(result.Reasons, "; ") if icfg.Action != config.ActionWarn { return fmt.Errorf("binary integrity check failed: %s", reasons) } _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: %s\n", reasons) } return nil } // prepareBinaryIntegrity takes no working directory, unlike VerifyBinaryIntegrity. // Suspicious-path detection compares the resolved binary against the agent's // working directory, and RunProxy has no such directory to compare against: the // field does not exist on Opts, and the pre-descriptor call here never passed // one either. A variadic parameter no caller can fill would read as a supported // option that silently does nothing, so it is absent rather than ignored. The // CLI entry point still passes its workspace to VerifyBinaryIntegrity, where the // comparison is meaningful. func prepareBinaryIntegrity(command []string, icfg *config.MCPBinaryIntegrity, logW io.Writer) (*integrity.PreparedCommand, error) { const agentWorkDir = "" manifest, loadErr := loadMCPIntegrityManifest(icfg) if loadErr != nil { return nil, fmt.Errorf("binary integrity: loading manifest: %w", loadErr) } prepared, err := integrity.Prepare(command, agentWorkDir) if err != nil { return nil, fmt.Errorf("binary integrity: preparing verified descriptors: %w", err) } success := false defer func() { if !success { _ = prepared.Close() } }() intCfg := &integrity.Config{Enabled: true, ManifestPath: icfg.ManifestPath, Action: icfg.Action} intCfg.Manifests = manifest.Entries result := integrity.VerifyPrepared(prepared, intCfg) if !result.Verified { reasons := strings.Join(result.Reasons, "; ") if icfg.Action != config.ActionWarn { return nil, fmt.Errorf("binary integrity check failed: %s", reasons) } _, _ = fmt.Fprintf(logW, "pipelock: binary integrity warning: %s\n", reasons) } success = true return prepared, nil } // loadMCPIntegrityManifest reads the manifest, optionally verifying its // detached signature, and returns the parsed manifest. When // RequireSignature is true the bytes used for parsing are the exact bytes // the signature was verified against - no second os.ReadFile, no TOCTOU // window between trust establishment and parse. func loadMCPIntegrityManifest(icfg *config.MCPBinaryIntegrity) (*integrity.Manifest, error) { if icfg.RequireSignature { pubKey, sigPath, err := resolveMCPManifestSigner(icfg) if err != nil { return nil, err } data, err := signing.LoadAndVerifyFile(icfg.ManifestPath, sigPath, pubKey) if err != nil { return nil, fmt.Errorf("verifying manifest signature: %w", err) } return integrity.ParseManifest(data) } return integrity.LoadManifest(icfg.ManifestPath) } // resolveMCPManifestSigner loads the trusted signer's public key and // resolves the signature path according to the integrity config. The // returned signature path is always non-empty. func resolveMCPManifestSigner(icfg *config.MCPBinaryIntegrity) (ed25519.PublicKey, string, error) { if err := signing.ValidateAgentName(icfg.TrustedSigner); err != nil { if icfg.TrustedSigner == "" { return nil, "", fmt.Errorf("trusted signer is required") } return nil, "", fmt.Errorf("invalid trusted signer %q: %w", icfg.TrustedSigner, err) } keystoreDir := icfg.Keystore if keystoreDir == "" { var err error keystoreDir, err = signing.DefaultKeystorePath() if err != nil { return nil, "", err } } sigPath := icfg.SignaturePath if sigPath == "" { sigPath = icfg.ManifestPath + signing.SigExtension } ks := signing.NewKeystore(keystoreDir) pubKey, err := ks.ResolvePublicKey(icfg.TrustedSigner) if err != nil { return nil, "", fmt.Errorf("loading trusted signer %q: %w", icfg.TrustedSigner, err) } return pubKey, sigPath, nil }