util

package
v0.0.0-...-04323d9 Latest Latest
Warning

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

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

Documentation

Overview

Package util provides utility functions for Docker and other shared functionality.

Package util provides network and other utility functions.

Index

Constants

View Source
const RedactedString = "REDACTED"

RedactedString is the string used to replace sensitive data.

Summary: Constant string for redacted data.

View Source
const TrueStr = "true"

TrueStr is a string constant representing the boolean value true. It is used for consistent string comparisons and parsing of boolean-like strings.

Summary: Constant for "true" string.

Variables

View Source
var (
	FastJSON = jsoniter.Config{
		EscapeHTML:             true,
		SortMapKeys:            false,
		ValidateJsonRawMessage: true,
	}.Froze()
)
View Source
var (
	// IsDockerSocketAccessibleFunc is a variable to allow mocking in tests.
	// It checks if the Docker socket is accessible.
	// Summary: Defines IsDockerSocketAccessibleFunc.
	IsDockerSocketAccessibleFunc = isDockerSocketAccessibleDefault
)

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString converts a byte slice to a string without allocation. IMPORTANT: The byte slice must not be modified while the string is in use.

Summary: Zero-copy conversion from bytes to string.

Parameters:

  • b ([]byte): The byte slice to convert.

Returns:

  • string: The resulting string.

Side Effects:

  • None.

func CheckConnection

func CheckConnection(ctx context.Context, address string) error

CheckConnection verifies if a TCP connection can be established to the given address.

Summary: Verifies TCP connectivity to an address.

This is typically used for health checks or validating upstream service reachability. It uses SafeDialer to respect egress policies, but allows overriding via environment variables.

Parameters:

  • ctx (context.Context): The context for the connection attempt.
  • address (string): The target address (URL or host:port).

Returns:

  • (error): nil if the connection succeeded, or an error if it failed.

func CloseDockerClient

func CloseDockerClient()

CloseDockerClient closes the shared Docker client. Summary: Closes the shared Docker client. Side Effects: - Closes the Docker client connection.

Parameters:

  • None

Returns:

  • None

Errors:

  • None

Side Effects:

  • None

Summary: Executes CloseDockerClient operation.

Parameters:

  • TODO: Document parameters.

Returns:

  • TODO: Document returns.

Errors:

  • TODO: Document errors.

Side Effects:

  • None.

func ContextWithRemoteIP

func ContextWithRemoteIP(ctx context.Context, ip string) context.Context

ContextWithRemoteIP creates a new context containing the remote IP address.

Summary: Injects the remote IP into the context.

Parameters:

  • ctx: context.Context. The parent context.
  • ip: string. The remote IP address to store in the context.

Returns:

  • context.Context: A new context with the remote IP attached.

func EstimateJSONSize

func EstimateJSONSize(v interface{}) int

EstimateJSONSize estimates the size of the JSON representation of a value. It avoids allocating the full JSON string by traversing the structure recursively. It supports standard Go types and respects basic JSON encoding rules.

Parameters:

  • None

Returns:

  • None

Errors:

  • None

Side Effects:

  • None

Summary: Executes EstimateJSONSize operation.

Parameters:

  • TODO: Document parameters.

Returns:

  • TODO: Document returns.

Errors:

  • TODO: Document errors.

Side Effects:

  • None.

func ExtractIP

func ExtractIP(addr string) string

ExtractIP extracts and validates the IP address from a string.

Summary: Parses and sanitizes an IP address string.

It handles "host:port" formats, strips IPv6 brackets, and removes zone indices.

Parameters:

  • addr: string. The address string to parse (e.g., "192.168.1.1:80", "[::1]", "fe80::1%eth0").

Returns:

  • string: The cleaned IP address string, or an empty string if the address is invalid.

func FastMarshal

func FastMarshal(v interface{}) ([]byte, error)

FastMarshal performs a high-performance JSON marshal into a byte slice.

