utils

package
v0.0.0-...-bd1a880 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2025 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Common errors
	ErrInvalidRequest      = errors.New("invalid request")
	ErrRequestTimeout      = errors.New("request timeout")
	ErrUnauthorized        = errors.New("unauthorized")
	ErrForbidden           = errors.New("forbidden")
	ErrNotFound            = errors.New("not found")
	ErrMethodNotAllowed    = errors.New("method not allowed")
	ErrTooManyRequests     = errors.New("too many requests")
	ErrInternalServerError = errors.New("internal server error")
	ErrBadGateway          = errors.New("bad gateway")
	ErrServiceUnavailable  = errors.New("service unavailable")
	ErrGatewayTimeout      = errors.New("gateway timeout")

	// Security-related errors
	ErrContentTypeNotAllowed = errors.New("content type not allowed")
	ErrInvalidContentLength  = errors.New("invalid content length")
	ErrRequestEntityTooLarge = errors.New("request entity too large")
	ErrInvalidHostHeader     = errors.New("invalid host header")
	ErrCSRFValidationFailed  = errors.New("CSRF validation failed")
	ErrIPAddressBlocked      = errors.New("IP address blocked")
	ErrRateLimitExceeded     = errors.New("rate limit exceeded")
)
View Source
var (
	// ErrThrottleContextCanceled indicates the context was canceled while waiting
	ErrThrottleContextCanceled = errors.New("context canceled while waiting for throttle")

	// ErrThrottleInvalidParams indicates invalid parameters for the throttle
	ErrThrottleInvalidParams = errors.New("invalid throttle parameters: limit must be > 0 and interval must be > 0")
)
View Source
var (
	DefaultOptions = ValidationOptions{
		MaxLength:  256,
		MinLength:  1,
		Required:   true,
		StrictMode: false,
	}

	StrictOptions = ValidationOptions{
		MaxLength:  256,
		MinLength:  1,
		Required:   true,
		StrictMode: true,
	}

	SecurityOptions = ValidationOptions{
		MaxLength:      64,
		MinLength:      8,
		Required:       true,
		StrictMode:     true,
		SanitizeOutput: true,
	}
)

Default validation options

Functions

func BadRequest

func BadRequest(c *gin.Context, message string)

BadRequest returns a 400 Bad Request response

func BindForm

func BindForm(c *gin.Context, obj interface{}) bool

BindForm binds the form data to the given struct with error handling

func BindHeader

func BindHeader(c *gin.Context, obj interface{}) bool

BindHeader binds the header values to the given struct with error handling

func BindJSON

func BindJSON(c *gin.Context, obj interface{}) bool

BindJSON binds the request body to the given struct with error handling

func BindQuery

func BindQuery(c *gin.Context, obj interface{}) bool

BindQuery binds the query parameters to the given struct with error handling

func BindURI

func BindURI(c *gin.Context, obj interface{}) bool

BindURI binds the URI parameters to the given struct with error handling

func BuildFilterArgs

func BuildFilterArgs(filterMap map[string]string) filters.Args

BuildFilterArgs constructs a filters.Args object from a map of filter key-value pairs. It skips empty values to avoid sending empty filters to the Docker API.

func CORSMiddleware

func CORSMiddleware(allowOrigins []string, allowMethods []string, allowHeaders []string, maxAge int) gin.HandlerFunc

CORSMiddleware creates a middleware that adds CORS headers

func CSVResponse

func CSVResponse(c *gin.Context, data []byte, filename string)

CSVResponse sends a CSV file as response

func Conflict

func Conflict(c *gin.Context, message string)

Conflict returns a 409 Conflict response

func ContainsString

func ContainsString(slice []string, str string) bool

ContainsString checks if a slice of strings contains a specific string. Case-insensitive comparison. NOTE: This specific implementation is not used by network_controller.go anymore, but kept here in case it's used elsewhere or intended for a different purpose.

func ConvertJSONMapToStringMap

func ConvertJSONMapToStringMap(jsonMap models.JSONMap) map[string]string

ConvertJSONMapToStringMap converts models.JSONMap to map[string]string

