bouncer

package
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package bouncer provides token validation, secret pattern matching, and streaming redaction for MCP proxy request/response filtering and security enforcement.

Index

Constants

View Source
const (
	// DefaultEstimatedTools is the default tool-count estimate when the
	// registry entry does not declare one. It matches the average used by
	// pkg/utils.TokenEstimator.CompareMCPConfigurations.
	DefaultEstimatedTools = 35
)
View Source
const SecretRedacted = "[SECRET_REDACTED]"
View Source
const SidecarFallback = "[VALUE_REDACTED]"

SidecarFallback is the sentinel string the sidecar LLM emits when its primary path fails (Ollama down, decode error, empty response). The redactor treats it as "I could not redact anything; do whatever you did without me" rather than as a hard error, so a single Ollama hiccup does not reject every request. See pkg/sidecar.Client.aggressiveRedact.

Variables

View Source
var (
	// ErrInvalidToken indicates the provided token is invalid.
	ErrInvalidToken = errors.New("invalid token")
	// ErrExpiredToken indicates the provided token has expired.
	ErrExpiredToken = errors.New("expired token")
	// ErrMissingToken indicates no token was provided.
	ErrMissingToken = errors.New("missing token")
)
View Source
var BuiltInPatterns = []SecretPattern{
	{
		Name:        "aws-access-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`AKIA[0-9A-Z]{16}`),
		Keywords:    []string{"AKIA"},
		Example:     "AKIAIOSFODNN7EXAMPLE",
		Description: "AWS Access Key ID (20 characters, starts with AKIA)",
	},
	{
		Name:        "aws-temporary-access-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`ASIA[0-9A-Z]{16}`),
		Keywords:    []string{"ASIA"},
		Example:     "ASIA followed by 16 uppercase letters or digits",
		Description: "AWS temporary (STS) Access Key ID (20 characters, starts with ASIA)",
	},
	{
		Name:         "aws-secret-access-key",
		Severity:     SeverityCritical,
		Pattern:      regexp.MustCompile(`(?i)aws_?secret_?access_?key["']?\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)`),
		Keywords:     []string{"aws"},
		KeywordsFold: true,
		SecretGroup:  1,
		Example:      "aws_secret_access_key = <40 base64 characters>",
		Description:  "AWS Secret Access Key (40 base64 characters after aws_secret_access_key; only the key is replaced)",
	},
	{
		Name:        "github-classic-pat",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`ghp_[A-Za-z0-9]{36,}`),
		Keywords:    []string{"ghp_"},
		Example:     "ghp_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		Description: "GitHub Classic Personal Access Token (starts with ghp_, 36+ chars after prefix)",
	},
	{
		Name:        "github-app-token",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`gh[ousr]_[A-Za-z0-9]{36,}`),
		Keywords:    []string{"gho_", "ghu_", "ghs_", "ghr_"},
		Example:     "gho_ / ghu_ / ghs_ / ghr_ followed by 36+ alphanumerics",
		Description: "GitHub OAuth, user-to-server, server-to-server and refresh tokens (gho_, ghu_, ghs_, ghr_)",
	},
	{
		Name:        "github-fine-grained-pat",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`github_pat_[A-Za-z0-9_]{22,}`),
		Keywords:    []string{"github_pat_"},
		Example:     "github_pat_11XXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXX",
		Description: "GitHub Fine-grained PAT (starts with github_pat_)",
	},
	{
		Name:        "gitlab-pat",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`glpat-[A-Za-z0-9_-]{20,}`),
		Keywords:    []string{"glpat-"},
		Example:     "glpat-XXXXXXXXXXXXXXXXXXXX",
		Description: "GitLab Personal Access Token (starts with glpat-, 20+ chars after prefix)",
	},
	{
		Name:        "stripe-secret-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`sk_(?:live|test)_[A-Za-z0-9]{24,}`),
		Keywords:    []string{"sk_live_", "sk_test_"},
		Example:     "sk_live_ / sk_test_ followed by 24+ alphanumerics",
		Description: "Stripe secret key, live or test mode (sk_live_, sk_test_)",
	},
	{
		Name:        "stripe-restricted-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`rk_(?:live|test)_[A-Za-z0-9]{24,}`),
		Keywords:    []string{"rk_live_", "rk_test_"},
		Example:     "rk_live_ / rk_test_ followed by 24+ alphanumerics",
		Description: "Stripe restricted key, live or test mode (rk_live_, rk_test_)",
	},
	{
		Name:        "stripe-publishable-key",
		Severity:    SeverityLow,
		Pattern:     regexp.MustCompile(`pk_live_[A-Za-z0-9]{24}`),
		Keywords:    []string{"pk_live_"},
		Example:     "[Stripe Publishable Key - 24 chars after pk_live_]",
		Description: "Stripe Live Publishable Key (starts with pk_live_)",
	},
	{
		Name:        "pem-private-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----`),
		Keywords:    []string{"PRIVATE KEY-----"},
		Example:     "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQ...\n-----END RSA PRIVATE KEY-----",
		Description: "Multi-line PEM-encoded private keys (RSA, EC, DSA, OpenSSH, PKCS8, encrypted)",
	},
	{
		Name:        "pgp-private-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`-----BEGIN PGP PRIVATE KEY BLOCK-----[\s\S]+?-----END PGP PRIVATE KEY BLOCK-----`),
		Keywords:    []string{"-----BEGIN PGP PRIVATE KEY BLOCK-----"},
		Example:     "-----BEGIN PGP PRIVATE KEY BLOCK-----\n...\n-----END PGP PRIVATE KEY BLOCK-----",
		Description: "ASCII-armored PGP/GPG private key blocks",
	},
	{
		Name:        "pem-certificate",
		Severity:    SeverityLow,
		Pattern:     regexp.MustCompile(`-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----`),
		Keywords:    []string{"-----BEGIN CERTIFICATE-----"},
		Example:     "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgI...\n-----END CERTIFICATE-----",
		Description: "Multi-line PEM-encoded X.509 certificates",
	},
	{
		Name:        "gcp-service-account",
		Severity:    SeverityLow,
		Pattern:     regexp.MustCompile(`"type"\s*:\s*"service_account"`),
		Keywords:    []string{"service_account"},
		Example:     `{"type": "service_account", "project_id": "...", "private_key": "..."}`,
		Description: "GCP service account JSON key marker (\"type\": \"service_account\") in free text; in JSON the private_key field is redacted by key name",
	},
	{
		Name:        "gcp-oauth-token",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`ya29\.[A-Za-z0-9_-]{20,}`),
		Keywords:    []string{"ya29."},
		Example:     "ya29.XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		Description: "GCP OAuth2 access / refresh token (starts with ya29., 20+ alphanumeric/_/- chars after)",
	},
	{
		Name:        "google-api-key",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`AIza[0-9A-Za-z_-]{35}`),
		Keywords:    []string{"AIza"},
		Example:     "AIza followed by 35 characters from [0-9A-Za-z_-]",
		Description: "Google API key (Maps, Firebase, Gemini, ...; 39 characters starting with AIza)",
	},
	{
		Name:        "slack-token",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`xox[bpars]-[A-Za-z0-9-]{20,}`),
		Keywords:    []string{"xox"},
		Example:     "xoxb-XXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX",
		Description: "Slack bot/user/app/refresh token (xoxb-, xoxp-, xoxa-, xoxr-, xoxs-, 20+ chars after prefix)",
	},
	{
		Name:        "slack-webhook",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`https://hooks\.slack\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{16,}`),
		Keywords:    []string{"hooks.slack.com"},
		Example:     "https://hooks.slack.com/services/T.../B.../...",
		Description: "Slack incoming-webhook URL",
	},
	{
		Name:        "openai-api-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`sk-[A-Za-z0-9]{40,}`),
		Keywords:    []string{"sk-"},
		Example:     "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		Description: "OpenAI API key, legacy format (sk- followed by 40+ alphanumeric chars)",
	},
	{
		Name:        "openai-project-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{40,}`),
		Keywords:    []string{"sk-proj-", "sk-svcacct-", "sk-admin-"},
		Example:     "sk-proj- followed by 40+ characters from [A-Za-z0-9_-]",
		Description: "OpenAI project, service-account and admin keys (sk-proj-, sk-svcacct-, sk-admin-)",
	},
	{
		Name:        "anthropic-api-key",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`sk-ant-[A-Za-z0-9_-]{32,}`),
		Keywords:    []string{"sk-ant-"},
		Example:     "sk-ant-api03-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		Description: "Anthropic API key (starts with sk-ant-, 32+ chars after prefix)",
	},
	{
		Name:        "npm-token",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`npm_[A-Za-z0-9]{36}`),
		Keywords:    []string{"npm_"},
		Example:     "npm_ followed by 36 alphanumerics",
		Description: "npm access token (starts with npm_)",
	},
	{
		Name:         "generic-api-key",
		Severity:     SeverityMedium,
		Pattern:      regexp.MustCompile(`(?i)(api[_-]?key)[_-]?[=]?[A-Za-z0-9]{16,}`),
		Keywords:     []string{"api"},
		KeywordsFold: true,
		Example:      "api_key=abcdefghijklmnopqrstuvwx",
		Description:  "Generic API key pattern (case-insensitive)",
	},
	{
		Name:         "bearer-token",
		Severity:     SeverityHigh,
		Pattern:      regexp.MustCompile(`(?i)bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+`),
		Keywords:     []string{"bearer"},
		KeywordsFold: true,
		Example:      "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
		Description:  "JWT Bearer token (three base64url segments)",
	},
	{
		Name:        "jwt",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`eyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*`),
		Keywords:    []string{"eyJ"},
		Example:     "eyJ<header>.eyJ<payload>.<signature>",
		Description: "JSON Web Token without a Bearer prefix (base64url header and payload both start with eyJ)",
	},
	{
		Name:         "basic-auth-header",
		Severity:     SeverityHigh,
		Pattern:      regexp.MustCompile(`(?i)authorization["']?\s*[:=]\s*["']?basic\s+([A-Za-z0-9+/]{8,}={0,2})`),
		Keywords:     []string{"authorization"},
		KeywordsFold: true,
		SecretGroup:  1,
		Example:      "Authorization: Basic dXNlcjpwYXNzd29yZA==",
		Description:  "HTTP Basic credentials after an Authorization header (only the base64 credentials are replaced)",
	},
	{
		Name:        "dsn-credentials",
		Severity:    SeverityCritical,
		Pattern:     regexp.MustCompile(`://[^:@/\s"'<>]*:([^@/\s"'<>]+)@`),
		Keywords:    []string{"://"},
		SecretGroup: 1,
		Example:     "postgres://user:password@db:5432/app",
		Description: "Password in a connection string or URL (postgres://, mysql://, mongodb+srv://, redis://, amqp://, https://user:pass@...; only the password is replaced)",
	},
	{
		Name:        "env-var-value",
		Severity:    SeverityMedium,
		Pattern:     regexp.MustCompile(`\$[A-Z_][A-Z0-9_]{0,30}=([^\s,}]+)`),
		Keywords:    []string{"$"},
		Example:     "$API_KEY=secret123",
		Description: "Environment variable assignment",
	},
	{
		Name:        "env-file-secret",
		Severity:    SeverityHigh,
		Pattern:     regexp.MustCompile(`(?m)^[ \t]*(?:export[ \t]+)?[A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|PRIVATE_KEY|ACCESS_KEY)[ \t]*=[ \t]*["']?([^\s"'#]+)`),
		Keywords:    []string{"PASSWORD", "PASSWD", "SECRET", "TOKEN", "API", "PRIVATE_KEY", "ACCESS_KEY"},
		SecretGroup: 1,
		Example:     "DB_PASSWORD=hunter2 (a line of a .env file)",
		Description: "Value of a .env / shell assignment whose UPPER_CASE name ends in PASSWORD, SECRET, TOKEN, API_KEY, PRIVATE_KEY or ACCESS_KEY (only the value is replaced)",
	},
}
View Source
var EmbedResultHandler func(EmbedOutcome)
View Source
var (
	ErrDangerousPattern = errors.New("dangerous regex pattern detected")
)
View Source
var SensitiveJSONFieldNames = func() []string {
	names := make([]string, 0, len(sensitiveKeyExact))
	for k := range sensitiveKeyExact {
		names = append(names, k)
	}
	sort.Strings(names)
	return names
}()