Summary: Marshals to a byte slice efficiently.

Parameters:

  • v (interface{}): The value to marshal.

Returns:

  • []byte: The marshaled byte slice.
  • error: An error if marshaling fails.

func FastMarshalToString

func FastMarshalToString(v interface{}) (string, error)

FastMarshalToString performs a high-performance JSON marshal into a string.

Summary: Marshals to a string efficiently.

Parameters:

  • v (interface{}): The value to marshal.

Returns:

  • string: The marshaled string.
  • error: An error if marshaling fails.

func GenerateUUID

func GenerateUUID() string

GenerateUUID creates a new random (version 4) UUID.

Summary: Generates a random UUID.

Parameters:

  • None.

Returns:

  • string: A string representation of the UUID (e.g., "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").

Side Effects:

  • Generates random data.

func GetClientIP

func GetClientIP(r *http.Request, trustProxy bool) string

GetClientIP extracts the client IP address from an HTTP request.

Summary: Determines the client's IP address.

Parameters:

  • r: *http.Request. The HTTP request to inspect.
  • trustProxy: bool. If true, trusts 'X-Real-IP' and 'X-Forwarded-For' headers. If false, only uses 'RemoteAddr'.

Returns:

  • string: The best-effort client IP address.

func GetDockerCommand

func GetDockerCommand() (string, []string)

GetDockerCommand returns the command and base arguments for running Docker. It checks the USE_SUDO_FOR_DOCKER environment variable to determine if "sudo" should be prepended to the command.

Summary: Retrieves the appropriate Docker command (with optional sudo).

Parameters:

  • None.

Returns:

  • string: The command to run (e.g., "docker" or "sudo").
  • []string: The arguments for the command (e.g., [] or ["docker"]).

Side Effects:

  • Reads environment variable USE_SUDO_FOR_DOCKER.

func HydrateSecretsInService

func HydrateSecretsInService(svc *configv1.UpstreamServiceConfig, secrets map[string]*configv1.SecretValue)

HydrateSecretsInService populates the service configuration with resolved secret values.

Summary: Populates service configuration with resolved secret values.

Parameters:

  • svc (*configv1.UpstreamServiceConfig): The upstream service configuration to hydrate secrets into.
  • secrets (map[string]*configv1.SecretValue): A map of resolved secret values.

func IsDockerSocketAccessible

func IsDockerSocketAccessible() bool

IsDockerSocketAccessible checks if the Docker daemon is accessible through the socket.

Summary: Checks if the Docker daemon is accessible.

Returns:

  • bool: True if the Docker daemon is accessible, false otherwise.

func IsEnvVarAllowed

func IsEnvVarAllowed(name string) bool

IsEnvVarAllowed checks if an environment variable is allowed to be accessed by the configuration system.

Summary: Validates if an environment variable is safe to expose to the configuration system.

Security Policy:

  1. Block `MCPANY_*` variables by default to prevent exfiltration of server secrets (like MCPANY_API_KEY, MCPANY_DB_DSN) via configuration injection.
  2. Allow explicitly whitelisted variables via `MCPANY_ALLOWED_ENV` (comma-separated).
  3. In Strict Mode (`MCPANY_STRICT_ENV_MODE=true`), block ALL variables unless whitelisted.

Parameters:

  • name: The name of the environment variable to check.

Returns:

  • bool: True if the environment variable is allowed, false otherwise.

func IsNil

func IsNil(i any) bool

IsNil checks if an interface value is nil or holds a nil pointer.

Summary: Checks if a value is nil or a nil interface.

Parameters:

  • i (any): The interface value to check.

Returns:

  • bool: True if the value is nil or a nil pointer, false otherwise.

Side Effects:

  • None.

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

IsPrivateIP checks if the IP address is private, link-local, or loopback.

Summary: Checks if an IP is internal/private.

This is a comprehensive check for any "internal" IP address that shouldn't be publicly routable.