func CreateHTTPClient

func CreateHTTPClient(config HTTPClientConfig) *http.Client

CreateHTTPClient creates an HTTP client with the given configuration

func EncodeRegistryAuth

func EncodeRegistryAuth(authConfig models.RegistryAuth) (string, error)

EncodeRegistryAuth encodes registry authentication details into a base64 string suitable for the X-Registry-Auth header.

func EnsureImage

func EnsureImage(ctx context.Context, cli DockerClient, imageName string, pull bool, logger *logrus.Logger) error

EnsureImage checks if an image exists locally, pulling it if necessary.

func EnsureNetwork

func EnsureNetwork(ctx context.Context, cli DockerClient, networkName string, driver string, labels map[string]string, enableIPv6 bool, internal bool, attachable bool, logger *logrus.Logger) (string, error)

EnsureNetwork checks if a network exists, creating it if necessary.

func EnsureVolume

func EnsureVolume(ctx context.Context, cli DockerClient, volumeName string, driver string, driverOpts map[string]string, labels map[string]string, logger *logrus.Logger) (string, error)

EnsureVolume checks if a volume exists, creating it if necessary.

func ErrorResponse

func ErrorResponse(c *gin.Context, statusCode int, code, message, details string)

ErrorResponse returns a standardized error response

func FileExists

func FileExists(filename string) bool

FileExists checks if a file exists and is not a directory.

func FileResponse

func FileResponse(c *gin.Context, data []byte, filename, contentType string)

FileResponse sends a file as response

func Forbidden

func Forbidden(c *gin.Context, message string)

Forbidden returns a 403 Forbidden response

func FormatContainerStatus

func FormatContainerStatus(state string, health *types.Health) string

FormatContainerStatus determines a user-friendly status string based on state and health. Note: This logic might need refinement based on specific desired statuses.

func FormatImageSize

func FormatImageSize(sizeBytes int64) string

FormatImageSize converts bytes to a human-readable string (KB, MB, GB).

func FormatLabels

func FormatLabels(labels map[string]string) []string

FormatLabels converts a map of labels into a slice of "key=value" strings. Returns an empty slice if the input map is nil or empty.

func FromJSON

func FromJSON(data []byte, obj interface{}) error

FromJSON converts JSON bytes to an object

func GenerateRequestID

func GenerateRequestID() string

GenerateRequestID generates a unique request ID

func GetClientIP

func GetClientIP(c *gin.Context) string

GetClientIP returns the client IP address

func GetContainerByID

func GetContainerByID(ctx context.Context, cli DockerClient, id string) (*types.Container, error)

GetContainerByID finds a container by its full or partial ID.

func GetContainerByName

func GetContainerByName(ctx context.Context, cli DockerClient, name string) (*types.Container, error)

GetContainerByName finds a container by its exact name.

func GetContainerIP

func GetContainerIP(networkSettings *types.NetworkSettings) string

GetContainerIP extracts the primary IP address from the container's network settings. It iterates through the networks and returns the first valid IP found. Returns an empty string if no IP address is found.

func GetContainerLogs

func GetContainerLogs(ctx context.Context, cli DockerClient, containerID string, options container.LogsOptions) (io.ReadCloser, error)

GetContainerLogs retrieves logs for a specific container.

func GetExternalResourceName

func GetExternalResourceName(external interface{}, defaultName string) string

GetExternalResourceName gets the name of an external resource from compose config.

func GetPaginationParams

func GetPaginationParams(c *gin.Context) (page int, pageSize int)

GetPaginationParams extracts page and page_size from query parameters with defaults and limits.

func GetRequestID

func GetRequestID(c *gin.Context) string

GetRequestID retrieves the request ID from the context

func GetResourceName

func GetResourceName(projectName, prefix, name string) string

GetResourceName generates the full resource name based on project and prefix. Follows Docker Compose naming convention (project_name) if prefix is empty.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a password using bcrypt.

func InspectNetwork

func InspectNetwork(ctx context.Context, cli DockerClient, networkID string) (network.Inspect, error)

InspectNetwork inspects a specific network.