SensitiveJSONFieldNames lists the canonical sensitive key names, for documentation and for callers that want to display them. Matching is done on normalized keys by IsSensitiveKey.

Functions

func AppendDecodedJSONString added in v1.1.1

func AppendDecodedJSONString(dst, raw []byte) []byte

AppendDecodedJSONString appends the decoded value of a string literal's raw content (as bounded by a JSONString) to dst.

func ApplyJSONEdits added in v1.1.1

func ApplyJSONEdits(data []byte, edits []JSONEdit) []byte

ApplyJSONEdits returns data with the (sorted, non-overlapping) edits applied. data is returned unchanged when there are no edits.

func CompileCustomPatterns added in v0.2.0

func CompileCustomPatterns(configs []PatternConfig) ([]*regexp.Regexp, error)

func CompileCustomPatternsWithTimeout added in v0.2.0

func CompileCustomPatternsWithTimeout(configs []PatternConfig, timeout time.Duration) ([]*regexp.Regexp, error)

func CompilePatterns added in v0.2.0

func CompilePatterns(configs []PatternConfig) ([]*regexp.Regexp, error)

func DetectLanguage added in v0.2.0

func DetectLanguage(filename string) string

func EmbedFailureCount added in v0.8.0

func EmbedFailureCount() uint64