Parameters:

  • ip: net.IP. The IP address to check.

Returns:

  • bool: True if the IP is private, link-local, or loopback.

func IsPrivateNetworkIP

func IsPrivateNetworkIP(ip net.IP) bool

IsPrivateNetworkIP checks if the IP address belongs to a private network.

Summary: Checks if an IP is a private network address.

This includes RFC1918 (Private IPv4), RFC4193 (Unique Local IPv6), and RFC6598 (CGNAT). It does NOT include loopback or link-local addresses.

Parameters:

  • ip: net.IP. The IP address to check.

Returns:

  • bool: True if the IP is a private network address.

func IsSensitiveKey

func IsSensitiveKey(key string) bool

IsSensitiveKey checks if a key name suggests it contains sensitive information.

Summary: Checks if a key name implies sensitive data.

Parameters:

  • key (string): The key name to check.

Returns:

  • bool: True if the key is considered sensitive, false otherwise.

func LevenshteinDistance

func LevenshteinDistance(s1, s2 string) int

LevenshteinDistance calculates the Levenshtein distance between two strings.

Summary: Calculates the Levenshtein edit distance.

It returns the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other.

Parameters:

  • s1: string. The first string.
  • s2: string. The second string.

Returns:

  • int: The Levenshtein distance.

func LevenshteinDistanceWithLimit

func LevenshteinDistanceWithLimit(s1, s2 string, limit int) int

LevenshteinDistanceWithLimit calculates the Levenshtein distance with an upper limit.

Summary: Calculates the Levenshtein edit distance with a limit.

If the distance is strictly greater than limit, it returns a value > limit (specifically limit + 1).

Parameters:

  • s1: string. The first string.
  • s2: string. The second string.
  • limit: int. The maximum distance to compute.

Returns:

  • int: The Levenshtein distance, or limit + 1 if it exceeds the limit.

func ListenWithRetry

func ListenWithRetry(ctx context.Context, network, address string) (net.Listener, error)

ListenWithRetry attempts to listen on the given address with retries to handle transient port conflicts.

Summary: Listens on an address with retry logic.

It is particularly useful for avoiding race conditions when binding to port 0 (dynamic allocation) in high-churn environments.

Parameters:

  • ctx (context.Context): The context for the listen operation.
  • network (string): The network type (e.g., "tcp").
  • address (string): The address to listen on.

Returns:

  • (net.Listener): The successfully bound listener.
  • (error): An error if binding fails after all retries.

func NewHTTPClientWithTLS

func NewHTTPClientWithTLS(tlsConfig *configv1.TLSConfig) (*http.Client, error)

NewHTTPClientWithTLS creates a new *http.Client configured with the specified TLS settings. It supports setting a custom CA certificate, a client certificate and key, the server name for SNI, and skipping verification.

It also configures the client with a SafeDialer to prevent SSRF attacks against cloud metadata services (LinkLocal addresses) and optionally private networks.

Parameters:

  • tlsConfig: The TLS settings to apply to the HTTP client's transport.

Returns:

  • *http.Client: A configured *http.Client.
  • error: An error if the TLS configuration is invalid or files cannot be read.

Summary: Initializes NewHTTPClientWithTLS operation.

Parameters:

  • TODO: Document parameters.

Returns:

  • TODO: Document returns.

Errors:

  • TODO: Document errors.

Side Effects:

  • None.

func NewSafeHTTPClient

func NewSafeHTTPClient() *http.Client

NewSafeHTTPClient creates a new HTTP client configured to prevent SSRF attacks.

Summary: Creates a secure HTTP client.

It uses a custom Transport backed by SafeDialer.

Configuration is loaded from environment variables:

  • MCPANY_DANGEROUS_ALLOW_LOCAL_IPS: Set to "true" to allow all local connections (loopback, private).
  • MCPANY_ALLOW_LOOPBACK_RESOURCES: Set to "true" to allow loopback connections.
  • MCPANY_ALLOW_PRIVATE_NETWORK_RESOURCES: Set to "true" to allow private network connections.

