utils

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	JSONContentTypes = []string{
		"application/json",
		"application/json; charset=utf-8",
	}

	MultipartContentTypes = []string{
		"multipart/form-data",
	}

	ImageContentTypes = []string{
		"image/jpeg",
		"image/jpg",
		"image/png",
		"image/gif",
		"image/webp",
		"image/svg+xml",
	}

	DocumentContentTypes = []string{
		"application/pdf",
		"application/msword",
		"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
		"application/vnd.ms-excel",
		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		"text/plain",
		"text/csv",
	}

	AllowedAttachmentTypes = append(append([]string{}, ImageContentTypes...), DocumentContentTypes...)
)

Common content type lists

View Source
var ErrInvalidCSRFToken = errors.New("invalid or expired CSRF token")

ErrInvalidCSRFToken indicates an invalid or expired CSRF token

Functions

func BuildSecureHTTPSURL

func BuildSecureHTTPSURL(host, uri string) (string, error)

BuildSecureHTTPSURL safely constructs an HTTPS URL from validated components

func DeleteAuthCookies

func DeleteAuthCookies(c *gin.Context)

DeleteAuthCookies removes all authentication cookies

func DeleteCookie

func DeleteCookie(c *gin.Context, name string, path string, domain string)

DeleteCookie removes a cookie by setting MaxAge to -1

func GenerateEncryptionKey

func GenerateEncryptionKey() (string, error)

GenerateEncryptionKey generates a new random 32-byte key for AES-256 Returns base64-encoded key suitable for environment variable

func GenerateRandomString

func GenerateRandomString(length int) (string, error)

GenerateRandomString generates a random base64 string

func GetBaseURL

func GetBaseURL() string

GetBaseURL returns the base URL for the application from environment

func GetCookie

func GetCookie(c *gin.Context, name string) (string, error)

GetCookie retrieves a cookie value

func IsAllowedDomain

func IsAllowedDomain(urlStr string, allowedDomains []string) (bool, error)

IsAllowedDomain checks if a domain is in the allowed list This should be configured based on your application's needs

func IsValidEmail

func IsValidEmail(email string) bool

func SanitizeFilename

func SanitizeFilename(filename string) (string, error)

SanitizeFilename sanitizes filenames to prevent path traversal

func SanitizeHostHeader

func SanitizeHostHeader(host string) (string, error)

SanitizeHostHeader validates and sanitizes the Host header Prevents host header injection attacks

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput sanitizes user input to prevent XSS

func SanitizeRequestURI

func SanitizeRequestURI(uri string) (string, error)

SanitizeRequestURI validates and sanitizes the request URI Prevents URI injection attacks

func SanitizeSearchQuery

func SanitizeSearchQuery(query string) (string, error)

SanitizeSearchQuery sanitizes search input for SQL LIKE queries Prevents SQL injection and removes dangerous characters

func SetAuthCookies

func SetAuthCookies(c *gin.Context, accessToken, refreshToken, csrfToken string, envMode string)

SetAuthCookies sets access token, refresh token, and CSRF token cookies

func SetSecureCookie

func SetSecureCookie(c *gin.Context, config CookieConfig)

SetSecureCookie sets an HTTP-only, Secure, SameSite cookie

func ValidateAlphanumeric

func ValidateAlphanumeric(value string, maxLength int, allowedChars string, fieldName string) error

ValidateAlphanumeric validates string contains only alphanumeric + allowed chars

func ValidateBooleanParam

func ValidateBooleanParam(value string, fieldName string) (bool, error)

ValidateBooleanParam validates boolean query parameters

func ValidateContentType

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

ValidateContentType checks if content type is in allowed list

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates email format with detailed error

func ValidateEnum

func ValidateEnum(value string, allowedValues []string, fieldName string) error

ValidateEnum validates a string value against a list of allowed values

func ValidateName

func ValidateName(name string) error

ValidateName validates first/last name

func ValidatePaginationParams