func EmbedSuccessCount added in v0.8.0

func EmbedSuccessCount() uint64

func EmbedToolCall added in v0.8.0

func EmbedToolCall(ctx context.Context, req EmbedRequest)

func EscapeJSONStringContent added in v1.1.1

func EscapeJSONStringContent(b []byte) []byte

EscapeJSONStringContent returns b escaped for use inside a JSON string literal (no HTML escaping, no surrounding quotes).

func EstimateToolsFromDescription added in v0.8.0

func EstimateToolsFromDescription(description string) int

EstimateToolsFromDescription derives a coarse tool-count estimate from the size of the registry entry's description. It is intentionally simple so it can be used as a fallback when no other signal is present; callers should prefer ComputeSnapshot with an explicit tool count whenever possible.

func FindDangerousPatterns added in v0.6.0

func FindDangerousPatterns(patterns []string) (unsafe []string, err error)

func FormatPatternList added in v0.2.0

func FormatPatternList() string

func FormatSnapshot added in v0.8.0

func FormatSnapshot(s Snapshot) string

FormatSnapshot renders the snapshot as a short human-readable block ready to print to stdout. Lines are kept short for terminal readability.

func GetBuffer added in v0.2.0

func GetBuffer() []byte

func GetPatternNames added in v0.2.0