Returns:

  • (*http.Client): A configured HTTP client.

func ParseToolName

func ParseToolName(toolName string) (service, bareToolName string, err error)

ParseToolName deconstructs a fully qualified tool name into its service key and bare tool name components. It splits the name using the standard separator.

Summary: Parses a fully qualified tool name.

Parameters:

  • toolName (string): The fully qualified tool name to parse.

Returns:

  • service (string): The service key part.
  • bareToolName (string): The tool name part.
  • err (error): An error if parsing fails.

Side Effects:

  • None.

func RandomFloat64

func RandomFloat64() float64

RandomFloat64 returns a random float64 in [0.0, 1.0). It uses the global math/rand source.

Summary: Generates a random float.

Parameters:

  • None.

Returns:

  • float64: A random float64 value.

Side Effects:

  • Generates random data.

func ReadLastNLines

func ReadLastNLines(path string, n int) ([][]byte, error)

ReadLastNLines reads the last n lines from a file. It is optimized to read from the end of the file.

Summary: Reads the tail of a file.

Parameters:

  • path: string. The path to the file.
  • n: int. The number of lines to read.

Returns:

  • [][]byte: A slice of byte slices representing the lines.
  • error: An error if the file cannot be opened or read.

Throws/Errors:

  • Returns error if file open or seek fails.

Side Effects:

  • Opens and reads the specified file from the filesystem.

func RedactDSN

func RedactDSN(dsn string) string

RedactDSN redacts the password from a DSN string. Supported formats: postgres://user:password@host...

Summary: Redacts passwords from DSN strings.

Parameters:

  • dsn (string): The DSN string to redact.

Returns:

  • string: The redacted DSN string.

func RedactJSON

func RedactJSON(input []byte) []byte

RedactJSON parses a JSON byte slice and redacts sensitive keys. If the input is not valid JSON object or array, it returns the input as is.

Summary: Redacts sensitive keys in JSON data.

Parameters:

  • input ([]byte): The JSON input to redact.

Returns:

  • []byte: The redacted JSON output.

func RedactMap

func RedactMap(m map[string]interface{}) map[string]interface{}

RedactMap recursively redacts sensitive keys in a map.

Optimization: This function performs a copy-on-write. If no sensitive keys are found, it returns the original map (zero allocation). If sensitive keys are found, it returns a new map with redacted values (and copies other fields). Note: This aligns with RedactJSON behavior which returns original slice if clean.

Summary: Recursively redacts sensitive keys in a map.

Parameters:

  • m (map[string]interface{}): The map to redact.

Returns:

  • map[string]interface{}: The potentially redacted map.

func RedactSecrets

func RedactSecrets(text string, secrets []string) string

RedactSecrets replaces all occurrences of the given secrets in the text with [REDACTED].

Summary: Convenience function to redact secrets from text.

Parameters:

  • text (string): The text to redact.
  • secrets ([]string): A list of secret values to redact from the text.

Returns:

  • string: The redacted text.

func RemoteIPFromContext

func RemoteIPFromContext(ctx context.Context) (string, bool)

RemoteIPFromContext retrieves the remote IP address stored in the context.

Summary: Retrieves the remote IP from the context.

Parameters:

  • ctx: context.Context. The context to retrieve the IP from.

Returns:

  • string: The remote IP address.
  • bool: True if the IP was found, false otherwise.

func ReplaceURLPath

func ReplaceURLPath(urlPath string, params map[string]interface{}, noEscapeParams map[string]bool) string

ReplaceURLPath replaces placeholders in a URL path with values from a params map. It handles URL escaping of values unless specified otherwise.

Summary: Substitutes placeholders in a URL path.