func InspectVolume

func InspectVolume(ctx context.Context, cli DockerClient, volumeID string) (volume.Volume, error)

InspectVolume inspects a specific volume.

func InternalServerError

func InternalServerError(c *gin.Context, message string)

InternalServerError returns a 500 Internal Server Error response

func IsContainerRunning

func IsContainerRunning(state string) bool

IsContainerRunning checks if the container state indicates it's running.

func IsExternalResource

func IsExternalResource(external interface{}) bool

IsExternalResource checks if a resource is marked as external in compose files.

func IsSensitiveField

func IsSensitiveField(field string) bool

IsSensitiveField checks if a field is sensitive and should not be logged

func IsValidContentType

func IsValidContentType(contentType string, allowedTypes []string) bool

IsValidContentType checks if the content type is valid

func IsValidURL

func IsValidURL(str string) bool

IsValidURL checks if a string is a valid URL.

func JSONResponse

func JSONResponse(c *gin.Context, data []byte, filename string)

JSONResponse sends a JSON file as response

func ListImages

func ListImages(ctx context.Context, cli DockerClient, options image.ListOptions) ([]image.Summary, error)

ListImages lists Docker images based on filters.

func ListNetworks

func ListNetworks(ctx context.Context, cli DockerClient, options network.ListOptions) ([]network.Summary, error)

ListNetworks lists Docker networks based on filters.

func ListVolumes

func ListVolumes(ctx context.Context, cli DockerClient, filter filters.Args) (volume.ListResponse, error)

ListVolumes lists Docker volumes based on filters.

func LoggingMiddleware

func LoggingMiddleware(logger *logrus.Logger) gin.HandlerFunc

LoggingMiddleware creates a middleware that logs requests

func MapToStruct

func MapToStruct(m map[string]interface{}, obj interface{}) error

MapToStruct converts a map to a struct using JSON tags

func MethodNotAllowed

func MethodNotAllowed(c *gin.Context, message string)

MethodNotAllowed returns a 405 Method Not Allowed response

func NoContentResponse

func NoContentResponse(c *gin.Context)

NoContentResponse returns a 204 No Content response

func NotFound

func NotFound(c *gin.Context, message string)

NotFound returns a 404 Not Found response

func PaginateResults

func PaginateResults(results interface{}, page, perPage int) (interface{}, int, int, error)

PaginateResults paginates a slice of results

func PaginatedResponse

func PaginatedResponse(c *gin.Context, data interface{}, page, perPage, total int)

PaginatedResponse returns a standardized paginated response

func ParseContainerLabels

func ParseContainerLabels(dockerLabels map[string]string) map[string]interface{}

ParseContainerLabels converts Docker API labels map to our JSONMap. Handles potential nil map from the API.

func ParseImageName

func ParseImageName(ref string) (reference.Named, error)

ParseImageName parses a Docker image name string into its components. It wraps github.com/docker_test/distribution/reference.ParseNamed.

func ParseRepositoryTag

func ParseRepositoryTag(refStr string) (repository string, tag string)

ParseRepositoryTag splits a full image reference (e.g., "nginx:latest", "myregistry.com/myimage:v1") into repository name ("nginx", "myregistry.com/myimage") and tag ("latest", "v1"). It defaults the tag to "latest" if not specified.

func RateLimitMiddleware

func RateLimitMiddleware(limiter *RateLimiter) gin.HandlerFunc

RateLimitMiddleware creates a middleware that limits request rates

func RecoveryMiddleware

func RecoveryMiddleware() gin.HandlerFunc

RecoveryMiddleware creates a middleware that recovers from panics

func RedactSensitiveData

func RedactSensitiveData(data map[string]interface{}) map[string]interface{}

RedactSensitiveData redacts sensitive data from a map

func RemoveNetwork

func RemoveNetwork(ctx context.Context, cli DockerClient, networkIDOrName string, logger *logrus.Logger) error

RemoveNetwork removes a network if it exists.

func RemoveVolume

func RemoveVolume(ctx context.Context, cli DockerClient, volumeIDOrName string, force bool, logger *logrus.Logger) error

