sanitize

package
v0.4.25 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Redact functions mask a known secret value for safe display in logs. Unlike the Sanitize* functions (which scan arbitrary strings for secret patterns), Redact* functions operate on a value that is already known to be sensitive and truncate or strip it so only a safe hint remains.

Package sanitize provides utilities for redacting sensitive information from logs.

This package offers two complementary approaches to secret sanitization, split across two files for cohesion:

  1. sanitize.go — Pattern-based detection: SanitizeString() and SanitizeJSON() use regex patterns to identify and redact secrets like API keys, tokens, and passwords from arbitrary strings/JSON.

  2. redact.go — Value masking: RedactSecret(), RedactSecretMap(), and RedactURL() mask a known-sensitive value for display, showing only a short safe hint.

Usage Guidelines:

  • Use RedactSecret()/RedactSecretMap() for auth headers and environment variables where you want to preserve a hint of the value for debugging.

  • Use SanitizeString()/SanitizeJSON() for full payload sanitization where secrets may appear in various formats throughout the data.

Example:

// For auth headers
log.Printf("Auth: %s", sanitize.RedactSecret(authHeader)) // "ghp_..." instead of full token

// For environment variables
log.Printf("Env: %v", sanitize.RedactSecretMap(envVars))

// For JSON payloads
sanitized := sanitize.SanitizeJSON(payload) // Replaces detected secrets with [REDACTED]

Index

Constants

View Source
const EnvRawPayloadLogs = "MCP_GATEWAY_UNSAFE_RAW_ENCLAVE_PAYLOAD_LOGS"

EnvRawPayloadLogs is the privileged opt-in that restores raw payload logging for enclave-scoped sessions. It exists for local debugging only; enabling it in a workflow republishes enclave payloads into exported artifacts.

Variables

View Source
var SecretPatterns = []*regexp.Regexp{
	regexp.MustCompile(`(?i)(token|key|secret|password|auth)[=:]\s*[^\s]{8,}`),
	regexp.MustCompile(`ghp_[a-zA-Z0-9]{36,}`),
	regexp.MustCompile(`github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}`),
	regexp.MustCompile(`(?i)bearer\s+[a-zA-Z0-9\-._~+/]+=*`),
	regexp.MustCompile(`(?i)authorization:\s*[a-zA-Z0-9\-._~+/]+=*`),
	regexp.MustCompile(`[a-f0-9]{32,}`),
	regexp.MustCompile(`(?i)(apikey|api_key|access_key)[=:]\s*[^\s]{8,}`),
	regexp.MustCompile(`(?i)(client_secret|client_id)[=:]\s*[^\s]{8,}`),
	regexp.MustCompile(`[a-zA-Z0-9_-]{20,}\.eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+`),

	regexp.MustCompile(`(?i)"(token|password|passwd|pwd|apikey|api_key|api-key|secret|client_secret|api_secret|authorization|auth|key|private_key|public_key|credentials|credential|access_token|refresh_token|bearer_token)"\s*:\s*"[^"]{1,}"`),
}

SecretPatterns contains regex patterns for detecting potential secrets

Functions

func EnablePayloadRedaction added in v0.4.23

func EnablePayloadRedaction()

EnablePayloadRedaction turns on process-wide redaction of MCP request and response payloads in every exported log sink. It is called during startup for the enclave and delegation profiles and is safe for concurrent use.

func EnablePrivateSelectorRedaction added in v0.4.17

func EnablePrivateSelectorRedaction()

EnablePrivateSelectorRedaction turns on process-wide redaction of private repository selectors, request paths, and runtime delegation identifiers in every sanitized log sink. It is called once during proxy startup for the enclave and delegation profiles and is safe for concurrent use.

func KeyedDigest added in v0.4.23

func KeyedDigest(value string) string

KeyedDigest returns a stable, non-reversible, per-process-keyed token for a value that must not be persisted in an exported log. Empty values render as "(none)". Tokens are comparable within a single process run and carry no information to a reader of the resulting artifact.

func MarshalAndSanitize

func MarshalAndSanitize(value any) string

MarshalAndSanitize marshals value to JSON and sanitizes the result to redact secrets. If marshaling fails, it returns a sanitized empty string rather than surfacing a logging-only error — callers should use this only in best-effort logging contexts.

func PayloadDigest added in v0.4.23

func PayloadDigest(payload []byte) string

PayloadDigest returns a stable, non-reversible digest of payload suitable for correlating identical payloads across log lines within one process run.

func PayloadRedactionEnabled added in v0.4.23

func PayloadRedactionEnabled() bool

PayloadRedactionEnabled reports whether process-wide payload redaction is active. The privileged raw-payload opt-in disables it.

func PrivateSelectorRedactionEnabled added in v0.4.17

func PrivateSelectorRedactionEnabled() bool

PrivateSelectorRedactionEnabled reports whether private-selector redaction is active for this process.

func RawPayloadLogsAllowed added in v0.4.23