func ValidatePaginationParams(limitStr, offsetStr string) (limit, offset int, err error)

ValidatePaginationParams validates and sanitizes limit/offset parameters Returns sanitized values with defaults and bounds checking

func ValidatePassword

func ValidatePassword(password string, policy PasswordPolicy) error

ValidatePassword validates a password against the policy

func ValidateProvider

func ValidateProvider(provider string) error

ValidateProvider validates SMTP provider name against whitelist

func ValidateRedirectURL

func ValidateRedirectURL(urlStr string) error

ValidateRedirectURL validates that a URL is safe to redirect to Prevents open redirect vulnerabilities

func ValidateStatus

func ValidateStatus(status string) error

ValidateStatus validates email/service status against allowed values

func ValidateStringLength

func ValidateStringLength(value string, minLength, maxLength int, fieldName string) error

ValidateStringLength validates string length constraints

func ValidateTagsList

func ValidateTagsList(tagsStr string) ([]string, error)

ValidateTagsList validates comma-separated tags Returns cleaned array of tags

func ValidateTrackingID

func ValidateTrackingID(id string) error

ValidateTrackingID validates tracking pixel/link IDs Should be alphanumeric with hyphens and underscores, reasonable length

Types

type CSRFService

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

CSRFService manages CSRF tokens (GAP-SEC-014)

func GetCSRFService

func GetCSRFService() *CSRFService

GetCSRFService returns the singleton CSRF service instance

func (*CSRFService) DeleteToken

func (s *CSRFService) DeleteToken(token string)

DeleteToken removes a CSRF token (e.g., on logout)

func (*CSRFService) GenerateToken

func (s *CSRFService) GenerateToken(userID uuid.UUID) (string, error)

GenerateToken creates a new CSRF token for a user

func (*CSRFService) RefreshToken

func (s *CSRFService) RefreshToken(token string) error

RefreshToken extends the expiration of an existing token

func (*CSRFService) ValidateToken

func (s *CSRFService) ValidateToken(token string, userID uuid.UUID) error

ValidateToken validates a CSRF token for a user

type CSRFToken

type CSRFToken struct {
	Token     string
	UserID    uuid.UUID
	ExpiresAt time.Time
}

CSRFToken represents a CSRF token with metadata

type CookieConfig

type CookieConfig struct {
	Name     string
	Value    string
	MaxAge   int
	Path     string
	Domain   string
	Secure   bool   // Only send over HTTPS
	HttpOnly bool   // Not accessible via JavaScript
	SameSite string // "Strict", "Lax", or "None"
}

CookieConfig holds cookie configuration (GAP-SEC-014)

type CustomValidator

type CustomValidator struct {
	Validator *validator.Validate
}

CustomValidator holds custom validation functions

func NewCustomValidator

func NewCustomValidator() *CustomValidator

NewCustomValidator creates a new validator with custom rules

type EncryptionService

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

EncryptionService handles encryption and decryption of sensitive data

func NewEncryptionService

func NewEncryptionService() (*EncryptionService, error)

NewEncryptionService creates a new encryption service Uses the ENCRYPTION_KEY from environment (32 bytes for AES-256)

func (*EncryptionService) Decrypt

func (e *EncryptionService) Decrypt(ciphertext string) (string, error)

Decrypt decrypts base64-encoded ciphertext using AES-256-GCM

func (*EncryptionService) Encrypt

func (e *EncryptionService) Encrypt(plaintext string) (string, error)

Encrypt encrypts plaintext using AES-256-GCM Returns base64-encoded ciphertext (nonce + encrypted data)

type PasswordPolicy

type PasswordPolicy struct {
	MinLength      int
	RequireUpper   bool
	RequireLower   bool
	RequireNumber  bool
	RequireSpecial bool
}

PasswordPolicy defines password requirements

func DefaultPasswordPolicy

func DefaultPasswordPolicy() PasswordPolicy

DefaultPasswordPolicy returns SOC 2 compliant password policy

Jump to

Keyboard shortcuts

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