Documentation
¶
Overview ¶
Package filevalidator provides comprehensive file validation functionality.
Index ¶
- Constants
- func AddCustomMediaTypeGroupMapping(group MediaTypeGroup, mimeTypes []string)
- func AddCustomMediaTypeMapping(ext string, mimeType string)
- func CreateFileFromBytes(filename string, content []byte) *multipart.FileHeader
- func CreateFileFromReader(filename string, reader io.Reader) (*multipart.FileHeader, error)
- func DetectContentType(data []byte) string
- func DetectContentTypeFromFile(filePath string) (string, error)
- func ExpandAcceptedTypes(acceptedTypes []string) []string
- func FormatSizeReadable(size int64) string
- func GetErrorMessage(err error) string
- func HasSupportedDocumentExtension(filename string) bool
- func HasSupportedImageExtension(filename string) bool
- func IsDocument(contentType string) bool
- func IsErrorOfType(err error, errType ValidationErrorType) bool
- func IsImage(contentType string) bool
- func IsValidationError(err error) bool
- func MIMETypeForExtension(ext string) string
- func StreamValidate(reader io.Reader, filename string, validator Validator, bufferSize int64) error
- func ValidateLocalFile(validator Validator, filePath string) error
- type ArchiveValidator
- type Constraints
- type ConstraintsBuilder
- func (b *ConstraintsBuilder) Build() Constraints
- func (b *ConstraintsBuilder) WithAcceptedTypes(types []string) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithAllowedExtensions(exts []string) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithBlockedExtensions(exts []string) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithDangerousChars(chars []string) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithFileNameRegex(pattern *regexp.Regexp) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithMaxFileSize(size int64) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithMaxNameLength(length int) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithMinFileSize(size int64) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithRequireExtension(require bool) *ConstraintsBuilder
- func (b *ConstraintsBuilder) WithStrictMIMETypeValidation(strict bool) *ConstraintsBuilder
- type ContentValidator
- type ContentValidatorRegistry
- type FileValidator
- func (v *FileValidator) GetConstraints() Constraints
- func (v *FileValidator) Validate(file *multipart.FileHeader) error
- func (v *FileValidator) ValidateBytes(content []byte, filename string) error
- func (v *FileValidator) ValidateReader(reader io.Reader, filename string, size int64) error
- func (v *FileValidator) ValidateWithContext(ctx context.Context, file *multipart.FileHeader) error
- type ImageValidator
- type MediaTypeGroup
- type PDFValidator
- type ValidationError
- type ValidationErrorType
- type Validator
Constants ¶
const ( KB = int64(1024) MB = KB * 1024 GB = MB * 1024 )
Size constants for easier file size configuration
Variables ¶
This section is empty.
Functions ¶
func AddCustomMediaTypeGroupMapping ¶
func AddCustomMediaTypeGroupMapping(group MediaTypeGroup, mimeTypes []string)
AddCustomMediaTypeGroupMapping adds custom MIME types to a media type group
func AddCustomMediaTypeMapping ¶
AddCustomMediaTypeMapping adds a custom file extension to MIME type mapping
func CreateFileFromBytes ¶
func CreateFileFromBytes(filename string, content []byte) *multipart.FileHeader
CreateFileFromBytes creates a multipart.FileHeader from a byte slice for validation testing
func CreateFileFromReader ¶
CreateFileFromReader creates a multipart.FileHeader from an io.Reader for validation testing
func DetectContentType ¶
DetectContentType detects the content type of a file from its bytes
func DetectContentTypeFromFile ¶
DetectContentTypeFromFile detects the content type of a file from its path
func ExpandAcceptedTypes ¶
ExpandAcceptedTypes takes a slice of accepted types (which can include MediaTypeGroups) and returns a slice with all specific MIME types
func FormatSizeReadable ¶
FormatSizeReadable converts a size in bytes to a human-readable string
func GetErrorMessage ¶
GetErrorMessage returns the message of a ValidationError, or empty string if not a ValidationError
func HasSupportedDocumentExtension ¶
HasSupportedDocumentExtension checks if a filename has a supported document extension
func HasSupportedImageExtension ¶
HasSupportedImageExtension checks if a filename has a supported image extension
func IsDocument ¶
IsDocument checks if a content type is a common document format
func IsErrorOfType ¶
func IsErrorOfType(err error, errType ValidationErrorType) bool
IsErrorOfType checks if an error is a ValidationError of the specified type
func IsValidationError ¶
IsValidationError checks if an error is a ValidationError
func MIMETypeForExtension ¶
MIMETypeForExtension returns the MIME type for a given file extension Returns empty string if the extension is not recognized
func StreamValidate ¶
StreamValidate validates a stream of bytes as they're read This is useful for validating large files without reading them entirely into memory
func ValidateLocalFile ¶
ValidateLocalFile validates a local file path against the validator's constraints
Types ¶
type ArchiveValidator ¶ added in v0.0.4
type ArchiveValidator struct {
MaxCompressionRatio float64
MaxFiles int
MaxDepth int
MaxUncompressedSize int64
MaxNestedArchives int
ArchiveExtensions []string
}
ArchiveValidator validates archive files to prevent zip bombs and other malicious archives
func DefaultArchiveValidator ¶ added in v0.0.4
func DefaultArchiveValidator() *ArchiveValidator
DefaultArchiveValidator creates an archive validator with sensible defaults
func (*ArchiveValidator) SupportedMIMETypes ¶ added in v0.0.4
func (v *ArchiveValidator) SupportedMIMETypes() []string
SupportedMIMETypes returns the MIME types this validator can handle
func (*ArchiveValidator) ValidateContent ¶ added in v0.0.4
func (v *ArchiveValidator) ValidateContent(reader io.Reader, size int64) error
ValidateContent validates the content of an archive file
type Constraints ¶
type Constraints struct {
// MaxFileSize is the maximum allowed file size in bytes
// Use the provided constants for readable configuration, e.g., 10 * MB for 10 megabytes
MaxFileSize int64
// MinFileSize is the minimum allowed file size in bytes
// Use the provided constants for readable configuration, e.g., 1 * KB for 1 kilobyte
MinFileSize int64
// AcceptedTypes is a list of allowed MIME types (e.g., "image/jpeg", "application/pdf")
// Special media type groups like "image/*" are also supported
AcceptedTypes []string
// AllowedExts is a list of allowed file extensions including the dot (e.g., ".jpg", ".pdf")
// If empty, all extensions are allowed unless blocked by BlockedExts
AllowedExts []string
// BlockedExts is a list of blocked file extensions including the dot (e.g., ".exe", ".php")
// These extensions will be blocked regardless of AllowedExts configuration
BlockedExts []string
// MaxNameLength is the maximum allowed length for filenames (including extension)
// If set to 0, no length limit will be enforced
MaxNameLength int
// FileNameRegex is an optional regular expression pattern for validating filenames
// If nil, no pattern matching will be performed
FileNameRegex *regexp.Regexp
// DangerousChars is a list of characters considered dangerous in filenames
DangerousChars []string
// RequireExtension enforces that files must have an extension
RequireExtension bool
// StrictMIMETypeValidation requires that both the MIME type and extension match
StrictMIMETypeValidation bool
// ContentValidationEnabled enables deep content validation
ContentValidationEnabled bool
// RequireContentValidation makes content validation mandatory
RequireContentValidation bool
// ContentValidatorRegistry holds content validators for different file types
ContentValidatorRegistry *ContentValidatorRegistry
}
Constraints defines the configuration for file validation
func DefaultConstraints ¶
func DefaultConstraints() Constraints
DefaultConstraints creates a new set of constraints with sensible defaults
func DocumentOnlyConstraints ¶
func DocumentOnlyConstraints() Constraints
DocumentOnlyConstraints creates constraints that only allow document files with sensible defaults
func ImageOnlyConstraints ¶
func ImageOnlyConstraints() Constraints
ImageOnlyConstraints creates constraints that only allow image files with sensible defaults
func MediaOnlyConstraints ¶
func MediaOnlyConstraints() Constraints
MediaOnlyConstraints creates constraints that only allow media files with sensible defaults
type ConstraintsBuilder ¶
type ConstraintsBuilder struct {
// contains filtered or unexported fields
}
ConstraintsBuilder is a builder for creating validation constraints
func NewConstraintsBuilder ¶
func NewConstraintsBuilder() *ConstraintsBuilder
NewConstraintsBuilder creates a new constraints builder starting with default constraints
func (*ConstraintsBuilder) Build ¶
func (b *ConstraintsBuilder) Build() Constraints
Build returns the built constraints
func (*ConstraintsBuilder) WithAcceptedTypes ¶
func (b *ConstraintsBuilder) WithAcceptedTypes(types []string) *ConstraintsBuilder
WithAcceptedTypes sets the accepted MIME types
func (*ConstraintsBuilder) WithAllowedExtensions ¶
func (b *ConstraintsBuilder) WithAllowedExtensions(exts []string) *ConstraintsBuilder
WithAllowedExtensions sets the allowed file extensions
func (*ConstraintsBuilder) WithBlockedExtensions ¶
func (b *ConstraintsBuilder) WithBlockedExtensions(exts []string) *ConstraintsBuilder
WithBlockedExtensions sets the blocked file extensions
func (*ConstraintsBuilder) WithDangerousChars ¶
func (b *ConstraintsBuilder) WithDangerousChars(chars []string) *ConstraintsBuilder
WithDangerousChars sets the dangerous characters list
func (*ConstraintsBuilder) WithFileNameRegex ¶
func (b *ConstraintsBuilder) WithFileNameRegex(pattern *regexp.Regexp) *ConstraintsBuilder
WithFileNameRegex sets the filename regex pattern
func (*ConstraintsBuilder) WithMaxFileSize ¶
func (b *ConstraintsBuilder) WithMaxFileSize(size int64) *ConstraintsBuilder
WithMaxFileSize sets the maximum file size
func (*ConstraintsBuilder) WithMaxNameLength ¶
func (b *ConstraintsBuilder) WithMaxNameLength(length int) *ConstraintsBuilder
WithMaxNameLength sets the maximum filename length
func (*ConstraintsBuilder) WithMinFileSize ¶
func (b *ConstraintsBuilder) WithMinFileSize(size int64) *ConstraintsBuilder
WithMinFileSize sets the minimum file size
func (*ConstraintsBuilder) WithRequireExtension ¶
func (b *ConstraintsBuilder) WithRequireExtension(require bool) *ConstraintsBuilder
WithRequireExtension sets whether an extension is required
func (*ConstraintsBuilder) WithStrictMIMETypeValidation ¶
func (b *ConstraintsBuilder) WithStrictMIMETypeValidation(strict bool) *ConstraintsBuilder
WithStrictMIMETypeValidation sets whether strict MIME type validation is required
type ContentValidator ¶ added in v0.0.4
type ContentValidator interface {
// ValidateContent validates the content of a file
ValidateContent(reader io.Reader, size int64) error
// SupportedMIMETypes returns the MIME types this validator can handle
SupportedMIMETypes() []string
}
ContentValidator is an interface for validating file contents beyond MIME type
type ContentValidatorRegistry ¶ added in v0.0.4
type ContentValidatorRegistry struct {
// contains filtered or unexported fields
}
ContentValidatorRegistry manages content validators for different file types
func NewContentValidatorRegistry ¶ added in v0.0.4
func NewContentValidatorRegistry() *ContentValidatorRegistry
NewContentValidatorRegistry creates a new content validator registry
func (*ContentValidatorRegistry) GetValidator ¶ added in v0.0.4
func (r *ContentValidatorRegistry) GetValidator(mimeType string) ContentValidator
GetValidator returns the validator for a given MIME type
func (*ContentValidatorRegistry) Register ¶ added in v0.0.4
func (r *ContentValidatorRegistry) Register(mimeType string, validator ContentValidator)
Register registers a content validator for specific MIME types
func (*ContentValidatorRegistry) ValidateContent ¶ added in v0.0.4
func (r *ContentValidatorRegistry) ValidateContent(mimeType string, reader io.Reader, size int64) error
ValidateContent validates content using the appropriate validator
type FileValidator ¶
type FileValidator struct {
// contains filtered or unexported fields
}
FileValidator implements the Validator interface
func New ¶
func New(constraints Constraints) *FileValidator
New creates a new file validator with the given constraints
func NewDefault ¶
func NewDefault() *FileValidator
NewDefault creates a new file validator with sensible default constraints
func (*FileValidator) GetConstraints ¶
func (v *FileValidator) GetConstraints() Constraints
GetConstraints returns the current validation constraints
func (*FileValidator) Validate ¶
func (v *FileValidator) Validate(file *multipart.FileHeader) error
Validate validates a file against the validator's constraints
func (*FileValidator) ValidateBytes ¶
func (v *FileValidator) ValidateBytes(content []byte, filename string) error
ValidateBytes validates a file from a byte slice with a filename
func (*FileValidator) ValidateReader ¶
ValidateReader validates a file from an io.Reader with a filename
func (*FileValidator) ValidateWithContext ¶
func (v *FileValidator) ValidateWithContext(ctx context.Context, file *multipart.FileHeader) error
ValidateWithContext validates a file with context for potential cancellation
type ImageValidator ¶ added in v0.0.4
type ImageValidator struct {
MaxWidth int
MaxHeight int
MaxPixels int
MinWidth int
MinHeight int
ValidatePixels bool
AllowSVG bool
MaxSVGSize int64
}
ImageValidator validates image files for malicious content and reasonable dimensions
func DefaultImageValidator ¶ added in v0.0.4
func DefaultImageValidator() *ImageValidator
DefaultImageValidator creates an image validator with sensible defaults
func (*ImageValidator) SupportedMIMETypes ¶ added in v0.0.4
func (v *ImageValidator) SupportedMIMETypes() []string
SupportedMIMETypes returns the MIME types this validator can handle
func (*ImageValidator) ValidateContent ¶ added in v0.0.4
func (v *ImageValidator) ValidateContent(reader io.Reader, size int64) error
ValidateContent validates the content of an image file
type MediaTypeGroup ¶
type MediaTypeGroup string
MediaTypeGroup defines a categorization of MIME types
const ( AllowAllImages MediaTypeGroup = "image/*" AllowAllDocuments MediaTypeGroup = "document/*" AllowAllAudio MediaTypeGroup = "audio/*" AllowAllVideo MediaTypeGroup = "video/*" AllowAllText MediaTypeGroup = "text/*" AllowAll MediaTypeGroup = "*/*" )
type PDFValidator ¶ added in v0.0.4
type PDFValidator struct {
AllowJavaScript bool
AllowEmbeddedFiles bool
AllowForms bool
AllowActions bool
MaxSize int64
ValidateStructure bool
}
PDFValidator validates PDF files for malicious content
func DefaultPDFValidator ¶ added in v0.0.4
func DefaultPDFValidator() *PDFValidator
DefaultPDFValidator creates a PDF validator with secure defaults
func (*PDFValidator) SupportedMIMETypes ¶ added in v0.0.4
func (v *PDFValidator) SupportedMIMETypes() []string
SupportedMIMETypes returns the MIME types this validator can handle
func (*PDFValidator) ValidateContent ¶ added in v0.0.4
func (v *PDFValidator) ValidateContent(reader io.Reader, size int64) error
ValidateContent validates the content of a PDF file
type ValidationError ¶
type ValidationError struct {
Type ValidationErrorType
Message string
}
ValidationError represents a custom error for file validation
func NewValidationError ¶
func NewValidationError(errType ValidationErrorType, message string) *ValidationError
NewValidationError creates a new ValidationError
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface
type ValidationErrorType ¶
type ValidationErrorType string
ValidationErrorType represents different types of validation errors
const ( ErrorTypeSize ValidationErrorType = "size" ErrorTypeMIME ValidationErrorType = "mime" ErrorTypeFileName ValidationErrorType = "filename" ErrorTypeExtension ValidationErrorType = "extension" ErrorTypeContent ValidationErrorType = "content" )
func GetErrorType ¶
func GetErrorType(err error) ValidationErrorType
GetErrorType returns the type of a ValidationError, or empty string if not a ValidationError
type Validator ¶
type Validator interface {
// Validate validates a file against the validator's constraints
Validate(file *multipart.FileHeader) error
// ValidateWithContext validates a file with context for potential cancellation
ValidateWithContext(ctx context.Context, file *multipart.FileHeader) error
// ValidateReader validates a file from an io.Reader with a filename
ValidateReader(reader io.Reader, filename string, size int64) error
// ValidateBytes validates a file from a byte slice with a filename
ValidateBytes(content []byte, filename string) error
// GetConstraints returns the current validation constraints
GetConstraints() Constraints
}
Validator provides the main interface for validating files