func RawPayloadLogsAllowed() bool

RawPayloadLogsAllowed reports whether the privileged raw-payload opt-in is set for this process. Callers use it to warn that enclave payloads will be written to exported artifacts.

func RedactErrorForLog added in v0.4.23

func RedactErrorForLog(err error) string

RedactErrorForLog reduces an error to a coarse category plus a stable digest. Backend errors frequently embed response bodies, so the message itself cannot be persisted for enclave-scoped traffic.

func RedactPrivateSelectors added in v0.4.17

func RedactPrivateSelectors(message string) string

RedactPrivateSelectors rewrites every private repository selector, repository API path, and runtime delegation identifier in message with a stable, non-reversible hash. It always redacts, regardless of the process-wide mode, so callers that know a value is sensitive can use it directly.

func RedactPrivateSelectorsIfEnabled added in v0.4.17

func RedactPrivateSelectorsIfEnabled(message string) string

RedactPrivateSelectorsIfEnabled applies RedactPrivateSelectors only when the process-wide mode is active. Non-enclave, non-delegation deployments keep their existing, fully readable diagnostics.

func RedactSecret added in v0.4.2

func RedactSecret(input string) string

RedactSecret returns a sanitized version of the input string for safe logging. It shows only the first 4 characters followed by "..." to prevent exposing sensitive data. For strings with 4 or fewer characters, it returns only "...". For empty strings, it returns an empty string.

func RedactSecretMap added in v0.4.2

func RedactSecretMap(env map[string]string) map[string]string

RedactSecretMap returns a sanitized version of environment variables where each value is truncated to first 4 characters followed by "..." This prevents sensitive information like API keys from being logged in full.

func RedactURL

func RedactURL(rawURL string) string

RedactURL returns a safe-to-log version of a URL by retaining only the scheme, host, and path. Userinfo (credentials), query parameters, and fragments are removed to prevent accidental leakage of secrets (e.g. api_key=..., token=...). If the input cannot be parsed as a URL, the literal string "<unparseable-url>" is returned instead so callers never log raw unverified input.

func RedactedPayloadJSON added in v0.4.23

func RedactedPayloadJSON(payload []byte) json.RawMessage

RedactedPayloadJSON returns the metadata-only JSON document written in place of an enclave payload in the JSONL log.

func RedactedPayloadText added in v0.4.23

func RedactedPayloadText(payload []byte) string

RedactedPayloadText returns the metadata-only rendering of payload used by the text and markdown log sinks.

func SanitizeArgs

func SanitizeArgs(args []string) []string

SanitizeArgs returns a sanitized version of command arguments for safe logging. It specifically handles Docker-style environment variable arguments (-e VAR=VALUE) by truncating ALL values to prevent exposing sensitive data like API tokens. This approach prioritizes security over debugging convenience - we truncate all environment variable values rather than trying to selectively identify secrets. Other arguments are passed through unchanged.

func SanitizeJSON

func SanitizeJSON(payloadBytes []byte) json.RawMessage

SanitizeJSON sanitizes a JSON payload by applying regex patterns to the entire string It takes raw bytes, applies regex sanitization in one pass, and returns sanitized bytes

func SanitizeJSONFromString added in v0.4.2

func SanitizeJSONFromString(sanitized string) json.RawMessage

SanitizeJSONFromString compacts an already-sanitized JSON string into a json.RawMessage. It skips the regex sanitization pass — callers that have already called SanitizeString on the payload string can use this to avoid running the 10 compiled regex patterns a second time.

func SanitizeString

func SanitizeString(message string) string

SanitizeString replaces potential secrets in a string with [REDACTED]. When private-selector redaction is enabled (enclave and delegation proxy profiles), repository selectors, repository API paths, and runtime delegation identifiers are additionally replaced with stable hashes.

func SetPayloadRedaction added in v0.4.23

func SetPayloadRedaction(enabled bool)

SetPayloadRedaction sets the process-wide payload redaction mode explicitly. It exists so tests can restore the previous mode; production code should call EnablePayloadRedaction.

func SetPrivateSelectorRedaction added in v0.4.17

func SetPrivateSelectorRedaction(enabled bool)

SetPrivateSelectorRedaction sets the redaction mode explicitly. It exists so tests can restore the previous mode; production code should call EnablePrivateSelectorRedaction.

func SetRawPayloadLogsAllowed added in v0.4.23

func SetRawPayloadLogsAllowed(allowed bool)

SetRawPayloadLogsAllowed overrides the privileged raw-payload opt-in. It exists so tests can exercise both modes; production code resolves the value from the environment.

func ShouldRedactPayload added in v0.4.23

func ShouldRedactPayload(enclaveSession bool) bool

ShouldRedactPayload reports whether a payload must be reduced to metadata before it is written to any log sink. enclaveSession carries the per-request enclave provenance marker, so a single enclave-scoped call is redacted even when the process default is off.

Types

This section is empty.

Jump to

Keyboard shortcuts

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