Documentation
¶
Overview ¶
Package security provides sensitive data detection for MCP tool calls. It scans tool call arguments and responses for secrets, credentials, sensitive file paths, and other potentially exposed data.
Index ¶
- Constants
- Variables
- func ExpandPath(path string) string
- func ExtractCardNumbers(text string) []string
- func ExtractPaths(content string) []string
- func FindHighEntropyStrings(content string, threshold float64, maxMatches int) []string
- func GetCardType(number string) string
- func GetCurrentPlatform() string
- func IsHighEntropy(s string, threshold float64) bool
- func IsPlatformMatch(platform string) bool
- func IsTestCard(number string) bool
- func LuhnValid(number string) bool
- func MaskMarkers() []string
- func MaskValue(value string) string
- func MatchesPathPattern(content, pattern string) bool
- func NormalizeCardNumber(number string) string
- func NormalizePath(path string) string
- func ShannonEntropy(s string) float64
- func SpotlightUntrusted(text, server, tool string) string
- func StripControlSequences(text string, classes map[string]bool) (out string, stripped []string)
- func StripInternalArgs(args map[string]interface{}) map[string]interface{}
- type Category
- type Detection
- type Detector
- func (d *Detector) MaskArguments(args map[string]interface{}) map[string]interface{}
- func (d *Detector) MaskJSON(value interface{}) interface{}
- func (d *Detector) MaskText(text string) (masked string, changed bool)
- func (d *Detector) Redact(content string) (redacted string, detections []Detection)
- func (d *Detector) ReloadConfig(cfg *config.SensitiveDataDetectionConfig)
- func (d *Detector) Scan(arguments, response string) *Result
- type FilePathPattern
- type Pattern
- type PatternBuilder
- func (b *PatternBuilder) Build() *Pattern
- func (b *PatternBuilder) WithCategory(cat Category) *PatternBuilder
- func (b *PatternBuilder) WithDescription(desc string) *PatternBuilder
- func (b *PatternBuilder) WithExamples(examples ...string) *PatternBuilder
- func (b *PatternBuilder) WithKeywords(keywords ...string) *PatternBuilder
- func (b *PatternBuilder) WithRegex(pattern string) *PatternBuilder
- func (b *PatternBuilder) WithSeverity(sev Severity) *PatternBuilder
- func (b *PatternBuilder) WithValidator(fn func(string) bool) *PatternBuilder
- type Result
- type Severity
Constants ¶
const (
// MaxDetectionsPerScan limits the number of detections per scan
MaxDetectionsPerScan = 50
)
Variables ¶
var KnownTestCards = map[string]string{
"4111111111111111": "visa_test",
"4242424242424242": "stripe_visa_test",
"5555555555554444": "mastercard_test",
"378282246310005": "amex_test",
"6011111111111117": "discover_test",
"3566002020360505": "jcb_test",
}
KnownTestCards contains well-known test card numbers used in development
Functions ¶
func ExpandPath ¶
ExpandPath expands environment variables and home directory in a path Supports: ~, $HOME, %USERPROFILE%, %APPDATA%, %LOCALAPPDATA%, %SYSTEMROOT%
func ExtractCardNumbers ¶
ExtractCardNumbers finds potential card numbers in text and validates them Returns only Luhn-valid card numbers
func ExtractPaths ¶
ExtractPaths extracts potential file paths from content
func FindHighEntropyStrings ¶
FindHighEntropyStrings finds strings with entropy above the threshold
func GetCardType ¶
GetCardType returns the card type based on the number prefix
func GetCurrentPlatform ¶
func GetCurrentPlatform() string
GetCurrentPlatform returns the current OS identifier
func IsHighEntropy ¶
IsHighEntropy checks if a string has entropy above the threshold
func IsPlatformMatch ¶
IsPlatformMatch checks if a platform specifier matches the current OS Supports: "all", "linux", "darwin", "windows"
func IsTestCard ¶
IsTestCard checks if a card number is a known test card
func LuhnValid ¶
LuhnValid validates a credit card number using the Luhn algorithm. The Luhn algorithm is used to validate credit card numbers and other identification numbers.
It accepts card numbers with various separators (spaces, dashes) which are stripped before validation. Valid card numbers are typically 13-19 digits.
func MaskMarkers ¶ added in v0.64.0
func MaskMarkers() []string
MaskMarkers are the substrings every MaskValue rendering carries: a value long enough to keep a prefix ends in maskedSuffix, a shorter one collapses to maskedWhole.
They are exported because the write doors have to RECOGNISE this package's renderings — internal/oauth's fail-closed net refuses a client that echoes one back, and it must derive the substrings it looks for from the constants the renderer is built from rather than keep its own copy beside them (issue #1148, round 7 finding 1).
func MaskValue ¶ added in v0.61.0
MaskValue renders a detected secret as a recognisable but unusable preview: the first four runes, then an elision. `AKIAIOSFODNN7EXAMPLE` becomes `AKIA…****`.
Values of four runes or fewer keep no prefix at all — a four-character secret is entirely prefix, so showing it would defeat the mask.
func MatchesPathPattern ¶
MatchesPathPattern checks if the content contains a path matching the pattern Uses glob-style matching
func NormalizeCardNumber ¶
NormalizeCardNumber removes all non-digit characters from a card number
func NormalizePath ¶
NormalizePath normalizes a path for the current platform - Handles forward/backward slashes - Expands environment variables - Normalizes case on Windows
func ShannonEntropy ¶
ShannonEntropy calculates the Shannon entropy of a string. Higher entropy (> 4.5) indicates more randomness, suggesting a potential secret.
Entropy ranges: - < 3.0: Low entropy (natural language, repeated chars) - 3.0-4.0: Medium entropy (encoded data) - 4.0-4.5: High entropy (possibly a secret) - > 4.5: Very high entropy (likely a random secret)
func SpotlightUntrusted ¶ added in v0.34.0
SpotlightUntrusted wraps untrusted upstream tool output in named guillemet fences so downstream LLMs can visually distinguish proxied content from trusted instructions (Spec 054 Track B, FR-B1/FR-B2).
Any guillemet characters already present in text are HTML-escaped before wrapping so the content cannot spoof or break out of the delimiter (FR-B2).
An empty text is a no-op and returns "".
func StripControlSequences ¶ added in v0.34.0
StripControlSequences removes hostile/invisible control sequences from text on a per-class basis. Only classes whose map value is true are applied.
Supported class keys:
- "ansi": ANSI CSI and OSC escape sequences
- "c0c1": C0 (U+0000–U+001F, except \t \n \r) and C1 (U+0080–U+009F)
- "zero_width": U+200B, U+200C, U+200D, U+2060, U+FEFF
- "bidi": U+202A–U+202E and U+2066–U+2069
The returned stripped slice contains the (sorted) names of the classes that actually removed at least one character, for audit logging.
func StripInternalArgs ¶ added in v0.61.0
StripInternalArgs returns a copy of a tool call's arguments without the internal `_auth_*` keys. Returns the input untouched when there are none, so the common case allocates nothing.
Types ¶
type Category ¶
type Category string
Category groups related detection patterns
const ( CategoryCloudCredentials Category = "cloud_credentials" CategoryPrivateKey Category = "private_key" CategoryAPIToken Category = "api_token" CategoryAuthToken Category = "auth_token" CategorySensitiveFile Category = "sensitive_file" CategoryDatabaseCredential Category = "database_credential" CategoryHighEntropy Category = "high_entropy" CategoryCreditCard Category = "credit_card" CategoryCustom Category = "custom" )
type Detection ¶
type Detection struct {
// Type is the pattern name that matched (e.g., "aws_access_key")
Type string `json:"type"`
// Category is the pattern category (e.g., "cloud_credentials")
Category string `json:"category"`
// Severity is the risk level (critical, high, medium, low)
Severity string `json:"severity"`
// Location is the JSON path where the match was found (e.g., "arguments.api_key")
Location string `json:"location"`
// IsLikelyExample indicates if the match is a known test/example value
IsLikelyExample bool `json:"is_likely_example"`
}
Detection represents a single sensitive data finding
type Detector ¶
type Detector struct {
// contains filtered or unexported fields
}
Detector scans data for sensitive information
func NewDetector ¶
func NewDetector(cfg *config.SensitiveDataDetectionConfig) *Detector
NewDetector creates a new detector with the given configuration
func (*Detector) MaskArguments ¶ added in v0.61.0
MaskArguments returns a deep copy of a tool call's arguments with every string leaf run through MaskText. The input map belongs to the storage layer and is never modified.
func (*Detector) MaskJSON ¶ added in v0.61.0
func (d *Detector) MaskJSON(value interface{}) interface{}
MaskJSON returns a copy of an arbitrary decoded-JSON value with every string leaf run through MaskText. Use it for payload fields typed as `any` (a tool call's response, say); MaskArguments is the map-shaped convenience wrapper.
func (*Detector) MaskText ¶ added in v0.61.0
MaskText replaces every sensitive value the detector recognises inside text with its MaskValue preview, returning the masked text and whether anything was replaced.
It differs from Redact in two deliberate ways:
- The replacement keeps a short prefix instead of collapsing to `[REDACTED:<category>]`, so an operator reviewing an activity record can still tell WHICH key leaked (and therefore which one to rotate) without the record itself carrying the credential.
- Known example values (`AKIAIOSFODNN7EXAMPLE` and friends) are masked too. Redact leaves them alone because a redacted example is a useless placeholder; here the opposite holds — the drawer that renders this text ends up in screenshots and screen-shares, and "it only looked like a secret" is not a judgement the rendering surface gets to make.
Sensitive FILE PATHS are deliberately not masked: the path is what makes the finding actionable ("this call read ~/.aws/credentials") and the path itself is not the secret.
Unlike Scan, masking is NOT capped at MaxDetectionsPerScan. That cap bounds how many findings are worth reporting; here a cap would be a disclosure budget — the 51st secret in a payload would be served in cleartext. Work stays bounded instead by the fixed pattern set (each applied once, over de-duplicated matches) and by the payload sizes the activity log already caps.
Masking also ignores the `enabled` flag: a record that carries a detection verdict was flagged while detection was on, and turning the feature off later must not retroactively serve its credentials. Per-category switches are still honoured, so a category the operator excluded is neither flagged nor masked.
func (*Detector) Redact ¶ added in v0.34.0
Redact scans content for sensitive data and replaces every detected secret with a category-tagged placeholder (`[REDACTED:<category>]`), returning the sanitized string and the list of detections that drove each replacement (Spec 054 Track B). It is additive and does not alter Scan behavior.
Patterns are applied sequentially over the evolving string. Matches that fail validation or are known examples are left untouched. The number of detections is capped at MaxDetectionsPerScan.
func (*Detector) ReloadConfig ¶
func (d *Detector) ReloadConfig(cfg *config.SensitiveDataDetectionConfig)
ReloadConfig reloads the detector configuration
type FilePathPattern ¶
type FilePathPattern struct {
// Name identifies the pattern
Name string
// Category for grouping (e.g., "ssh", "cloud", "env")
Category string
// Severity for this path type
Severity Severity
// Patterns are glob-style patterns to match
// Supports: * (any chars), ? (single char), ** (recursive)
Patterns []string
// Platform specifies the OS: "all", "linux", "darwin", "windows"
Platform string
}
FilePathPattern defines a sensitive file path pattern
func GetFilePathPatterns ¶
func GetFilePathPatterns() []*FilePathPattern
GetFilePathPatterns returns the built-in sensitive file path patterns
type Pattern ¶
type Pattern struct {
// Name is the unique identifier for this pattern (e.g., "aws_access_key")
Name string
// Description is human-readable explanation
Description string
// Regex is the compiled pattern to match
Regex *regexp.Regexp
// Keywords are exact strings to match (alternative to Regex)
Keywords []string
// Category groups related patterns
Category Category
// Severity indicates the risk level
Severity Severity
// Validate is an optional function for additional validation (e.g., Luhn)
Validate func(match string) bool
// KnownExamples are test/example values to flag as is_likely_example
KnownExamples []string
// contains filtered or unexported fields
}
Pattern defines a pattern for detecting sensitive data
func (*Pattern) IsKnownExample ¶
IsKnownExample checks if a match is a known test/example value
type PatternBuilder ¶
type PatternBuilder struct {
// contains filtered or unexported fields
}
PatternBuilder provides a fluent API for building patterns
func NewPattern ¶
func NewPattern(name string) *PatternBuilder
NewPattern creates a new pattern builder
func (*PatternBuilder) Build ¶
func (b *PatternBuilder) Build() *Pattern
Build returns the constructed pattern
func (*PatternBuilder) WithCategory ¶
func (b *PatternBuilder) WithCategory(cat Category) *PatternBuilder
WithCategory sets the category
func (*PatternBuilder) WithDescription ¶
func (b *PatternBuilder) WithDescription(desc string) *PatternBuilder
WithDescription sets the description
func (*PatternBuilder) WithExamples ¶
func (b *PatternBuilder) WithExamples(examples ...string) *PatternBuilder
WithExamples sets known example values
func (*PatternBuilder) WithKeywords ¶
func (b *PatternBuilder) WithKeywords(keywords ...string) *PatternBuilder
WithKeywords sets the keywords to match
func (*PatternBuilder) WithRegex ¶
func (b *PatternBuilder) WithRegex(pattern string) *PatternBuilder
WithRegex sets the regex pattern
func (*PatternBuilder) WithSeverity ¶
func (b *PatternBuilder) WithSeverity(sev Severity) *PatternBuilder
WithSeverity sets the severity
func (*PatternBuilder) WithValidator ¶
func (b *PatternBuilder) WithValidator(fn func(string) bool) *PatternBuilder
WithValidator sets the validation function
type Result ¶
type Result struct {
// Detected is true if any sensitive data was found
Detected bool `json:"detected"`
// Detections is the list of findings
Detections []Detection `json:"detections,omitempty"`
// ScanDurationMs is the time taken to scan in milliseconds
ScanDurationMs int64 `json:"scan_duration_ms"`
// Truncated is true if payload exceeded max size and was truncated
Truncated bool `json:"truncated,omitempty"`
}
Result is the complete detection result stored in Activity metadata
func (*Result) AddDetection ¶
AddDetection adds a detection to the result, avoiding duplicates
func (*Result) DetectionTypes ¶
DetectionTypes returns a unique list of detection types found
func (*Result) MaxSeverity ¶
MaxSeverity returns the highest severity level in the result
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package detect implements the deterministic, offline MCP tool-scanner v2 (Spec 076).
|
Package detect implements the deterministic, offline MCP tool-scanner v2 (Spec 076). |
|
Package patterns provides sensitive data detection patterns for various credential types.
|
Package patterns provides sensitive data detection patterns for various credential types. |