RemoveVolume removes a volume if it exists.

func RequestIDMiddleware

func RequestIDMiddleware() gin.HandlerFunc

RequestIDMiddleware creates a middleware that adds a request ID

func SanitizeDockerName

func SanitizeDockerName(name string) string

SanitizeDockerName removes invalid characters from a Docker resource name.

func SanitizeHTML

func SanitizeHTML(input string) string

SanitizeHTML sanitizes HTML content

func SanitizeHeaders

func SanitizeHeaders(headers map[string]string) map[string]string

SanitizeHeaders returns a map of headers with sensitive information masked

func SanitizeValue

func SanitizeValue(field string, value interface{}) string

SanitizeValue sanitizes a value for logging

func SecureHeaders

func SecureHeaders(c *gin.Context)

SecureHeaders adds security headers to the response

func ServiceUnavailable

func ServiceUnavailable(c *gin.Context, message string)

ServiceUnavailable returns a 503 Service Unavailable response

func SortNetworks

func SortNetworks(networks []*models.Network, sortBy string, sortOrder string) []*models.Network

SortNetworks sorts a slice of Network models. Placeholder implementation - returns the original slice. TODO: Implement actual sorting logic based on sortBy and sortOrder.

func StatusAccepted

func StatusAccepted(c *gin.Context, message string)

StatusAccepted returns a 202 Accepted response

func StringHasPrefix

func StringHasPrefix(s, prefix string) bool

StringHasPrefix is a simple wrapper around strings.HasPrefix.

func StructToMap

func StructToMap(obj interface{}) (map[string]interface{}, error)

StructToMap converts a struct to a map using JSON tags

func SuccessResponse

func SuccessResponse(c *gin.Context, data interface{})

SuccessResponse returns a standardized success response

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc

TimeoutMiddleware creates a middleware that adds a timeout to requests

func ToJSON

func ToJSON(obj interface{}) ([]byte, error)

ToJSON converts an object to JSON bytes

func TooManyRequests

func TooManyRequests(c *gin.Context, message string)

TooManyRequests returns a 429 Too Many Requests response

func Unauthorized

func Unauthorized(c *gin.Context, message string)

Unauthorized returns a 401 Unauthorized response

func UnprocessableEntity

func UnprocessableEntity(c *gin.Context, message string)

UnprocessableEntity returns a 422 Unprocessable Entity response

func ValidateCSRFToken

func ValidateCSRFToken(c *gin.Context, token string) bool

ValidateCSRFToken validates a CSRF token

func ValidateContainerName

func ValidateContainerName(name string, options ...ValidationOptions) error

ValidateContainerName validates a container name.

func ValidateEmail

func ValidateEmail(email string, options ...ValidationOptions) error

ValidateEmail validates an email address.

func ValidateFilename

func ValidateFilename(filename string, options ...ValidationOptions) error

ValidateFilename validates a filename.

func ValidateIPAddress

func ValidateIPAddress(ip string, options ...ValidationOptions) error

ValidateIPAddress validates an IP address.

func ValidateImageName

func ValidateImageName(name string, options ...ValidationOptions) error

ValidateImageName validates a Docker image name.

func ValidateJSONInput

func ValidateJSONInput(jsonStr string, maxDepth int, options ...ValidationOptions) error

ValidateJSONInput validates a JSON string.

func ValidateNetworkName

func ValidateNetworkName(name string, options ...ValidationOptions) error

ValidateNetworkName validates a network name.

func ValidatePassword

func ValidatePassword(password string, options ...ValidationOptions) error

ValidatePassword validates a password.

func ValidatePath

func ValidatePath(path string, options ...ValidationOptions) error

ValidatePath validates a file path.

func ValidatePathHTTP

func ValidatePathHTTP(path string) bool

ValidatePath validates a file path for security in HTTP context

func ValidatePort

func ValidatePort(port int) error

ValidatePort validates a port number.

func ValidatePortString

func ValidatePortString(port string) error

ValidatePortString validates a port number as a string.

func ValidateRequestHeaders

func ValidateRequestHeaders(c *gin.Context, config map[string]string) bool