func GetPatternNames() []string

func GlobalEmbedPool added in v0.8.0

func GlobalEmbedPool() *embedder.Pool

func IsPatternSafe added in v0.6.0

func IsPatternSafe(pattern string) bool

func IsSensitiveKey added in v1.1.1

func IsSensitiveKey(key string) bool

IsSensitiveKey reports whether a JSON object key names a credential. The comparison is case-insensitive and ignores '-', '_' and spaces, so "API-Key", "api_key" and "apiKey" are the same key.

func LoadPatternsWithLogging added in v0.2.0

func LoadPatternsWithLogging(customConfigs []PatternConfig) ([]*regexp.Regexp, []string)

func MatchSecret added in v0.2.0

func MatchSecret(input string) []string

func PatternsToRegexps added in v0.2.0

func PatternsToRegexps(patterns []SecretPattern) []*regexp.Regexp

func RedactJSONWithSidecar added in v0.8.0

func RedactJSONWithSidecar(ctx context.Context, data []byte, r *Redactor, sidecar SidecarClient, alwaysCallSidecar bool) ([]byte, error)

RedactJSONWithSidecar applies the regex redactor first and then, if a sidecar is configured and either the regex matched nothing or alwaysCallSidecar is true, hands the already-redacted content to the sidecar for a second pass. The sidecar therefore never sees a secret the regex layer could catch (the regex pass runs first regardless), and its output is accepted only if it is valid JSON with the same structure as its input (VerifySidecarOutput) or matches the sidecar's documented fallback sentinel. Output that is valid JSON but changes the structure is discarded in favor of the regex-redacted input, with a warning.

func RedactSecrets added in v0.2.0

func RedactSecrets(input string) string

RedactSecrets replaces every built-in secret pattern match in free-form text (stderr lines, error strings). It uses the same engine and the same single-scan-per-pattern span logic as RedactJSON.

func RedactWithPatterns added in v0.2.0

func RedactWithPatterns(input string, patterns []*regexp.Regexp) string

RedactWithPatterns replaces every match of patterns in input. Prefer Redactor.RedactText in hot paths: this helper compiles a redactor for the pattern list on every call.

func ReturnBuffer added in v0.2.0

func ReturnBuffer(buf []byte)

func SafeCompile added in v0.6.0

func SafeCompile(pattern string) (*regexp.Regexp, error)

func SafeCompileMust added in v0.6.0

func SafeCompileMust(pattern string) *regexp.Regexp

func SetGlobalEmbedPool added in v0.8.0

func SetGlobalEmbedPool(p *embedder.Pool)

func SetupEmbedder added in v0.8.0

func SetupEmbedder(cfg embedder.Config, poolCfg embedder.PoolConfig) error

func StripComments added in v0.6.0

func StripComments(pattern string) string

func ValidatePattern added in v0.6.0

func ValidatePattern(pattern string) error