Parameters:

  • urlPath (string): The URL path containing placeholders in the format "{{key}}".
  • params (map[string]interface{}): A map of keys to values to replace placeholders with.
  • noEscapeParams (map[string]bool): A map of keys that should NOT be URL escaped.

Returns:

  • string: The URL path with placeholders replaced.

Side Effects:

  • None.

func ReplaceURLQuery

func ReplaceURLQuery(urlQuery string, params map[string]interface{}, noEscapeParams map[string]bool) string

ReplaceURLQuery replaces placeholders in a URL query string with values from a params map. It handles URL query escaping of values unless specified otherwise.

Summary: Substitutes placeholders in a URL query string.

Parameters:

  • urlQuery (string): The URL query string containing placeholders in the format "{{key}}".
  • params (map[string]interface{}): A map of keys to values to replace placeholders with.
  • noEscapeParams (map[string]bool): A map of keys that should NOT be URL escaped.

Returns:

  • string: The URL query string with placeholders replaced.

Side Effects:

  • None.

func ResolveSecret

func ResolveSecret(ctx context.Context, secret *configv1.SecretValue) (string, error)

ResolveSecret resolves a SecretValue configuration object into a concrete string value. It handles various secret types including plain text, environment variables, file paths, remote URLs, Vault, and AWS Secrets Manager.

Summary: Resolves a secret configuration into a string value.

Parameters:

  • ctx (context.Context): The context for the secret resolution.
  • secret (*configv1.SecretValue): The configuration object to resolve.

Returns:

  • string: The resolved secret string.
  • error: An error if resolution fails.

func ResolveSecretMap

func ResolveSecretMap(ctx context.Context, secretMap map[string]*configv1.SecretValue, plainMap map[string]string) (map[string]string, error)

ResolveSecretMap resolves a map of SecretValue objects and merges them with a map of plain strings. If a key exists in both maps, the value from the secretMap (once resolved) takes precedence.

Summary: Resolves a map of secrets and merges with plain values.

Parameters:

  • ctx (context.Context): The context for the secret resolution.
  • secretMap (map[string]*configv1.SecretValue): A map of keys to SecretValue objects.
  • plainMap (map[string]string): A map of keys to plain string values.

Returns:

  • map[string]string: A single map containing all keys with their resolved string values.
  • error: An error if any secret resolution fails.

func SafeDialContext

func SafeDialContext(ctx context.Context, network, addr string) (net.Conn, error)

SafeDialContext creates a connection to the given address with strict SSRF protection.

Summary: Dials an address with default security protections.

It is a convenience wrapper around SafeDialer with default settings (blocking private/loopback).

Parameters:

  • ctx (context.Context): The context for the dial operation.
  • network (string): The network type.
  • addr (string): The address to connect to (host:port).

Returns:

  • (net.Conn): The established connection.
  • (error): An error if the connection is blocked by policy or fails.

func SanitizeAuthentication

func SanitizeAuthentication(a *configv1.Authentication) *configv1.Authentication

