Documentation
¶
Overview ¶
Package proxy provides an embedded HTTP proxy for intercepting outbound requests from the sandboxed agent. It supports multiple LLM providers (Anthropic, OpenAI) in passthrough mode with optional DLP (Data Loss Prevention) processing. In later releases it will also host generic egress substitution for non-LLM services.
internal/proxy/usage.go
Index ¶
- Constants
- func DefaultDialectConfigs() map[Dialect]*DialectConfig
- func HashBody(body []byte) string
- func IsChatGPTToken(r *http.Request) bool
- func IsSSEResponse(resp *http.Response) bool
- type Config
- type CredsSubHook
- type DLPInfo
- type DLPProcessor
- func (dp *DLPProcessor) Detokenize(text string) string
- func (dp *DLPProcessor) DetokenizeReader(r io.Reader) io.Reader
- func (dp *DLPProcessor) ExportTokenMap() map[string]string
- func (dp *DLPProcessor) ImportTokenMap(m map[string]string)
- func (dp *DLPProcessor) Mode() string
- func (dp *DLPProcessor) PatternCount() int
- func (dp *DLPProcessor) PatternNames() []string
- func (dp *DLPProcessor) Process(data []byte, dialect Dialect) *DLPResult
- func (dp *DLPProcessor) Tokenize(original string) string
- type DLPResult
- type Dialect
- type DialectConfig
- type DialectDetector
- type HTTPServiceApprovalsManager
- type HeaderInjectionHook
- type Hook
- type HookAbortError
- type InspectConfig
- type InspectContextFunc
- type InspectHook
- type InterceptResult
- type LLMRateLimiter
- func (l *LLMRateLimiter) AcquireInFlight() bool
- func (l *LLMRateLimiter) AllowRequest() bool
- func (l *LLMRateLimiter) AllowTokens(n int) bool
- func (l *LLMRateLimiter) ConsumeTokens(n int)
- func (l *LLMRateLimiter) ReleaseInFlight()
- func (l *LLMRateLimiter) TPMEnabled() bool
- func (l *LLMRateLimiter) TokenBudgetAvailable() bool
- type LeakGuardHook
- type Proxy
- func (p *Proxy) Addr() net.Addr
- func (p *Proxy) DLP() *DLPProcessor
- func (p *Proxy) EnvVars() map[string]string
- func (p *Proxy) HookRegistry() *Registry
- func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (p *Proxy) SetApprovalsForTest(m HTTPServiceApprovalsManager)
- func (p *Proxy) SetEventCallback(fn func(mcpinspect.MCPToolCallInterceptedEvent))
- func (p *Proxy) SetHTTPServiceApprovals(m HTTPServiceApprovalsManager)
- func (p *Proxy) SetHTTPServiceTransportForTest(rt http.RoundTripper)
- func (p *Proxy) SetHTTPServices(svcs []policy.HTTPService)
- func (p *Proxy) SetMCPArgInspection(resolve InspectContextFunc, maxArgs int)
- func (p *Proxy) SetPolicyEngine(e *policy.Engine)
- func (p *Proxy) SetRegistry(r *mcpregistry.Registry)
- func (p *Proxy) SetSessionAnalyzer(analyzer *mcpinspect.SessionAnalyzer)
- func (p *Proxy) SetStorageForTest(s *Storage)
- func (p *Proxy) Start(ctx context.Context) error
- func (p *Proxy) Stats() (ProxyStatus, error)
- func (p *Proxy) Stop(ctx context.Context) error
- type ProxyStats
- type ProxyStatus
- type Redaction
- type Registry
- func (r *Registry) ApplyPostHooks(serviceName string, resp *http.Response, ctx *RequestContext) error
- func (r *Registry) ApplyPreHooks(serviceName string, req *http.Request, ctx *RequestContext) error
- func (r *Registry) InjectedHeaderNamesForService(serviceName string) []string
- func (r *Registry) Register(serviceName string, h Hook)
- type RequestContext
- type RequestInfo
- type RequestLogEntry
- type RequestRewriter
- type ResponseInfo
- type ResponseLogEntry
- type RetentionConfig
- type RetentionResult
- type SSEInterceptor
- type Storage
- func (s *Storage) BodiesPath() string
- func (s *Storage) Close() error
- func (s *Storage) GetStats() (ProxyStats, error)
- func (s *Storage) LogPath() string
- func (s *Storage) LogRequest(entry *RequestLogEntry) error
- func (s *Storage) LogResponse(entry *ResponseLogEntry) error
- func (s *Storage) ReadLogEntries() ([]json.RawMessage, error)
- func (s *Storage) ReadRequestBody(requestID string) ([]byte, error)
- func (s *Storage) ReadResponseBody(requestID string) ([]byte, error)
- func (s *Storage) StoreBodiesEnabled() bool
- func (s *Storage) StoreRequestBody(requestID string, body []byte) error
- func (s *Storage) StoreResponseBody(requestID string, body []byte) error
- type ToolCall
- type Usage
Constants ¶
const AttrUpstreamURL = "proxy.upstream_url"
AttrUpstreamURL is the Attrs key under which the proxy stores the resolved upstream *url.URL for the request.
It exists because r.Host is the proxy's own listen address: the agent is configured to talk to 127.0.0.1, and the real destination is resolved from the dialect. A hook making a policy decision about where a request is going must use this, not the request's Host.
const DefaultInspectMaxBodyBytes int64 = 8 << 20 // 8 MiB
DefaultInspectMaxBodyBytes caps how much of a request body is buffered for inspection.
The agent controls the body, so an unbounded read is a denial-of-service surface against the daemon rather than against the upstream. Exceeding the cap is treated as a failed inspection, not as a skip: a body too large to inspect is uninspected content, and the rule's on_failure decides what happens to it -- which is a deny by default.
8 MiB rather than something tighter because this proxy carries LLM traffic, and a request with a long context legitimately runs to several megabytes. A cap set below real payload sizes would turn fail_closed into a blanket block on ordinary use, and the operator would have no way to tell that from a policy that was working.
const DefaultMCPArgMaxBytes = 1 << 20
DefaultMCPArgMaxBytes caps how much of a streamed tool argument is accumulated before inspection.
On the streaming paths the arguments arrive as fragments and must be held until complete, so an unbounded accumulator is a memory surface the model on the other end controls. Exceeding the cap is a failed inspection, not a skip: arguments too large to inspect are uninspected arguments, and the rule's on_failure decides -- a deny by default.
1 MiB because a tool argument is a function call's parameters, not a payload. Real ones run to kilobytes; anything near this is already anomalous.
Variables ¶
This section is empty.
Functions ¶
func DefaultDialectConfigs ¶
func DefaultDialectConfigs() map[Dialect]*DialectConfig
DefaultDialectConfigs returns the default configuration for each dialect.
func HashBody ¶
HashBody computes a SHA256 hash of the body for integrity verification. Returns an empty string for empty bodies. Format: "sha256:hexdigest"
func IsChatGPTToken ¶
IsChatGPTToken returns true if the Authorization header contains an OAuth token (non-sk-* Bearer token), indicating ChatGPT login flow.
func IsSSEResponse ¶
IsSSEResponse returns true if the response is a Server-Sent Events stream.
Types ¶
type Config ¶
type Config struct {
// SessionID is the current session ID (set by agentmon).
SessionID string
// Proxy contains proxy mode and upstream settings.
Proxy config.ProxyConfig
// DLP is the DLP configuration.
DLP config.DLPConfig
// Storage is the storage configuration.
Storage config.LLMStorageConfig
// MCP is the MCP security policy configuration.
MCP config.SandboxMCPConfig
}
Config holds the proxy configuration using config package types.
type CredsSubHook ¶
type CredsSubHook struct {
// contains filtered or unexported fields
}
CredsSubHook performs credential substitution using a credsub.Table. PreHook replaces fake credentials with real ones in request bodies. PostHook replaces real credentials with fakes in response bodies.
func NewCredsSubHook ¶
func NewCredsSubHook(table *credsub.Table, scrubServices map[string]bool) *CredsSubHook
NewCredsSubHook returns a CredsSubHook that uses the given table. scrubServices controls which services have response scrubbing enabled. Pass nil to scrub all responses (backward-compatible default).
func (*CredsSubHook) Name ¶
func (h *CredsSubHook) Name() string
func (*CredsSubHook) PostHook ¶
func (h *CredsSubHook) PostHook(resp *http.Response, ctx *RequestContext) error
PostHook replaces real credentials with fakes in the response body. When scrubServices is non-nil, scrubbing is skipped for services not in the map.
func (*CredsSubHook) PreHook ¶
func (h *CredsSubHook) PreHook(r *http.Request, _ *RequestContext) error
PreHook replaces fake credentials with real ones in the request body, header values, URL query string, and URL path.
type DLPInfo ¶
type DLPInfo struct {
Redactions []Redaction `json:"redactions"`
}
DLPInfo contains DLP processing information.
type DLPProcessor ¶
type DLPProcessor struct {
// contains filtered or unexported fields
}
DLPProcessor processes data for PII detection and redaction/tokenization.
func NewDLPProcessor ¶
func NewDLPProcessor(cfg config.DLPConfig) *DLPProcessor
NewDLPProcessor creates a new DLP processor using config.DLPConfig.
func (*DLPProcessor) Detokenize ¶
func (dp *DLPProcessor) Detokenize(text string) string
Detokenize reverses tokenization for a given text.
func (*DLPProcessor) DetokenizeReader ¶
func (dp *DLPProcessor) DetokenizeReader(r io.Reader) io.Reader
DetokenizeReader wraps r so tokens are replaced with their originals as the stream is read.
Streaming needs its own path because a token can straddle a chunk boundary. A per-chunk ReplaceAllString would leave "TOK_abcd" at the end of one read and "ef0123456789" at the start of the next, and neither half matches, so the token would reach the client intact and unresolvable. This holds back a short tail until either enough bytes arrive to decide or the stream ends.
When tokenization is not the active mode there is nothing to reverse, so r is returned unwrapped and the stream keeps its original read boundaries.
func (*DLPProcessor) ExportTokenMap ¶
func (dp *DLPProcessor) ExportTokenMap() map[string]string
ExportTokenMap exports the token mapping for external storage.
func (*DLPProcessor) ImportTokenMap ¶
func (dp *DLPProcessor) ImportTokenMap(m map[string]string)
ImportTokenMap imports a token mapping.
func (*DLPProcessor) Mode ¶
func (dp *DLPProcessor) Mode() string
Mode returns the DLP mode (redact, tokenize, or disabled).
func (*DLPProcessor) PatternCount ¶
func (dp *DLPProcessor) PatternCount() int
PatternCount returns the number of active DLP patterns.
func (*DLPProcessor) PatternNames ¶
func (dp *DLPProcessor) PatternNames() []string
PatternNames returns the names of active DLP patterns.
func (*DLPProcessor) Process ¶
func (dp *DLPProcessor) Process(data []byte, dialect Dialect) *DLPResult
Process applies DLP to the given data.
func (*DLPProcessor) Tokenize ¶
func (dp *DLPProcessor) Tokenize(original string) string
Tokenize mints (or reuses) the reversible pseudonym for a value.
It is the same store the regex DLP path uses, deliberately: one token space per session means Detokenize on the response reverses both, and a value found by both a regex pattern and an inspection profile gets one token rather than two.
type DLPResult ¶
type DLPResult struct {
// ProcessedData is the data after DLP processing.
ProcessedData []byte
// Redactions is a list of redactions that were applied.
Redactions []Redaction
// Modified indicates if any changes were made.
Modified bool
}
DLPResult contains the result of DLP processing.
type DialectConfig ¶
type DialectConfig struct {
// Upstream is the base URL for the provider's API.
Upstream *url.URL
// AuthHeader is the header name used for authentication.
// e.g., "x-api-key" for Anthropic, "Authorization" for OpenAI
AuthHeader string
// PathPrefixes are path prefixes that identify this dialect.
PathPrefixes []string
}
DialectConfig holds configuration for a specific LLM provider dialect.
type DialectDetector ¶
type DialectDetector struct {
// contains filtered or unexported fields
}
DialectDetector detects the LLM provider dialect from HTTP requests.
func NewDialectDetector ¶
func NewDialectDetector(configs map[Dialect]*DialectConfig) *DialectDetector
NewDialectDetector creates a new dialect detector with the given configs.
func (*DialectDetector) Detect ¶
func (d *DialectDetector) Detect(r *http.Request) Dialect
Detect determines the dialect from the request. Detection order: 1. x-api-key header -> Anthropic 2. anthropic-version header -> Anthropic 3. Authorization header present -> OpenAI 4. No auth -> Unknown
func (*DialectDetector) GetUpstream ¶
func (d *DialectDetector) GetUpstream(dialect Dialect) *url.URL
GetUpstream returns the upstream URL for the given dialect.
type HTTPServiceApprovalsManager ¶
type HTTPServiceApprovalsManager interface {
RequestApproval(ctx context.Context, req approvals.Request) (approvals.Resolution, error)
}
HTTPServiceApprovalsManager is the subset of approvals.Manager needed by the declared-service path. Declared here as a local interface to keep the import surface narrow and to simplify testing — tests install a fake implementation via SetApprovalsForTest and don't have to spin up a real approvals.Manager with its TTY/TOTP/WebAuthn machinery.
type HeaderInjectionHook ¶
type HeaderInjectionHook struct {
// contains filtered or unexported fields
}
HeaderInjectionHook injects the real credential into a request header. Registered per service name so it only fires for matched requests.
func NewHeaderInjectionHook ¶
func NewHeaderInjectionHook(serviceName, headerName, template string, table *credsub.Table) *HeaderInjectionHook
NewHeaderInjectionHook creates a hook that injects the real credential for serviceName into the header specified by headerName using template. The template must contain "{{secret}}" which is replaced with the real credential at request time.
func (*HeaderInjectionHook) HeaderName ¶
func (h *HeaderInjectionHook) HeaderName() string
HeaderName returns the header that this hook injects. Used by the declared-service log path to redact the injected value from audit records.
func (*HeaderInjectionHook) Name ¶
func (h *HeaderInjectionHook) Name() string
func (*HeaderInjectionHook) PostHook ¶
func (h *HeaderInjectionHook) PostHook(_ *http.Response, _ *RequestContext) error
func (*HeaderInjectionHook) PreHook ¶
func (h *HeaderInjectionHook) PreHook(r *http.Request, _ *RequestContext) error
type Hook ¶
type Hook interface {
// Name returns a stable identifier for this hook, used in logs and
// audit events.
Name() string
// PreHook is called before the request is forwarded upstream.
PreHook(*http.Request, *RequestContext) error
// PostHook is called after the upstream response arrives and before
// it is returned to the agent.
PostHook(*http.Response, *RequestContext) error
}
Hook is an extension point registered with the proxy. Hooks are keyed by service name and invoked for every request routed to that service. A hook registered under the empty service name runs for every request regardless of which service (if any) matched.
PreHook runs BEFORE the proxy forwards the request to the upstream. At this point the request body still contains whatever the agent sent (including any fake credentials that a later substitution pass will replace). A hook that needs to see the post-substitution body is out of scope for this plan — the Hook interface may grow a third phase in a later plan if that need is real.
Returning a non-nil error from PreHook aborts the request. The proxy returns an HTTP 502 to the agent and logs the error. Remaining pre-hooks for the same request are NOT invoked.
PostHook runs AFTER the upstream responds, but BEFORE the response is returned to the agent. This is where response-time concerns live (audit logging, response scrubbing, token accounting).
Returning a non-nil error from PostHook is logged but does not change the response the agent sees. All post-hooks for the same request are invoked even if one fails.
type HookAbortError ¶
HookAbortError is returned by a PreHook to abort the request with a specific HTTP status code. When the proxy receives this error from ApplyPreHooks, it responds with the given status code and message instead of forwarding the request. Any other error type results in a 502 Bad Gateway.
func (*HookAbortError) Error ¶
func (e *HookAbortError) Error() string
type InspectConfig ¶
type InspectConfig struct {
// Resolve supplies the engine and inspector per request.
Resolve InspectContextFunc
// MaxBodyBytes overrides DefaultInspectMaxBodyBytes. Zero uses it.
MaxBodyBytes int64
// MCPArgMaxBytes overrides DefaultMCPArgMaxBytes, the cap on a single
// MCP tool call's accumulated arguments. Zero uses it.
MCPArgMaxBytes int
}
InspectConfig is what a session hands the LLM proxy to enable inspection.
func (InspectConfig) Enabled ¶
func (c InspectConfig) Enabled() bool
Enabled reports whether inspection should be wired for this session.
type InspectContextFunc ¶
type InspectContextFunc func() (*policy.Engine, policy.InspectChecker)
InspectContextFunc supplies the policy engine and its inspector for the current request.
It is a function rather than two stored pointers so the engine is resolved per request. Proxy.SetPolicyEngine captures an engine at construction, and that capture is why the network, transparent-TCP and DNS paths keep enforcing the previous policy after a live update (documented at internal/api/session_policy.go:47). Inspection does not need a fourth instance of that bug.
type InspectHook ¶
type InspectHook struct {
// contains filtered or unexported fields
}
InspectHook runs content inspection over request bodies.
It resolves only decisions that carry an inspection spec. A plain network deny is left alone: the proxy, the macOS network filter and the Linux netmonitor each enforce network policy on their own path, and a second enforcement point here would change behaviour for every deployment that does not use inspection at all.
func NewInspectHook ¶
func NewInspectHook(resolve InspectContextFunc, maxBody int64, logger *slog.Logger) *InspectHook
NewInspectHook returns a hook that inspects request bodies. A zero or negative maxBody uses DefaultInspectMaxBodyBytes.
func (*InspectHook) PostHook ¶
func (h *InspectHook) PostHook(*http.Response, *RequestContext) error
PostHook implements Hook. Response inspection is not wired: a policy decision is about what the agent sends, and the response path has its own scrubbing in CredsSubHook and the DLP processor.
func (*InspectHook) PreHook ¶
func (h *InspectHook) PreHook(r *http.Request, ctx *RequestContext) error
PreHook implements Hook.
func (*InspectHook) SetDLP ¶
func (h *InspectHook) SetDLP(dp *DLPProcessor)
SetDLP installs the DLP processor whose token store backs reversible redaction. Without it, on_violation: redact writes a placeholder.
type InterceptResult ¶
type InterceptResult struct {
Events []mcpinspect.MCPToolCallInterceptedEvent
HasBlocked bool
RewrittenBody []byte // Non-nil if tool calls were blocked or arguments redacted
}
InterceptResult holds the outcome of MCP tool call interception.
type LLMRateLimiter ¶
type LLMRateLimiter struct {
// contains filtered or unexported fields
}
LLMRateLimiter enforces RPM (requests per minute) and TPM (tokens per minute) rate limits on LLM API calls to prevent denial-of-wallet attacks.
func NewLLMRateLimiter ¶
func NewLLMRateLimiter(cfg config.LLMRateLimitsConfig) *LLMRateLimiter
NewLLMRateLimiter creates a new LLM rate limiter from configuration.
func (*LLMRateLimiter) AcquireInFlight ¶
func (l *LLMRateLimiter) AcquireInFlight() bool
AcquireInFlight attempts to acquire an in-flight slot (when TPM is enabled). Returns false if TPM is not configured or the concurrency cap is reached. Non-blocking: if all slots are occupied, returns false immediately so the caller can reject the request (e.g. 429) instead of piling up goroutines.
func (*LLMRateLimiter) AllowRequest ¶
func (l *LLMRateLimiter) AllowRequest() bool
AllowRequest checks whether a new request is allowed under the RPM limit.
func (*LLMRateLimiter) AllowTokens ¶
func (l *LLMRateLimiter) AllowTokens(n int) bool
AllowTokens checks whether the given number of tokens is allowed under the TPM limit.
func (*LLMRateLimiter) ConsumeTokens ¶
func (l *LLMRateLimiter) ConsumeTokens(n int)
ConsumeTokens deducts tokens from the TPM budget after a response is received. Uses force-consume since the operation already happened and must be accounted for.
func (*LLMRateLimiter) ReleaseInFlight ¶
func (l *LLMRateLimiter) ReleaseInFlight()
ReleaseInFlight releases an in-flight slot. Must be called after AcquireInFlight returns true, typically in a defer.
func (*LLMRateLimiter) TPMEnabled ¶
func (l *LLMRateLimiter) TPMEnabled() bool
TPMEnabled returns true if tokens-per-minute limiting is active.
func (*LLMRateLimiter) TokenBudgetAvailable ¶
func (l *LLMRateLimiter) TokenBudgetAvailable() bool
TokenBudgetAvailable returns true if the TPM bucket is not depleted. Use this as a pre-request gate: if previous responses have driven the token bucket negative (via ForceConsumeN), block new requests until tokens replenish.
type LeakGuardHook ¶
type LeakGuardHook struct {
// contains filtered or unexported fields
}
LeakGuardHook blocks requests that contain known fake credentials.
func NewLeakGuardHook ¶
func NewLeakGuardHook(table *credsub.Table, logger *slog.Logger) *LeakGuardHook
NewLeakGuardHook returns a LeakGuardHook that scans for fakes.
func (*LeakGuardHook) Name ¶
func (h *LeakGuardHook) Name() string
func (*LeakGuardHook) PostHook ¶
func (h *LeakGuardHook) PostHook(_ *http.Response, _ *RequestContext) error
func (*LeakGuardHook) PreHook ¶
func (h *LeakGuardHook) PreHook(r *http.Request, ctx *RequestContext) error
type Proxy ¶
type Proxy struct {
// contains filtered or unexported fields
}
Proxy is an HTTP proxy that intercepts LLM API requests.
func (*Proxy) DLP ¶
func (p *Proxy) DLP() *DLPProcessor
DLP returns the proxy's DLP processor, or nil.
func (*Proxy) EnvVars ¶
EnvVars returns the environment variables to set for the agent process. In addition to the LLM base URLs, this includes one <NAME>_API_URL entry per declared http_services entry, each pointing at /svc/<name> on the proxy listener so cooperating child processes can route through the gateway via a base URL override.
func (*Proxy) HookRegistry ¶
HookRegistry returns the proxy's hook registry. Callers use this to register Hook implementations that participate in the request pipeline.
func (*Proxy) ServeHTTP ¶
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
func (*Proxy) SetApprovalsForTest ¶
func (p *Proxy) SetApprovalsForTest(m HTTPServiceApprovalsManager)
SetApprovalsForTest installs an approvals manager for the declared- service path. Test-only; production wiring goes through SetHTTPServiceApprovals.
func (*Proxy) SetEventCallback ¶
func (p *Proxy) SetEventCallback(fn func(mcpinspect.MCPToolCallInterceptedEvent))
SetEventCallback sets a callback that is invoked for each MCP tool call intercept event. It is safe for concurrent use.
func (*Proxy) SetHTTPServiceApprovals ¶
func (p *Proxy) SetHTTPServiceApprovals(m HTTPServiceApprovalsManager)
SetHTTPServiceApprovals wires the approvals manager consulted for `approve` decisions on declared services. Called once during startup from app.go alongside SetPolicyEngine and SetHTTPServices.
func (*Proxy) SetHTTPServiceTransportForTest ¶
func (p *Proxy) SetHTTPServiceTransportForTest(rt http.RoundTripper)
SetHTTPServiceTransportForTest injects a RoundTripper used for declared-service forwarding. Test-only.
func (*Proxy) SetHTTPServices ¶
func (p *Proxy) SetHTTPServices(svcs []policy.HTTPService)
SetHTTPServices stores the declared HTTP services for env var injection. Called once during proxy startup in app.go. Thread-safe. The slice is stored as-is — SetHTTPServices replaces it whole on each call and EnvVars snapshots it under lock, so no in-place mutation is safe.
func (*Proxy) SetMCPArgInspection ¶
func (p *Proxy) SetMCPArgInspection(resolve InspectContextFunc, maxArgs int)
SetMCPArgInspection installs argument inspection for MCP tool calls. A nil resolve disables it.
func (*Proxy) SetPolicyEngine ¶
SetPolicyEngine wires the policy engine for http_services dispatch. Called once during startup.
func (*Proxy) SetRegistry ¶
func (p *Proxy) SetRegistry(r *mcpregistry.Registry)
SetRegistry sets the MCP tool registry on the proxy. It is safe for concurrent use and is called once the shim has finished discovering tools.
func (*Proxy) SetSessionAnalyzer ¶
func (p *Proxy) SetSessionAnalyzer(analyzer *mcpinspect.SessionAnalyzer)
SetSessionAnalyzer sets the cross-server analyzer on the proxy. It is safe for concurrent use and is called once the analyzer has been created.
func (*Proxy) SetStorageForTest ¶
SetStorageForTest installs a Storage instance for the declared-service logging path. Production uses the same Storage that the LLM path uses; tests point it at a temp dir. Test-only setter to keep the dependency visible.
func (*Proxy) Stats ¶
func (p *Proxy) Stats() (ProxyStatus, error)
Stats returns the current proxy status including usage statistics.
type ProxyStats ¶
type ProxyStats struct {
TotalRequests int `json:"total_requests"`
RequestsWithRedactions int `json:"requests_with_redactions"`
TotalInputTokens int `json:"total_input_tokens"`
TotalOutputTokens int `json:"total_output_tokens"`
TotalRedactions int `json:"total_redactions"`
}
ProxyStats contains aggregated statistics from the proxy log.
type ProxyStatus ¶
type ProxyStatus struct {
State string `json:"state"`
Address string `json:"address"`
Mode string `json:"mode"`
DLPMode string `json:"dlp_mode"`
ActivePatterns int `json:"active_patterns"`
PatternNames []string `json:"pattern_names,omitempty"`
TotalRequests int `json:"total_requests"`
RequestsWithRedactions int `json:"requests_with_redactions"`
TotalInputTokens int `json:"total_input_tokens"`
TotalOutputTokens int `json:"total_output_tokens"`
}
ProxyStatus contains the complete status of the proxy.
type Redaction ¶
type Redaction struct {
// Field is the JSON path where the redaction occurred (if applicable).
Field string `json:"field,omitempty"`
// Type is the internal type name of PII that was detected (for logs).
Type string `json:"type"`
// Count is the number of unique instances redacted.
Count int `json:"count"`
}
Redaction describes a single redaction event.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry stores hooks keyed by service name. It is safe for concurrent use. Hooks registered for the same service name are invoked in registration order.
The zero value of Registry is NOT usable — call NewRegistry.
func (*Registry) ApplyPostHooks ¶
func (r *Registry) ApplyPostHooks(serviceName string, resp *http.Response, ctx *RequestContext) error
ApplyPostHooks invokes PostHook on every hook registered under the empty service name and serviceName, in registration order. Unlike ApplyPreHooks, errors do NOT short-circuit — every hook is invoked even if an earlier one fails. The first error encountered is returned; subsequent errors are silently dropped (hooks that need their own error reporting should log internally).
func (*Registry) ApplyPreHooks ¶
ApplyPreHooks invokes PreHook on each hook registered under the empty service name followed by each hook registered under serviceName, in registration order. It stops at the first non-nil error and returns it. Hooks that have not been reached are not invoked.
func (*Registry) InjectedHeaderNamesForService ¶
InjectedHeaderNamesForService returns the set of header names that HeaderInjectionHook entries registered for serviceName will write. Declared-service request/response logging consults this list so the audit sanitizer can redact the injected values even when the header name is not in the fixed auth denylist. Includes hooks registered under the empty service name (which run globally).
func (*Registry) Register ¶
Register adds a hook under the given service name. A hook may be registered multiple times under different service names; a single service may have multiple hooks registered. Use the empty string as the service name to register a hook that runs for every request.
Register panics if h is nil — all hooks must be non-nil interface values. This catches programmer errors at registration time rather than producing a confusing nil pointer dereference later inside ApplyPreHooks or ApplyPostHooks. Both bare nil (an untyped nil interface) and typed-nil hooks (e.g. a nil *concreteHook assigned to a Hook variable) are rejected.
type RequestContext ¶
type RequestContext struct {
// RequestID is a unique identifier assigned by the proxy for each
// incoming request. Hooks may use it for correlation across logs.
RequestID string
// SessionID is the agentmon session ID that owns the spawned process
// making this request.
SessionID string
// ServiceName is the name of the service this request was matched
// to, or the empty string if no service matched. Hooks registered
// under the empty service name run for every request regardless of
// match.
ServiceName string
// StartTime is when the proxy first saw this request.
StartTime time.Time
// Attrs is a hook-private scratch area. Hooks must namespace their
// keys to avoid colliding with other hooks.
Attrs map[string]any
}
RequestContext carries per-request state shared between the proxy and any registered hooks. It is created by the proxy at the start of each request and passed to PreHook and PostHook callbacks.
Attrs is a free-form map intended for hooks to communicate with each other — for example, a DLP hook storing its redaction result so a later logging hook can include it in the audit event. Keys should be namespaced with the hook's package name (e.g. "llm.dlp.result") to avoid collisions.
type RequestInfo ¶
type RequestInfo struct {
Method string `json:"method"`
Path string `json:"path"`
Headers map[string][]string `json:"headers"`
BodySize int `json:"body_size"`
BodyHash string `json:"body_hash"`
}
RequestInfo contains request details.
type RequestLogEntry ¶
type RequestLogEntry struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
Timestamp time.Time `json:"timestamp"`
Dialect Dialect `json:"dialect,omitempty"`
ServiceKind string `json:"service_kind,omitempty"` // "llm" or "http_service"
ServiceName string `json:"service_name,omitempty"` // e.g. "github"
RuleName string `json:"rule_name,omitempty"` // e.g. "read-issues"
Request RequestInfo `json:"request"`
DLP *DLPInfo `json:"dlp,omitempty"`
}
RequestLogEntry represents a logged request.
type RequestRewriter ¶
type RequestRewriter struct {
// contains filtered or unexported fields
}
RequestRewriter rewrites requests for forwarding to upstream.
func NewRequestRewriter ¶
func NewRequestRewriter(detector *DialectDetector) *RequestRewriter
NewRequestRewriter creates a new request rewriter.
type ResponseInfo ¶
type ResponseInfo struct {
Status int `json:"status"`
Headers map[string][]string `json:"headers"`
BodySize int `json:"body_size,omitempty"`
BodyHash string `json:"body_hash,omitempty"`
}
ResponseInfo contains response details.
type ResponseLogEntry ¶
type ResponseLogEntry struct {
RequestID string `json:"request_id"`
SessionID string `json:"session_id"`
Timestamp time.Time `json:"timestamp"`
DurationMs int64 `json:"duration_ms"`
Response ResponseInfo `json:"response"`
Usage Usage `json:"usage,omitempty"`
}
ResponseLogEntry represents a logged response.
type RetentionConfig ¶
type RetentionConfig struct {
MaxAgeDays int // Delete sessions older than this (0 = disabled)
MaxSizeMB int // Max total storage size in MB (0 = disabled)
Eviction string // "oldest_first" or "largest_first"
}
RetentionConfig configures session cleanup policy.
type RetentionResult ¶
type RetentionResult struct {
SessionsRemoved int
BytesReclaimed int64
Sessions []string // IDs of removed sessions
}
RetentionResult reports cleanup results.
func RunRetention ¶
func RunRetention( sessionsDir string, config RetentionConfig, currentSessionID string, logger *slog.Logger, ) (*RetentionResult, error)
RunRetention cleans up old sessions based on retention policy. currentSessionID is excluded from cleanup. Runs synchronously - caller should use goroutine if non-blocking behavior is needed.
type SSEInterceptor ¶
type SSEInterceptor struct {
// contains filtered or unexported fields
}
SSEInterceptor processes an SSE stream line-by-line, evaluating MCP tool calls against a policy and suppressing/replacing blocked tool_use events mid-stream. It replaces the previous io.Copy approach where SSE interception was audit-only.
func NewSSEInterceptor ¶
func NewSSEInterceptor( registry *mcpregistry.Registry, policy *mcpinspect.PolicyEvaluator, dialect Dialect, sessionID, requestID string, onEvent func(mcpinspect.MCPToolCallInterceptedEvent), logger *slog.Logger, analyzer *mcpinspect.SessionAnalyzer, rateLimiter *mcpinspect.RateLimiterRegistry, versionPinCfg *config.MCPVersionPinningConfig, mcpArgs *mcpArgInspector, ) *SSEInterceptor
NewSSEInterceptor creates a new SSE stream interceptor. The analyzer parameter enables cross-server pattern detection; pass nil to disable.
type Storage ¶
type Storage struct {
// contains filtered or unexported fields
}
Storage handles request/response logging to disk.
func NewStorage ¶
NewStorage creates a new storage instance. basePath is the base storage directory (e.g., ~/.agentmon/sessions). sessionID is the current session ID. storeBodies enables storing full request/response bodies to disk.
func (*Storage) BodiesPath ¶
BodiesPath returns the path to the bodies directory.
func (*Storage) GetStats ¶
func (s *Storage) GetStats() (ProxyStats, error)
GetStats reads the log file and computes aggregated statistics.
func (*Storage) LogRequest ¶
func (s *Storage) LogRequest(entry *RequestLogEntry) error
LogRequest logs a request entry to the JSONL file.
func (*Storage) LogResponse ¶
func (s *Storage) LogResponse(entry *ResponseLogEntry) error
LogResponse logs a response entry to the JSONL file.
func (*Storage) ReadLogEntries ¶
func (s *Storage) ReadLogEntries() ([]json.RawMessage, error)
ReadLogEntries reads all log entries from storage. This is useful for testing and debugging.
func (*Storage) ReadRequestBody ¶
ReadRequestBody reads a stored request body from disk. Returns nil if the file doesn't exist.
func (*Storage) ReadResponseBody ¶
ReadResponseBody reads a stored response body from disk. Returns nil if the file doesn't exist.
func (*Storage) StoreBodiesEnabled ¶
StoreBodiesEnabled returns whether body storage is enabled.
func (*Storage) StoreRequestBody ¶
StoreRequestBody stores the request body to disk. The body is stored as JSON in llm-bodies/<request_id>.json Returns nil if body storage is disabled or body is empty.
type ToolCall ¶
type ToolCall struct {
ID string // "toolu_..." or "call_..."
Name string // tool name
Input json.RawMessage // arguments
}
ToolCall represents a tool invocation extracted from an LLM response.
func ExtractToolCalls ¶
ExtractToolCalls parses tool call blocks from an LLM response body. It returns nil if no tool calls are found or the body is malformed.
func ExtractToolCallsFromSSE ¶
ExtractToolCallsFromSSE parses tool calls from a buffered SSE response body. It dispatches to dialect-specific extractors based on the dialect parameter. Returns nil if no tool calls are found.
For SSE extraction, ToolCall.Input will be nil because we do not accumulate streamed argument deltas -- we only need the tool name and ID for policy evaluation.
type Usage ¶
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
HasUsage bool `json:"-"` // true when the response contained a parseable usage field
}
Usage represents normalized token usage from LLM responses. Different providers use different field names, but we normalize to input_tokens and output_tokens for consistent logging and cost attribution.
func ExtractSSEUsage ¶
ExtractSSEUsage extracts token usage from an SSE event stream body. It scans each "data:" line for usage information.
func ExtractUsage ¶
ExtractUsage extracts token usage from an LLM response body. It normalizes the provider-specific field names to the standard InputTokens and OutputTokens fields.
For Anthropic responses:
{"usage": {"input_tokens": 150, "output_tokens": 892}}
For OpenAI/ChatGPT responses:
{"usage": {"prompt_tokens": 150, "completion_tokens": 892, "total_tokens": 1042}}
Returns zero Usage if the body is empty, invalid JSON, or the dialect is unknown.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package credsub implements the per-session credential substitution table that maps fake credentials (the bytes an agent sees in its environment) to real credentials (the bytes sent upstream).
|
Package credsub implements the per-session credential substitution table that maps fake credentials (the bytes an agent sees in its environment) to real credentials (the bytes sent upstream). |
|
Package secrets defines the SecretProvider interface that agentmon uses to fetch real credentials from external secret stores at session start, plus the URI grammar, sentinel errors, and the provider Registry shared by all provider implementations.
|
Package secrets defines the SecretProvider interface that agentmon uses to fetch real credentials from external secret stores at session start, plus the URI grammar, sentinel errors, and the provider Registry shared by all provider implementations. |
|
awssm
Package awssm implements secrets.SecretProvider using AWS Secrets Manager.
|
Package awssm implements secrets.SecretProvider using AWS Secrets Manager. |
|
azurekv
Package azurekv implements secrets.SecretProvider using Azure Key Vault.
|
Package azurekv implements secrets.SecretProvider using Azure Key Vault. |
|
gcpsm
Package gcpsm implements secrets.SecretProvider using GCP Secret Manager.
|
Package gcpsm implements secrets.SecretProvider using GCP Secret Manager. |
|
keyring
Package keyring implements secrets.SecretProvider using the OS keyring: macOS Keychain (via /usr/bin/security), Linux Secret Service (via D-Bus), or Windows Credential Manager.
|
Package keyring implements secrets.SecretProvider using the OS keyring: macOS Keychain (via /usr/bin/security), Linux Secret Service (via D-Bus), or Windows Credential Manager. |
|
onepassword
Package onepassword implements secrets.SecretProvider using the 1Password Connect API.
|
Package onepassword implements secrets.SecretProvider using the 1Password Connect API. |
|
secretstest
Package secretstest provides test doubles for the secrets.SecretProvider interface.
|
Package secretstest provides test doubles for the secrets.SecretProvider interface. |
|
vault
Package vault implements secrets.SecretProvider using HashiCorp Vault's KV v2 secrets engine.
|
Package vault implements secrets.SecretProvider using HashiCorp Vault's KV v2 secrets engine. |