ValidateRequestHeaders checks if the request headers are valid

func ValidateURL

func ValidateURL(rawURL string, allowedSchemes []string, options ...ValidationOptions) error

ValidateURL validates a URL.

func ValidateUsername

func ValidateUsername(username string, options ...ValidationOptions) error

ValidateUsername validates a username.

func ValidateVolumeName

func ValidateVolumeName(name string, options ...ValidationOptions) error

ValidateVolumeName validates a volume name.

func VerifyPassword

func VerifyPassword(password, hash string) bool

VerifyPassword verifies a password against a hash.

func XMLResponse

func XMLResponse(c *gin.Context, data []byte, filename string)

XMLResponse sends an XML file as response

Types

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Details string `json:"details,omitempty"`
}

APIError represents an API error

func FormatError

func FormatError(err error) APIError

FormatError formats an error for API responses

type DockerClient

type DockerClient interface {
	ContainerList(ctx context.Context, options container.ListOptions) ([]types.Container, error)
	ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error)
	ContainerLogs(ctx context.Context, container string, options container.LogsOptions) (io.ReadCloser, error)
	ImageList(ctx context.Context, options image.ListOptions) ([]image.Summary, error)
	ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error)
	ImagePull(ctx context.Context, ref string, options image.PullOptions) (io.ReadCloser, error)
	NetworkList(ctx context.Context, options network.ListOptions) ([]network.Summary, error)                       // Use network.ListOptions and network.Summary
	NetworkInspect(ctx context.Context, networkID string, options network.InspectOptions) (network.Inspect, error) // Use network.InspectOptions and network.Inspect
	NetworkCreate(ctx context.Context, name string, options network.CreateOptions) (network.CreateResponse, error) // Use network.CreateOptions and network.CreateResponse
	NetworkRemove(ctx context.Context, networkID string) error
	VolumeList(ctx context.Context, filter filters.Args) (volume.ListResponse, error)
	VolumeInspect(ctx context.Context, volumeID string) (volume.Volume, error)
	VolumeCreate(ctx context.Context, options volume.CreateOptions) (volume.Volume, error)
	VolumeRemove(ctx context.Context, volumeID string, force bool) error
	Ping(ctx context.Context) (types.Ping, error)
}

DockerClient defines the interface for Docker client operations needed by utils

type HTTPClientConfig

type HTTPClientConfig struct {
	Timeout               time.Duration
	KeepAlive             time.Duration
	MaxIdleConns          int
	IdleConnTimeout       time.Duration
	TLSHandshakeTimeout   time.Duration
	ExpectContinueTimeout time.Duration
	ResponseHeaderTimeout time.Duration
	MaxResponseBodySize   int64
	Proxy                 func(*http.Request) (*url.URL, error)
	TLSConfig             *tls.Config
	AllowedContentTypes   []string
	DisallowedHosts       []string
}

HTTPClientConfig contains configuration for the HTTP client

func DefaultHTTPClientConfig

func DefaultHTTPClientConfig() HTTPClientConfig

DefaultHTTPClientConfig returns the default HTTP client configuration

func SecureHTTPClientConfig

func SecureHTTPClientConfig() HTTPClientConfig

SecureHTTPClientConfig returns a secure HTTP client configuration

type HTTPResponse

type HTTPResponse struct {
	StatusCode int
	Headers    map[string]string
	Body       []byte
}

HTTPResponse is a wrapper for HTTP responses

func HTTPRequest

func HTTPRequest(ctx context.Context, method, urlString string, headers map[string]string, body io.Reader, config HTTPClientConfig) (*HTTPResponse, error)

HTTPRequest sends an HTTP request with security checks

type Meta