func ValidatePatterns added in v0.2.0

func ValidatePatterns() error

func ValidateReDoS added in v0.2.0

func ValidateReDoS(pattern string, timeout time.Duration) error

func VerifySidecarOutput added in v1.1.1

func VerifySidecarOutput(orig, out []byte) error

VerifySidecarOutput returns an error describing the first difference that is not a redaction of orig.

func WalkJSONObjectMembers added in v1.1.1

func WalkJSONObjectMembers(data []byte, fn func(key []byte, start, end int)) bool

WalkJSONObjectMembers calls fn for every member of the top-level object of data with the member's decoded key (only valid during the call) and the bounds of its raw value (data[start:end]). It reports false when data is not a valid JSON object.

func WalkJSONStrings added in v1.1.1

func WalkJSONStrings(data []byte, visit func(JSONString)) bool

WalkJSONStrings calls visit for every string literal of data (a complete JSON document), keys included, in document order. It reports false when data is not valid JSON (visit may already have been called for a prefix).

Types

type AlertManager added in v0.2.0

type AlertManager struct {
	// contains filtered or unexported fields
}

func NewAlertManager added in v0.2.0

func NewAlertManager(verbose bool) *AlertManager

func (*AlertManager) EmitSummary added in v0.2.0

func (am *AlertManager) EmitSummary(messageID string, method string)

func (*AlertManager) GetCounts added in v0.2.0

func (am *AlertManager) GetCounts() map[string]int

func (*AlertManager) RecordRedaction added in v0.2.0

func (am *AlertManager) RecordRedaction(event RedactionEvent)

func (*AlertManager) SetEnabled added in v0.2.0

func (am *AlertManager) SetEnabled(enabled bool)

func (*AlertManager) SetVerbose added in v0.2.0

func (am *AlertManager) SetVerbose(verbose bool)

type BoilerplateProcessor added in v0.2.0

type BoilerplateProcessor interface {
	Process(content []byte, language string) ([]byte, BoilerplateReport, error)
}

type BoilerplatePruner added in v0.2.0

type BoilerplatePruner struct {
	// contains filtered or unexported fields
}

func NewBoilerplatePruner added in v0.2.0

func NewBoilerplatePruner(enabled, redactImports, redactLicenses bool, customPatterns []PatternDef) *BoilerplatePruner

func (*BoilerplatePruner) Process added in v0.2.0

func (p *BoilerplatePruner) Process(content []byte, language string) ([]byte, BoilerplateReport, error)

func (*BoilerplatePruner) ProcessStream added in v0.2.0

func (p *BoilerplatePruner) ProcessStream(reader io.Reader, writer io.Writer, language string) (BoilerplateReport, error)

type BoilerplateReport added in v0.2.0

type BoilerplateReport struct {
	ImportsRedacted  int
	LicensesRedacted int
	OriginalSize     int
	ProcessedSize    int
	TokenSavings     int
}

type Bouncer

type Bouncer struct{}

Bouncer is a token validation and secret detection service.

func New

func New() *Bouncer

New creates a new Bouncer instance.

func (*Bouncer) ExtractClaims

func (b *Bouncer) ExtractClaims(ctx context.Context, token string) (Claims, error)

ExtractClaims extracts claims from a validated token.

func (*Bouncer) Validate

func (b *Bouncer) Validate(ctx context.Context, token string) error

Validate checks if the provided token is valid.

type Claims

type Claims map[string]interface{}

Claims represents the claims extracted from a validated token.

type Config added in v0.2.0

type Config struct {
	// Enabled defaults to true when omitted; set `enabled: false` to turn the
	// regex redactor off explicitly.
	Enabled *bool `yaml:"enabled,omitempty"`
	// Patterns is the documented key for custom patterns; CustomPatterns is
	// accepted as an alias for older configs. Both lists are compiled.
	Patterns       []PatternDef `yaml:"patterns,omitempty"`
	CustomPatterns []PatternDef `yaml:"custom_patterns,omitempty"`
	// SidecarAlwaysCall opts in to the per-request sidecar LLM behavior
	// introduced (and then reverted) around #274. When false (the default),
	// the sidecar is consulted only when the regex layer matched zero
	// secrets, which keeps the per-request cost to one regex pass for the
	// common case.
	SidecarAlwaysCall *bool `yaml:"sidecar_always_call,omitempty"`
	// EntropyDetection enables the generic high-entropy detector (off by
	// default): long random-looking tokens next to a key-like word (key,
	// secret, token, password) are redacted even when no pattern
	// recognizes them. See RedactorOptions.Entropy.
	EntropyDetection *bool `yaml:"entropy_detection,omitempty"`
}

