security

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2026 License: MIT Imports: 10 Imported by: 0

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

View Source
const (
	// MaxDetectionsPerScan limits the number of detections per scan
	MaxDetectionsPerScan = 50
)

Variables

View Source
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

func ExpandPath(path string) string

ExpandPath expands environment variables and home directory in a path Supports: ~, $HOME, %USERPROFILE%, %APPDATA%, %LOCALAPPDATA%, %SYSTEMROOT%

func ExtractCardNumbers

func ExtractCardNumbers(text string) []string

ExtractCardNumbers finds potential card numbers in text and validates them Returns only Luhn-valid card numbers

func ExtractPaths

func ExtractPaths(content string) []string

ExtractPaths extracts potential file paths from content

func FindHighEntropyStrings

func FindHighEntropyStrings(content string, threshold float64, maxMatches int) []string

FindHighEntropyStrings finds strings with entropy above the threshold

func GetCardType

func GetCardType(number string) string

GetCardType returns the card type based on the number prefix

func GetCurrentPlatform

func GetCurrentPlatform() string

GetCurrentPlatform returns the current OS identifier

func IsHighEntropy

func IsHighEntropy(s string, threshold float64) bool

IsHighEntropy checks if a string has entropy above the threshold

func IsPlatformMatch

func IsPlatformMatch(platform string) bool

IsPlatformMatch checks if a platform specifier matches the current OS Supports: "all", "linux", "darwin", "windows"

func IsTestCard

func IsTestCard(number string) bool

IsTestCard checks if a card number is a known test card

func LuhnValid

func LuhnValid(number string) bool

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 MatchesPathPattern

func MatchesPathPattern(content, pattern string) bool

MatchesPathPattern checks if the content contains a path matching the pattern Uses glob-style matching

func NormalizeCardNumber

func NormalizeCardNumber(number string) string

NormalizeCardNumber removes all non-digit characters from a card number

func NormalizePath

func NormalizePath(path string) string

NormalizePath normalizes a path for the current platform - Handles forward/backward slashes - Expands environment variables - Normalizes case on Windows

func ShannonEntropy

func ShannonEntropy(s string) float64

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)

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) ReloadConfig

func (d *Detector) ReloadConfig(cfg *config.SensitiveDataDetectionConfig)

ReloadConfig reloads the detector configuration

func (*Detector) Scan

func (d *Detector) Scan(arguments, response string) *Result

Scan checks data for sensitive information

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

func (p *Pattern) IsKnownExample(match string) bool

IsKnownExample checks if a match is a known test/example value

func (*Pattern) IsValid

func (p *Pattern) IsValid(match string) bool

IsValid checks if a match passes additional validation (e.g., Luhn for credit cards)

func (*Pattern) Match

func (p *Pattern) Match(content string) []string

Match checks if the content matches this pattern and returns all matches

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 NewResult

func NewResult() *Result

NewResult creates a new empty Result

func (*Result) AddDetection

func (r *Result) AddDetection(d Detection)

AddDetection adds a detection to the result, avoiding duplicates

func (*Result) DetectionTypes

func (r *Result) DetectionTypes() []string

DetectionTypes returns a unique list of detection types found

func (*Result) MaxSeverity

func (r *Result) MaxSeverity() string

MaxSeverity returns the highest severity level in the result

type Severity

type Severity string

Severity represents the risk level of a detection

const (
	SeverityCritical Severity = "critical" // Private keys, cloud credentials
	SeverityHigh     Severity = "high"     // API tokens, database credentials
	SeverityMedium   Severity = "medium"   // Credit cards, high entropy strings
	SeverityLow      Severity = "low"      // Custom patterns, keywords
)

Directories

Path Synopsis
Package patterns provides sensitive data detection patterns for various credential types.
Package patterns provides sensitive data detection patterns for various credential types.

Jump to

Keyboard shortcuts

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