type Meta struct {
	Page       int       `json:"page,omitempty"`
	PerPage    int       `json:"per_page,omitempty"`
	TotalPages int       `json:"total_pages,omitempty"`
	Total      int       `json:"total,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
	RequestID  string    `json:"request_id,omitempty"`
	Version    string    `json:"version,omitempty"`
}

Meta contains metadata for pagination responses

type RateLimiter

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

RateLimiter manages rate limiting for HTTP requests

func NewRateLimiter

func NewRateLimiter(rps int, burst int) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) CleanupLimiters

func (rl *RateLimiter) CleanupLimiters(maxAge time.Duration)

CleanupLimiters removes old limiters

func (*RateLimiter) GetLimiter

func (rl *RateLimiter) GetLimiter(key string) *rate.Limiter

GetLimiter gets or creates a rate limiter for the given IP

type Response

type Response struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   *APIError   `json:"error,omitempty"`
	Meta    *Meta       `json:"meta,omitempty"`
}

Response represents a standardized API response

type Throttle

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

Throttle provides a mechanism to limit the rate of operations

func NewThrottle

func NewThrottle(limit int, interval time.Duration) *Throttle

NewThrottle creates a new rate limiter with the specified limit per interval limit: maximum number of operations per interval interval: the time interval for the rate limit

func (*Throttle) Wait

func (t *Throttle) Wait(ctx context.Context) error

Wait blocks until a token is available or the context is canceled It returns nil if a token was acquired, or an error if the context was canceled

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Code    string `json:"code"`
	Message string `json:"message"`
	Value   string `json:"value,omitempty"` // The invalid value (sanitized for sensitive fields)
}

ValidationError represents a validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type ValidationOptions

type ValidationOptions struct {
	// MaxLength is the maximum allowed length
	MaxLength int

	// MinLength is the minimum allowed length
	MinLength int

	// Required specifies if the value is required
	Required bool

	// StrictMode enables stricter validation rules
	StrictMode bool

	// AllowedValues is a list of allowed values
	AllowedValues []string

	// DisallowedValues is a list of disallowed values
	DisallowedValues []string

	// CustomValidation is a custom validation function
	CustomValidation func(interface{}) error

	// SanitizeOutput determines if output should be sanitized
	SanitizeOutput bool
}

ValidationOptions contains options for validation.

type ValidationResult

type ValidationResult struct {
	Errors []*ValidationError `json:"errors"`
}

ValidationResult contains the result of a validation operation.

func NewValidationResult

func NewValidationResult() *ValidationResult

NewValidationResult creates a new ValidationResult.

func ValidateContainerSecurityOptions

func ValidateContainerSecurityOptions(container types.Container) *ValidationResult

Validate container security options using types.Container

func ValidateCredentials

func ValidateCredentials(username, password string, options ...ValidationOptions) *ValidationResult

ValidateCredentials validates username and password credentials

func ValidateSecurityOpts

func ValidateSecurityOpts(opts []string) *ValidationResult

ValidateSecurityOpts validates Docker security options.

func ValidateStruct

func ValidateStruct(s interface{}) *ValidationResult

ValidateStruct validates a struct using validator tags

func (*ValidationResult) AddError

func (vr *ValidationResult) AddError(field, code, message string, value ...interface{})

AddError adds an error to the validation result.

func (*ValidationResult) ErrorMessages

func (vr *ValidationResult) ErrorMessages() []string

ErrorMessages returns all error messages.

func (*ValidationResult) ErrorsByField

func (vr *ValidationResult) ErrorsByField() map[string]string

ErrorsByField returns a map of field names to error messages.

func (*ValidationResult) First

func (vr *ValidationResult) First() *ValidationError

First returns the first error or nil if there are no errors.

func (*ValidationResult) GetErrors

func (vr *ValidationResult) GetErrors() []*ValidationError

GetErrors returns all validation errors.

func (*ValidationResult) IsValid

func (vr *ValidationResult) IsValid() bool

IsValid returns true if the validation passed.

func (*ValidationResult) MergeResults

func (vr *ValidationResult) MergeResults(other *ValidationResult)

MergeResults merges the errors from another ValidationResult into this one.

func (*ValidationResult) ToJSON

func (vr *ValidationResult) ToJSON() (string, error)

ToJSON returns the validation result as a JSON string.

Directories

Path Synopsis
Package archiver provides utilities for working with container file archives
Package archiver provides utilities for working with container file archives

Jump to

Keyboard shortcuts

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