Config defines the bouncer configuration, including whether the bouncer is enabled and any custom regex patterns for secret detection.

func LoadConfig added in v0.2.0

func LoadConfig(r io.Reader) (*Config, error)

LoadConfig reads and parses a bouncer YAML configuration from the provided reader.

func LoadConfigFile added in v0.2.0

func LoadConfigFile(path string) (*Config, error)

LoadConfigFile reads and parses a bouncer YAML configuration from the given file path.

func (*Config) AllPatternDefs added in v0.9.2

func (c *Config) AllPatternDefs() []PatternDef

AllPatternDefs returns the documented and legacy custom pattern lists in a single slice (Patterns followed by CustomPatterns). Exported so external packages (e.g. migrate.Config.Validate) can walk the configured patterns without re-implementing the merge logic.

func (*Config) CompilePatterns added in v0.2.0

func (c *Config) CompilePatterns() (*LoadedPatterns, error)

CompilePatterns compiles built-in and custom patterns into a LoadedPatterns struct.

func (*Config) EntropyEnabled added in v1.1.1

func (c *Config) EntropyEnabled() bool

EntropyEnabled reports whether the high-entropy detector should run. Defaults to false.

func (*Config) IsEnabled added in v0.9.2

func (c *Config) IsEnabled() bool

IsEnabled reports whether the redactor should run. A nil Config or an omitted `enabled` key means enabled.

func (*Config) NewRedactor added in v1.1.1

func (c *Config) NewRedactor(alerts *AlertManager) *Redactor

NewRedactor builds the redactor this config describes: custom patterns followed by the built-ins, plus the options. It returns nil when redaction is disabled.

func (*Config) ShouldAlwaysCallSidecar added in v0.9.2

func (c *Config) ShouldAlwaysCallSidecar() bool

ShouldAlwaysCallSidecar reports whether the sidecar LLM must run on every request, even when the regex layer already matched a secret. Defaults to false (the regex-cleaned payload is forwarded without the LLM round-trip).

type EmbedOutcome added in v0.8.0

type EmbedOutcome struct {
	Request  EmbedRequest `json:"request"`
	Provider string       `json:"provider"`
	Model    string       `json:"model,omitempty"`
	Vector   []float32    `json:"vector,omitempty"`
	Err      string       `json:"error,omitempty"`
}

type EmbedRequest added in v0.8.0

type EmbedRequest struct {
	ToolName string
	Args     json.RawMessage
}

type JSONDecodedSpanMapper added in v1.1.1

type JSONDecodedSpanMapper struct {
	// contains filtered or unexported fields
}

JSONDecodedSpanMapper maps byte ranges of a decoded string back to the raw literal content it was decoded from.

func NewJSONDecodedSpanMapper added in v1.1.1

func NewJSONDecodedSpanMapper(raw []byte) *JSONDecodedSpanMapper