SanitizeAuthentication sanitizes the authentication object. It modifies the object in place (assumes it's already a clone).

Summary: Sanitizes an authentication object.

Parameters:

  • a (*configv1.Authentication): The authentication object to sanitize.

Returns:

  • *configv1.Authentication: The sanitized authentication object, or nil if input is nil.

func SanitizeCredential

func SanitizeCredential(c *configv1.Credential) *configv1.Credential

SanitizeCredential creates a sanitized copy of the credential object with sensitive data redacted.

Summary: Sanitizes a credential object.

Parameters:

  • c (*configv1.Credential): The credential object to sanitize.

Returns:

  • *configv1.Credential: A sanitized copy of the credential object, or nil if input is nil.

func SanitizeFilename

func SanitizeFilename(filename string) string

SanitizeFilename cleans a filename to ensure it is safe to use. It removes any directory components, null bytes, and restricts characters to alphanumeric, dots, dashes, and underscores.

Summary: Sanitizes a filename.

Parameters:

  • filename (string): The filename to sanitize.

Returns:

  • string: The sanitized filename.

Side Effects:

  • None.

func SanitizeID

func SanitizeID(ids []string, alwaysAppendHash bool, maxSanitizedPrefixLength, reqHashLength int) (string, error)

SanitizeID sanitizes a slice of strings to form a valid ID. It performs the following operations:

  1. Joining the strings with a "." separator.

  2. Removing any characters that are not allowed (alphanumerics, "_", "-"). Allowed characters are: `[a-zA-Z0-9_-]`.

  3. Truncating the result to the specified maximum length.

  4. Optionally, appending a hash of the original string to ensure uniqueness, especially when truncation occurs or when illegal characters are present.

After sanitizing each string individually, it joins them with a "." separator to form the final identifier.

Summary: Creates a sanitized, unique identifier from a list of string parts.

Parameters:

  • ids ([]string): A slice of strings to be sanitized and joined.
  • alwaysAppendHash (bool): If true, forces a hash to be appended.
  • maxSanitizedPrefixLength (int): The maximum allowed length for the sanitized prefix.
  • reqHashLength (int): The desired length of the hexadecimal hash to be appended.

Returns:

  • string: A single string representing the sanitized and joined identifier.
  • error: An error if the sanitization fails (e.g., if ids is empty).

Side Effects:

  • None.

func SanitizeOperationID

func SanitizeOperationID(input string) string

SanitizeOperationID cleans an input string to make it suitable for use as an operation ID. It replaces any sequence of disallowed characters with a short hexadecimal hash of that sequence, ensuring uniqueness while preserving as much of the original string as possible.

Summary: Sanitizes a string for use as an operation ID.

Parameters:

  • input (string): The string to be sanitized.

Returns:

  • string: The sanitized string.

Side Effects:

  • None.

func SanitizeSecretValue

func SanitizeSecretValue(s *configv1.SecretValue) *configv1.SecretValue

SanitizeSecretValue sanitizes a SecretValue.

Summary: Sanitizes a SecretValue object.

Parameters:

  • s (*configv1.SecretValue): The secret value to sanitize.

Returns:

  • *configv1.SecretValue: The sanitized secret value, or nil if input is nil.

func SanitizeServiceName

func SanitizeServiceName(name string) (string, error)

SanitizeServiceName sanitizes the given service name. It ensures that the name is a valid identifier by removing disallowed characters and appending a hash if the name is too long or contains illegal characters. This function calls SanitizeID with alwaysAppendHash set to false.

Summary: Sanitizes a service name to be safe for use as an identifier.

Parameters:

  • name (string): The service name to sanitize.

Returns:

  • string: The sanitized service name.
  • error: An error if sanitization fails.

Side Effects:

  • None.

func SanitizeToolName

func SanitizeToolName(name string) (string, error)

SanitizeToolName sanitizes the given tool name. It ensures that the name is a valid identifier by removing disallowed characters and appending a hash if the name is too long or contains illegal characters. This function calls SanitizeID with alwaysAppendHash set to false.

Summary: Sanitizes a tool name to be safe for use as an identifier.

Parameters:

  • name (string): The tool name to sanitize.

Returns:

  • string: The sanitized tool name.
  • error: An error if sanitization fails.

Side Effects:

  • None.

func SanitizeUser

func SanitizeUser(u *configv1.User) *configv1.User

SanitizeUser creates a sanitized copy of the user object with sensitive data redacted.

Summary: Sanitizes a user object.

Parameters:

  • u (*configv1.User): The user object to sanitize.

Returns:

  • *configv1.User: A sanitized copy of the user object, or nil if input is nil.

func SanitizeUserToken

func SanitizeUserToken(t *configv1.UserToken) *configv1.UserToken

SanitizeUserToken sanitizes the user token.

Summary: Sanitizes a user token.

Parameters:

  • t (*configv1.UserToken): The user token to sanitize.

Returns:

  • *configv1.UserToken: The sanitized user token, or nil if input is nil.

func StripSecretsFromAuth

func StripSecretsFromAuth(auth *configv1.Authentication)

StripSecretsFromAuth removes sensitive values from the authentication config.

Summary: Removes sensitive values from authentication config.

Parameters:

  • auth (*configv1.Authentication): The authentication configuration to strip secrets from.

func StripSecretsFromCollection

func StripSecretsFromCollection(collection *configv1.Collection)

StripSecretsFromCollection removes sensitive information from the service collection.

Summary: Removes sensitive information from service collection.

Parameters:

  • collection (*configv1.Collection): The service collection to strip secrets from.

func StripSecretsFromProfile

func StripSecretsFromProfile(profile *configv1.ProfileDefinition)

StripSecretsFromProfile removes sensitive information from the profile definition.

Summary: Removes sensitive information from profile definition.

Parameters:

  • profile (*configv1.ProfileDefinition): The profile definition to strip secrets from.

func StripSecretsFromService

func StripSecretsFromService(svc *configv1.UpstreamServiceConfig)

StripSecretsFromService removes sensitive information from the service configuration.

Summary: Removes sensitive information from service configuration.

Parameters:

  • svc (*configv1.UpstreamServiceConfig): The upstream service configuration to strip secrets from.

func ToString

func ToString(v any) string

ToString converts a value to a string representation efficiently. It handles common types like string, json.Number, int, float, and bool without using reflection when possible. Optimization: We manually handle all standard Go numeric types to avoid the overhead of reflection (fmt.Sprintf) which is significantly slower and generates more allocations.

Summary: Converts any value to a string efficiently.

Parameters:

  • v (any): The value to convert to a string.

Returns:

  • string: The string representation of the value.

Side Effects:

  • None.

func WalkJSONStrings

func WalkJSONStrings(input []byte, visitor func(raw []byte) ([]byte, bool)) []byte

WalkJSONStrings visits every string value in the JSON input.

Summary: Walks through a JSON bytes slice and applies a visitor function to all string values.

It supports non-standard JSON with comments (// and /* */).

Parameters:

  • input: []byte. The JSON input to walk.
  • visitor: func(raw []byte) ([]byte, bool). A function that takes the raw string bytes (including quotes) and returns a replacement and a modified flag.

Returns:

  • []byte: The potentially modified JSON output.

func WalkStandardJSONStrings

func WalkStandardJSONStrings(input []byte, visitor func(raw []byte) ([]byte, bool)) []byte

WalkStandardJSONStrings visits every string value in the JSON input.

Summary: Optimized JSON walker for standard JSON (no comments).

It visits every string value (not keys) and applies the visitor.

Parameters:

  • input: []byte. The standard JSON input.
  • visitor: func(raw []byte) ([]byte, bool). A function that takes the raw string bytes and returns a replacement and a modified flag.

Returns:

  • []byte: The potentially modified JSON output.

Types

type IPResolver

type IPResolver interface {
	// LookupIP looks up host using the local resolver.
	//
	// Summary: Looks up host IP addresses.
	//
	// Parameters:
	//   - ctx (context.Context): The context for the lookup.
	//   - network (string): The network type (e.g., "ip", "ip4", "ip6").
	//   - host (string): The host to look up.
	//
	// Returns:
	//   - ([]net.IP): A slice of that host's IPv4 and IPv6 addresses.
	//   - (error): An error if the lookup fails.
	LookupIP(ctx context.Context, network, host string) ([]net.IP, error)
}

IPResolver defines an interface for looking up IP addresses.

Summary: Interface for IP address resolution.

It matches the signature of net.Resolver.LookupIP.

type NetDialer

type NetDialer interface {
	// DialContext connects to the address on the named network using the provided context.
	//
	// Summary: Dials a network connection.
	//
	// Parameters:
	//   - ctx (context.Context): The context for the dial operation.
	//   - network (string): The network type.
	//   - address (string): The address to connect to.
	//
	// Returns:
	//   - (net.Conn): The established connection.
	//   - (error): An error if the connection fails.
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

NetDialer defines an interface for dialing network connections.

Summary: Interface for network dialing.

It matches the signature of net.Dialer.DialContext.

type SafeDialer

type SafeDialer struct {
	// AllowLoopback allows connections to loopback addresses (127.0.0.1, ::1).
	AllowLoopback bool
	// AllowPrivate allows connections to private network addresses (RFC 1918, RFC 4193).
	AllowPrivate bool
	// AllowLinkLocal allows connections to link-local addresses (169.254.x.x, fe80::/10).
	// This includes cloud metadata services.
	AllowLinkLocal bool

	// Resolver is used for DNS lookups. If nil, net.DefaultResolver is used.
	Resolver IPResolver
	// Dialer is used for establishing connections. If nil, &net.Dialer{} is used.
	Dialer NetDialer
}

SafeDialer provides control over outbound connections to prevent Server-Side Request Forgery (SSRF).

Summary: Secure network dialer preventing SSRF.

func NewSafeDialer

func NewSafeDialer() *SafeDialer

NewSafeDialer creates a new SafeDialer with strict default security settings.

Summary: Initializes a SafeDialer with secure defaults.

By default, it blocks all non-public IP addresses (loopback, private, link-local).

Returns:

  • (*SafeDialer): A new SafeDialer instance with restrictive defaults.

func (*SafeDialer) DialContext

func (d *SafeDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

DialContext establishes a network connection to the given address while enforcing egress policies.

Summary: Dials a network address securely.

It resolves the host's IP addresses and verifies them against the allowed list before connecting.

Parameters:

  • ctx (context.Context): The context for the dial operation.
  • network (string): The network type (e.g., "tcp", "tcp4", "tcp6").
  • addr (string): The address to connect to (host:port).

Returns:

  • (net.Conn): The established connection.
  • (error): An error if resolution fails, all resolved IPs are blocked by policy, or the connection fails.

type SecretRedactor

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

SecretRedactor handles redaction of secrets from text. It is optimized to pre-process the list of secrets once and reuse the configuration.

Summary: Optimized text redactor for known secrets.

func NewSecretRedactor

func NewSecretRedactor(secrets []string) *SecretRedactor

NewSecretRedactor creates a new SecretRedactor with the given secrets. It performs filtering, deduplication, and sorting of secrets to ensure optimal redaction.

Summary: Creates a new SecretRedactor.

Parameters:

  • secrets ([]string): The list of secrets to redact.

Returns:

  • *SecretRedactor: The configured redactor.

func (*SecretRedactor) Redact

func (r *SecretRedactor) Redact(text string) string

Redact replaces all occurrences of the configured secrets in the text with [REDACTED].

Summary: Redacts secrets from text.

Parameters:

  • text (string): The text to redact.

Returns:

  • string: The redacted text.

type WrappedServerStream

type WrappedServerStream struct {
	grpc.ServerStream
	Ctx context.Context
}

WrappedServerStream is a wrapper around grpc.ServerStream that allows modifying the context.

Summary: A wrapper for grpc.ServerStream that overrides the context.

func (*WrappedServerStream) Context

func (w *WrappedServerStream) Context() context.Context

Context returns the modified context.

Summary: Returns the context associated with the stream.

Returns:

  • context.Context: The modified context.

Directories

Path Synopsis
Package passhash provides password hashing utilities using bcrypt.
Package passhash provides password hashing utilities using bcrypt.
Package schemaconv provides utilities for converting between schema formats.
Package schemaconv provides utilities for converting between schema formats.
Package testutil provides testing utilities.
Package testutil provides testing utilities.

Jump to

Keyboard shortcuts

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