util

package
v0.0.0-...-650ca3f Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: Apache-2.0 Imports: 31 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 TrueStr = "true"

TrueStr is a string constant for "true".

Variables

View Source
var (
	// IsDockerSocketAccessibleFunc is a variable to allow mocking in tests.
	// It checks if the Docker socket is accessible.
	IsDockerSocketAccessibleFunc = isDockerSocketAccessibleDefault
)

Functions

func CloseDockerClient

func CloseDockerClient()

CloseDockerClient closes the shared Docker client. It should be called on application shutdown.

func ContextWithRemoteIP

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

ContextWithRemoteIP returns a new context with the remote IP.

func ExtractIP

func ExtractIP(addr string) string

ExtractIP extracts the IP address from a host:port string or just an IP string. It also handles IPv6 brackets.

func GenerateUUID

func GenerateUUID() string

GenerateUUID creates a new random (version 4) UUID.

Returns:

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

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.

Returns:

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

func IsDockerSocketAccessible

func IsDockerSocketAccessible() bool

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

func IsNil

func IsNil(i any) bool

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

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

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

func IsPrivateNetworkIP

func IsPrivateNetworkIP(ip net.IP) bool

IsPrivateNetworkIP checks if the IP address is a private network address. This includes RFC1918, RFC4193 (Unique Local), and RFC6598 (CGNAT). It does NOT include loopback or link-local addresses.

func IsSensitiveKey

func IsSensitiveKey(key string) bool

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

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.

tlsConfig contains the TLS settings to apply to the HTTP client's transport. It returns a configured *http.Client or an error if the TLS configuration is invalid or files cannot be read.

func NewSafeHTTPClient

func NewSafeHTTPClient() *http.Client

NewSafeHTTPClient creates a new http.Client that prevents SSRF. It uses SafeDialer to block access to link-local and private IPs. Configuration can be overridden via environment variables: - MCPANY_ALLOW_LOOPBACK_RESOURCES: Set to "true" to allow loopback addresses. - MCPANY_ALLOW_PRIVATE_NETWORK_RESOURCES: Set to "true" to allow private network addresses.

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.

toolName is the fully qualified tool name. It returns the service key, the bare tool name, and an error if parsing fails (though the current implementation does not return an error).

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.

func RedactMap

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

RedactMap recursively redacts sensitive keys in a map. Note: This function creates a deep copy of the map with redacted values.

func RemoteIPFromContext

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

RemoteIPFromContext retrieves the remote IP from the context.

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.

Parameters:

urlPath: The URL path containing placeholders in the format "{{key}}".
params: A map of keys to values to replace placeholders with.
noEscapeParams: A map of keys that should NOT be URL escaped.

Returns:

The URL path with placeholders replaced.

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.

Parameters:

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

Returns:

The URL query string with placeholders replaced.

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.

Parameters:

ctx: The context for the secret resolution (used for network requests, etc).
secret: The SecretValue configuration object to resolve.

Returns:

The resolved secret string.
An error if resolution fails (e.g., missing env var, file read error).

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.

Parameters:

ctx: The context for the secret resolution.
secretMap: A map of keys to SecretValue objects.
plainMap: A map of keys to plain string values.

Returns:

A single map containing all keys with their resolved string values.
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, but strictly prevents connections to private or loopback IP addresses to mitigate SSRF vulnerabilities.

It resolves the host's IP addresses and checks each one. If any resolved IP is private or loopback, the connection is blocked.

ctx is the context for the dial operation. network is the network type (e.g., "tcp"). addr is the address to connect to (host:port). It returns the established connection or an error if the connection fails or is blocked.

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_-]`. Wait, checking the implementation: It allows a-z, A-Z, 0-9, _, - It seems to replace invalid chars with nothing. Actually it calculates `dirtyCount`. If `dirtyCount > 0`, it means we need to "sanitize" by removing them? Yes, `rawSanitizedLen := len(id) - dirtyCount`. And later it only writes if valid char.

  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.

Parameters:

ids: A slice of strings to be sanitized and joined. Each element of the slice
     represents a part of the final identifier.
alwaysAppendHash: A boolean that, if true, forces a hash to be appended to each
                  sanitized string, regardless of whether it was modified.
maxSanitizedPrefixLength: The maximum allowed length for the sanitized prefix of each
                          string before a hash is appended.
reqHashLength: The desired length of the hexadecimal hash to be appended.

Returns:

A single string representing the sanitized and joined identifier.

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.

input is the string to be sanitized. It returns the sanitized string.

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.

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.

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.

Types

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
}

SafeDialer provides control over outbound connections to prevent SSRF.

func NewSafeDialer

func NewSafeDialer() *SafeDialer

NewSafeDialer creates a new SafeDialer with strict defaults (blocking all non-public IPs).

func (*SafeDialer) DialContext

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

DialContext creates a connection to the given address, enforcing the configured egress policy.

type WrappedServerStream

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

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

func (*WrappedServerStream) Context

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

Context returns 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