NewJSONDecodedSpanMapper builds the mapper for raw (a literal's content).

func (*JSONDecodedSpanMapper) Raw added in v1.1.1

func (m *JSONDecodedSpanMapper) Raw(ds, de int) (int, int)

Raw returns the raw range covering every escape that produced the decoded range [ds, de).

type JSONEdit added in v1.1.1

type JSONEdit struct {
	Start, End int
	Repl       []byte
}

JSONEdit replaces data[Start:End] with Repl.

type JSONPathElem added in v1.1.1

type JSONPathElem struct {
	Key   []byte
	Index int
}

JSONPathElem is one step of the path to a JSON value: an object member (Key set, Index -1) or an array element (Key nil, Index >= 0). Key is the decoded member name; it aliases the walker's buffers and is only valid during the visit.

type JSONString added in v1.1.1

type JSONString struct {
	// Path leads from the root to the value (for an object key: to the
	// member the key names, so the key itself is Path[len(Path)-1].Key).
	// It aliases the walker's state and is only valid during the visit.
	Path []JSONPathElem
	// IsKey reports whether the literal is an object key.
	IsKey bool
	// Start and End bound the raw literal content in the document, quotes
	// excluded: the literal is data[Start-1:End+1].
	Start, End int
	// Escaped reports whether the raw content contains backslash escapes
	// (when false the raw content is the decoded value).
	Escaped bool
}

JSONString is one string literal of a document, as seen by a WalkJSONStrings visitor.

type LoadedPatterns added in v0.2.0

type LoadedPatterns struct {
	BuiltIn []SecretPattern
	Custom  []SecretPattern
	All     []*regexp.Regexp
}

LoadedPatterns holds the compiled built-in and custom regex patterns.

type PatternConfig added in v0.2.0

type PatternConfig struct {
	Name    string `yaml:"name"`
	Pattern string `yaml:"pattern"`
}

func (PatternConfig) Validate added in v0.2.0

func (pc PatternConfig) Validate() error

type PatternDef added in v0.2.0

type PatternDef struct {
	Name    string `yaml:"name"`
	Pattern string `yaml:"pattern"`
}

PatternDef defines a custom regex pattern for secret detection.

type RedactionEvent added in v0.2.0

type RedactionEvent struct {
	PatternName string
	Count       int
	Timestamp   time.Time
	MessageID   string
	Method      string
}

type RedactionMeta added in v0.2.0

type RedactionMeta struct {
	MessageID string
	Method    string
}

type Redactor added in v0.1.2

type Redactor struct {
	// contains filtered or unexported fields
}

func DefaultRedactor added in v1.1.1

func DefaultRedactor() *Redactor

DefaultRedactor returns a shared redactor built from the built-in patterns. It is what RedactSecrets and the log redaction helpers use.

func NewRedactor added in v0.1.2

func NewRedactor(patterns []*regexp.Regexp) *Redactor

NewRedactor builds a redactor for patterns. Built-in patterns keep their keyword prefilter and secret capture group; custom patterns are prefiltered on their literal prefix when they have one.

func NewRedactorFromLoaded added in v0.2.0

func NewRedactorFromLoaded(loaded *LoadedPatterns) *Redactor

func NewRedactorWithAlerts added in v0.2.0

func NewRedactorWithAlerts(patterns []*regexp.Regexp, alertManager *AlertManager) *Redactor

func NewRedactorWithOptions added in v1.1.1

func NewRedactorWithOptions(patterns []*regexp.Regexp, opts RedactorOptions) *Redactor

NewRedactorWithOptions builds a redactor for patterns with opts.

func (*Redactor) EntropyEnabled added in v1.1.1

func (r *Redactor) EntropyEnabled() bool

EntropyEnabled reports whether the generic high-entropy detector is on.

func (*Redactor) Patterns added in v0.9.2

func (r *Redactor) Patterns() []*regexp.Regexp

Patterns returns the compiled patterns this redactor applies.

func (*Redactor) RedactBytes added in v1.1.1

func (r *Redactor) RedactBytes(data []byte) ([]byte, int)

RedactBytes is RedactText for byte slices; it returns data itself when nothing matched, and the number of replaced spans.

func (*Redactor) RedactJSON added in v0.1.2

func (r *Redactor) RedactJSON(data []byte) ([]byte, int, error)

RedactJSON redacts a JSON document losslessly: every byte is copied through unchanged except string literals (values or object keys) that contain a secret and the values of sensitive keys, so numbers, key order, whitespace and escaping survive byte for byte. Strings holding a JSON document (for example an MCP result's content[].text) are redacted recursively. See jsonredact.go for the details.

If the input is not valid JSON it falls back to a byte-level scan of the raw input rather than passing it through unchanged, so a malformed or truncated payload can never be used to smuggle a secret past the redactor. When nothing needs redacting the input slice itself is returned.

func (*Redactor) RedactPayload added in v1.1.1

func (r *Redactor) RedactPayload(data []byte) ([]byte, int)

RedactPayload is RedactJSON without logging, for callers that run while a log record is being formatted (see internal/logx).

func (*Redactor) RedactStream added in v0.1.2

func (r *Redactor) RedactStream(reader io.Reader, writer io.Writer, meta ...*RedactionMeta) error

RedactStream copies reader to writer, replacing secrets as they pass through. Input is accumulated before scanning and a tail of up to maxOverlap bytes after the last match is held back until more input (or EOF) arrives, so a secret split across arbitrary read boundaries — including very small reads from a pipe — is still redacted as a whole.

All per-request scratch buffers (carry, output, scan spans) come from package-level sync.Pools; the defer block returns each one with its backing array zeroed (where it holds sensitive bytes) before this function returns. See issue #277 for the allocation profile this is meant to flatten.

func (*Redactor) RedactText added in v1.1.1

func (r *Redactor) RedactText(s string) string

RedactText redacts free-form text (log lines, error strings): every pattern runs once and the matches are replaced in a single pass.

type RedactorOptions added in v1.1.1

type RedactorOptions struct {
	// Entropy enables the generic high-entropy detector (off by default):
	// a run of 20+ characters from [A-Za-z0-9+/=_-] with Shannon entropy
	// >= 4.0 bits per character is redacted when a key-like word (key,
	// secret, token, password) is within 20 characters of it, or when it
	// is the value of a JSON key containing such a word.
	Entropy bool
	// Alerts, when set, receives redaction events from RedactStream.
	Alerts *AlertManager
}

RedactorOptions tunes a Redactor beyond its pattern list.

type SecretPattern added in v0.2.0

type SecretPattern struct {
	Name         string
	Severity     Severity
	Pattern      *regexp.Regexp
	Keywords     []string
	KeywordsFold bool
	SecretGroup  int
	Example      string
	Description  string
}

SecretPattern is one built-in redaction rule.

Keywords is a prefilter: every match of Pattern must contain at least one of the keywords (compared ASCII case-insensitively when KeywordsFold is set). The redactor only runs Pattern over text that contains a keyword, which keeps the per-byte cost of dozens of patterns close to the cost of a single pass. A pattern with no keywords is run over every string.

SecretGroup, when non-zero, names the capture group that holds the secret itself: only that group is replaced, so the context that made the match recognizable (a URL scheme and host, an `Authorization: Basic` prefix, a variable name) stays readable.

func GetBuiltInPatterns added in v0.2.0

func GetBuiltInPatterns() []SecretPattern

func GetPatternByName added in v0.2.0

func GetPatternByName(name string) *SecretPattern

type Severity added in v1.1.1

type Severity string

Severity ranks how damaging a leaked secret of a given kind is. It is informational (shown by `bouncer list-patterns` and in the docs); every match is redacted regardless of severity.

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
)

type SidecarClient added in v0.8.0

type SidecarClient interface {
	Redact(ctx context.Context, content string) string
	FallbackCount() int64
	Provider() string
	Model() string
	Healthy(ctx context.Context) bool
}

type Snapshot added in v0.8.0

type Snapshot struct {
	ServerName         string
	Transport          string
	EstimatedTools     int
	NativeTokens       int
	LeanProxyTokens    int
	SavedTokens        int
	SavingsPercent     float64
	HasRegistryBudget  bool
	RegistryBudgetNote string
}

Snapshot describes the token impact of adding a server to a LeanProxy deployment. It is computed from a registry feed entry before the server is installed so the user can preview the cost.

func ComputeSnapshot added in v0.8.0

func ComputeSnapshot(name, transport string, estimatedTools int, tokensPerTurn int64) Snapshot

ComputeSnapshot returns a token-cost preview for the given server definition.

The estimate is derived from the entry's declared tool count when available (TokensPerTurn is treated as a per-turn override), otherwise from a default heuristic. The LeanProxy cost assumes a single gateway schema (invoke_tool + list_tools) regardless of how many real tools the server exposes.

The returned Snapshot is safe for direct fmt.Stringer-style printing via FormatSnapshot.

type StreamingRedactor added in v0.2.0

type StreamingRedactor struct {
	// contains filtered or unexported fields
}

StreamingRedactor is a thin wrapper kept for API compatibility. All streaming redaction is implemented by Redactor.RedactStream, which carries state across read boundaries; this type used to redact each read independently and leaked any secret that straddled a boundary.

func NewStreamingRedactor added in v0.2.0

func NewStreamingRedactor(patterns []*regexp.Regexp) *StreamingRedactor

func NewStreamingRedactorWithAlerts added in v0.2.0

func NewStreamingRedactorWithAlerts(patterns []*regexp.Regexp, am *AlertManager) *StreamingRedactor

func (*StreamingRedactor) RedactStream added in v0.2.0

func (sr *StreamingRedactor) RedactStream(r io.Reader, w io.Writer, meta ...*RedactionMeta) error

func (*StreamingRedactor) RedactToWriter added in v0.2.0

func (sr *StreamingRedactor) RedactToWriter(r io.Reader, w io.Writer) error

RedactToWriter is an alias for RedactStream kept for backwards compatibility with callers that pre-date the RedactStream rename. Both methods share the same code path — fixing one fixes both — so any future change to streaming redaction must update the single implementation in Redactor.RedactStream. See issue #277 for the rationale.

type TokenValidator

type TokenValidator interface {
	Validate(ctx context.Context, token string) error
	ExtractClaims(ctx context.Context, token string) (Claims, error)
}

TokenValidator validates tokens and extracts claims from them.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL