sanitization

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AllowedFields = map[string]bool{
	"card_bin":   true,
	"card_brand": true,
	"card_type":  true,

	"transaction_id":   true,
	"authorization_id": true,
	"merchant_uid":     true,

	"mid":         true,
	"merchant_id": true,
	"acceptor_id": true,
	"tid":         true,
	"terminal_id": true,
}

AllowedFields are field names that should bypass sanitization.

View Source
var PaymentXMLPatterns = []XMLSanitizationPattern{
	{
		Name:        "AcctNum",
		Pattern:     regexp.MustCompile(`(?i)(<AcctNum>[^<]*</AcctNum>|&lt;AcctNum&gt;[^&]*&lt;/AcctNum&gt;)`),
		MaskingFunc: MaskCardNumber,
	},
	{
		Name:        "CardNum",
		Pattern:     regexp.MustCompile(`(?i)(<CardNum>[^<]*</CardNum>|&lt;CardNum&gt;[^&]*&lt;/CardNum&gt;)`),
		MaskingFunc: MaskCardNumber,
	},
	{
		Name:        "CardNumber",
		Pattern:     regexp.MustCompile(`(?i)(<CardNumber>[^<]*</CardNumber>|&lt;CardNumber&gt;[^&]*&lt;/CardNumber&gt;)`),
		MaskingFunc: MaskCardNumber,
	},
	{
		Name:        "TrackData",
		Pattern:     regexp.MustCompile(`(?i)(<TrackData>[^<]*</TrackData>|&lt;TrackData&gt;[^&]*&lt;/TrackData&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "CVV",
		Pattern:     regexp.MustCompile(`(?i)(<CVV>[^<]*</CVV>|&lt;CVV&gt;[^&]*&lt;/CVV&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "CVV2",
		Pattern:     regexp.MustCompile(`(?i)(<CVV2>[^<]*</CVV2>|&lt;CVV2&gt;[^&]*&lt;/CVV2&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "CVC",
		Pattern:     regexp.MustCompile(`(?i)(<CVC>[^<]*</CVC>|&lt;CVC&gt;[^&]*&lt;/CVC&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "ExpDate",
		Pattern:     regexp.MustCompile(`(?i)(<ExpDate>[^<]*</ExpDate>|&lt;ExpDate&gt;[^&]*&lt;/ExpDate&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "ExpiryDate",
		Pattern:     regexp.MustCompile(`(?i)(<ExpiryDate>[^<]*</ExpiryDate>|&lt;ExpiryDate&gt;[^&]*&lt;/ExpiryDate&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "Password",
		Pattern:     regexp.MustCompile(`(?i)(<Password>[^<]*</Password>|&lt;Password&gt;[^&]*&lt;/Password&gt;)`),
		MaskingFunc: MaskCompletelyFunc(redactedValue),
	},
	{
		Name:        "TransArmorToken",
		Pattern:     regexp.MustCompile(`(?i)(<TransArmorToken>[^<]*</TransArmorToken>|&lt;TransArmorToken&gt;[^&]*&lt;/TransArmorToken&gt;)`),
		MaskingFunc: MaskTokenLastFour,
	},
}

PaymentXMLPatterns contains pre-configured patterns for common payment processing XML elements.

It is designed for safe logging (masking/redaction), not for request validation.

View Source
var RapidConnectXMLPatterns = PaymentXMLPatterns

RapidConnectXMLPatterns is an alias for PaymentXMLPatterns for compatibility with existing codebases.

View Source
var SensitiveFields = map[string]SanitizationType{
	"cvv":           FullyRedact,
	"security_code": FullyRedact,
	"cvv2":          FullyRedact,
	"cvc":           FullyRedact,
	"cvc2":          FullyRedact,

	"cardholder":      FullyRedact,
	"cardholder_name": FullyRedact,

	"card_number": PartialMask,
	"number":      PartialMask,

	"pan_value":              PartialMask,
	"pan":                    PartialMask,
	"primary_account_number": PartialMask,

	"account_number": PartialMask,
	"ssn":            PartialMask,
	"tin":            PartialMask,
	"tax_id":         PartialMask,
	"ein":            PartialMask,

	"password":    FullyRedact,
	"secret":      FullyRedact,
	"private_key": FullyRedact,
	"secret_key":  FullyRedact,

	"access_token":         FullyRedact,
	"refresh_token":        FullyRedact,
	"id_token":             FullyRedact,
	"token":                FullyRedact,
	"client_secret":        FullyRedact,
	"api_key":              FullyRedact,
	"api_token":            FullyRedact,
	"api_key_id":           PartialMask,
	"authorization":        FullyRedact,
	"authorization_header": FullyRedact,
}

SensitiveFields defines fields that require explicit sanitization behavior.

This list is intentionally keyed by lowercased field name.

Functions

func MaskCardNumber

func MaskCardNumber(match string) string

MaskCardNumber shows BIN + last 4 digits of card numbers (PCI-friendly).

func MaskCompletelyFunc

func MaskCompletelyFunc(replacement string) func(string) string

MaskCompletelyFunc returns a function that replaces the inner text with a fixed replacement.

func MaskFirstLast added in v0.8.0

func MaskFirstLast(value string, prefixLen, suffixLen int) string

MaskFirstLast keeps the first prefixLen and last suffixLen characters and masks the middle. Behavior matches Lift's sanitization helpers.

func MaskFirstLast4 added in v0.8.0

func MaskFirstLast4(value string) string

MaskFirstLast4 keeps the first and last 4 characters and masks the middle.

func MaskTokenLastFour

func MaskTokenLastFour(match string) string

MaskTokenLastFour shows only the last 4 characters of tokens.

func NewPolicySanitizer added in v0.13.1

func NewPolicySanitizer(policy *Policy) (func(key string, value any) any, error)

NewPolicySanitizer returns a sanitizer function based on the provided policy.

When policy is nil, the default sanitizer (SanitizeFieldValue) is returned.

func SanitizeFieldValue

func SanitizeFieldValue(key string, value any) any

SanitizeFieldValue sanitizes a field value based on its key name.

This function is intentionally deterministic and safe-by-default for known sensitive keys.

func SanitizeJSON

func SanitizeJSON(jsonBytes []byte) string

SanitizeJSON recursively sanitizes JSON data for logging.

It returns a formatted JSON string with known sensitive fields masked/redacted while preserving structure.

func SanitizeJSONValue added in v0.13.0

func SanitizeJSONValue(jsonBytes []byte) any

SanitizeJSONValue returns a sanitized JSON structure suitable for structured logging.

Unlike SanitizeJSON, this function preserves JSON structure (map/slice) so JSON loggers (zap, pino, etc) will emit the value as nested JSON instead of an escaped string.

func SanitizeLogString

func SanitizeLogString(value string) string

SanitizeLogString removes control characters that could enable log forging.

func SanitizeXML

func SanitizeXML(xmlString string, patterns []XMLSanitizationPattern) string

SanitizeXML sanitizes XML content using configurable patterns.

It supports both regular XML (<AcctNum>...</AcctNum>) and HTML-escaped XML (&lt;AcctNum&gt;...&lt;/AcctNum&gt;).

func ScrubFreeText added in v0.14.0

func ScrubFreeText(value string) string

ScrubFreeText applies best-effort scrubbing to unstructured strings (for example, provider error messages).

It is intended as a complement to structured sanitization (SanitizeFieldValue / SanitizeJSONValue), since upstream errors are often plain text blobs.

Types

type Policy added in v0.13.1

type Policy struct {
	AllowedFields     []string     `json:"allowed_fields,omitempty" yaml:"allowed_fields,omitempty"`
	FullyRedactFields []string     `json:"fully_redact_fields,omitempty" yaml:"fully_redact_fields,omitempty"`
	PartialMaskFields []string     `json:"partial_mask_fields,omitempty" yaml:"partial_mask_fields,omitempty"`
	Rules             []PolicyRule `json:"rules,omitempty" yaml:"rules,omitempty"`
}

Policy allows services to override field sanitization behavior without providing custom code.

Rules are evaluated before the built-in AllowedFields/SensitiveFields defaults.

func PolicyFromEnv added in v0.14.0

func PolicyFromEnv(envVar string) (*Policy, error)

PolicyFromEnv loads a sanitization policy from an environment variable.

When the variable is unset or contains only whitespace, the returned policy is nil so callers can pass it directly into observability.LoggerConfig (nil means "use defaults").

The value can be JSON or YAML (using the same field names as the JSON policy schema).

func PolicyFromText added in v0.14.0

func PolicyFromText(text string) (*Policy, error)

PolicyFromText parses and validates a sanitization policy from a string.

The input can be JSON or YAML. Empty/whitespace-only values (and JSON "null") return (nil, nil).

type PolicyAction added in v0.13.1

type PolicyAction string
const (
	PolicyAllow       PolicyAction = "allow"
	PolicyFullyRedact PolicyAction = "fully_redact"
	PolicyPartialMask PolicyAction = "partial_mask"
)

type PolicyRule added in v0.13.1

type PolicyRule struct {
	// ParentKey scopes the rule to a single parent key. When empty, the rule applies globally.
	ParentKey string       `json:"parent_key,omitempty" yaml:"parent_key,omitempty"`
	Key       string       `json:"key" yaml:"key"`
	Action    PolicyAction `json:"action" yaml:"action"`
}

type RawJSON added in v0.13.0

type RawJSON []byte

RawJSON is a marker type for JSON payloads that should be sanitized and logged as structured JSON (object/array) rather than as an escaped string.

type SanitizationType

type SanitizationType int

SanitizationType defines how to sanitize a field.

const (
	FullyRedact SanitizationType = iota
	PartialMask
)

type XMLSanitizationPattern

type XMLSanitizationPattern struct {
	Pattern     *regexp.Regexp
	MaskingFunc func(match string) string
	Name        string
}

XMLSanitizationPattern defines a regex-based sanitization rule for XML elements.

Jump to

Keyboard shortcuts

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