service

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 38 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ParamsType  = "params"
	FormsType   = "forms"
	HeadersType = "headers"
	QueryType   = "query"
)

Variables

View Source
var (
	ErrNoToken           = errors.New("no token provided")
	ErrInvalidAuthFormat = errors.New("invalid authorization format")
	ErrInvalidToken      = errors.New("invalid token")
)

Auth failures are deliberately coarse: the caller learns that the credential was not accepted and nothing about which part of it failed.

Functions

func ApplyImagickResourceLimits added in v1.7.0

func ApplyImagickResourceLimits()

ApplyImagickResourceLimits sets process-wide ImageMagick resource limits so a decompression bomb or an oversized resize target cannot exhaust host memory, disk or CPU. MagickSetResourceLimit is global despite hanging off a wand. Must be called once after imagick.Initialize(). Defaults are generous enough that no legitimate stored image starts failing; when a limit is exceeded the resize paths already fall back to serving the original bytes.

Unit note: the C API takes bytes for MEMORY/MAP/DISK, pixels for AREA and seconds for TIME. We log the effective values so they can be eyeballed on the first boot.

func BearerToken added in v1.8.0

func BearerToken(c *fiber.Ctx) (string, error)

BearerToken extracts the raw bearer credential from the Authorization header.

func ByteToStream

func ByteToStream(data []byte) io.Reader

func CheckToken

func CheckToken(c *fiber.Ctx) error

CheckToken authenticates a request against the general TOKEN only. A bucket-scoped token is rejected here, which is what gates the operator routes (/aws, /minio, /monitor, /metrics): those act on any bucket or expose service-wide data, so a credential limited to a single bucket must not reach them. Bucket-aware routes use ResolvePrincipal instead.

func CreateFile

func CreateFile(file []byte) (*os.File, error)

func DownloadFile

func DownloadFile(filepath string, url string) error

func GetWidthAndHeight

func GetWidthAndHeight(c *fiber.Ctx, requestType string) (bool, uint, uint)

func HasUnsafeObjectKey added in v1.7.0

func HasUnsafeObjectKey(key string) bool

HasUnsafeObjectKey reports whether an object key is empty or contains a ".." path segment. Object stores treat keys opaquely, but rejecting traversal-like segments keeps read/delete keys aligned with the sanitized keys upload writes and avoids surprises if a key is ever mapped onto a filesystem path.

func ImageToByte

func ImageToByte(img string) []byte

func IsImageFile

func IsImageFile(filename string) bool

func IsInt

func IsInt(one, two string) bool

func MinioClient

func MinioClient() *minio.Client

func RandomName

func RandomName(length int) string

func RatioWidthHeight

func RatioWidthHeight(width, height, targetWidth, targetHeight uint) (uint, uint)

func ReadEnvAndSet added in v1.2.2

func ReadEnvAndSet() error

func Response

func Response(c *fiber.Ctx, code int, success bool, message string, data any) error

func SanitizeObjectName added in v1.6.4

func SanitizeObjectName(objectName string) string

SanitizeObjectName removes or replaces unsupported characters for MinIO object names

func SetWidthToHeight

func SetWidthToHeight(width, height string) (string, string)

func StorePrincipal added in v1.8.0

func StorePrincipal(c *fiber.Ctx, p Principal)

StorePrincipal records p on the request context for downstream handlers.

func StreamToByte

func StreamToByte(stream io.Reader) []byte

func TokenValid added in v1.7.0

func TokenValid(clientToken string) bool

TokenValid reports whether clientToken matches the configured server TOKEN using a constant-time comparison. An empty token on either side is never valid (an empty server token must not authenticate an empty client token). Use this where the token arrives outside the Authorization header, e.g. a WebSocket query parameter that browsers cannot set as a header.

Types

type AwsService

type AwsService interface {
	GlacierVaultList() *glacier.ListVaultsOutput
	GlacierUploadArchive(vaultName string, fileBuffer []byte) (*glacier.UploadArchiveOutput, error)
	GlacierInitiateRetrieval(vaultName, archiveId string, retrievalType string) (*glacier.InitiateJobOutput, error)
	GlacierListJobs(vaultName string) (*glacier.ListJobsOutput, error)
	GlacierGetJobOutput(vaultName, jobId string) (*glacier.GetJobOutputOutput, error)
	GlacierDescribeJob(vaultName, jobId string) (*glacier.DescribeJobOutput, error)
	GlacierInventoryRetrieval(vaultName string) (*glacier.InitiateJobOutput, error)
	GlacierDownloadToMinio(vaultName, jobId, targetBucket, targetPath string) error
	GlacierDownloadToLocal(vaultName, jobId, localPath string) error
	S3PutObject(bucketName string, objectName string, fileBuffer io.Reader) (*manager.UploadOutput, error)
	ListBuckets() ([]s3types.Bucket, error)
	BucketExists(bucketName string) bool
	DeleteObjects(bucketName string, objectKeys []string) error
	IsConnected() bool
}

func NewAwsService

func NewAwsService() AwsService

type CacheService added in v1.5.0

type CacheService interface {
	Get(key string) ([]byte, error)
	Set(key string, value []byte, expiration time.Duration) error
	Delete(key string) error
	GetResizedImage(bucket, path string, width, height uint) ([]byte, error)
	SetResizedImage(bucket, path string, width, height uint, data []byte) error
	FlushAll() error
	Close() error
}

func NewCacheService added in v1.5.0

func NewCacheService() (CacheService, error)

type ImageService added in v1.5.0

type ImageService struct {
	MinioClient *minio.Client
}

func (*ImageService) GetImage added in v1.5.0

func (s *ImageService) GetImage(bucket, objectName string, width, height int) ([]byte, error)

GetImage gets an image from storage and optionally resizes it

func (*ImageService) GetImageInfo added in v1.5.0

func (s *ImageService) GetImageInfo(data []byte) (width uint, height uint, format string, err error)

GetImageInfo returns width, height and format of an image

func (*ImageService) ImagickFormat added in v1.5.0

func (s *ImageService) ImagickFormat(image []byte) (error, string)

func (*ImageService) ImagickGetWidthHeight added in v1.5.0

func (s *ImageService) ImagickGetWidthHeight(image []byte) (error, uint, uint)

func (*ImageService) ImagickResize added in v1.5.0

func (s *ImageService) ImagickResize(image []byte, targetWidth, targetHeight uint) []byte

func (*ImageService) IsImageFile added in v1.5.0

func (s *ImageService) IsImageFile(data []byte) bool

IsImageFile checks if the file is a valid image by examining its content (magic bytes)

func (*ImageService) IsResizable added in v1.5.0

func (s *ImageService) IsResizable(data []byte) bool

IsResizable checks if the file is a valid image that can be resized

func (*ImageService) OptimizeImage added in v1.7.0

func (s *ImageService) OptimizeImage(data []byte, opts OptimizeOptions) ([]byte, uint, uint, error)

OptimizeImage re-encodes a resizable raster image in a single decode/encode pass: optional downscale (explicit target dims win over MaxDimension), metadata strip, and per-format quality. It returns the encoded bytes and the final dimensions.

Inputs that are not resizable rasters (per IsResizable) and animated-capable GIFs are returned unchanged with a nil error, so callers can treat any success as "safe to store". GIF is passed through because a single-frame resize would flatten animations.

func (*ImageService) ProcessImage added in v1.5.0

func (s *ImageService) ProcessImage(data []byte) ([]byte, error)

ProcessImage processes an image (resize, optimize, etc.). Retained for backward compatibility; it is a thin wrapper over OptimizeImage with the original caps and per-format quality values.

func (*ImageService) ResizeImage added in v1.5.0

func (s *ImageService) ResizeImage(data []byte, width, height int) ([]byte, error)

ResizeImage resizes an image to the specified dimensions

type OptimizeOptions added in v1.7.0

type OptimizeOptions struct {
	MaxDimension uint // cap on the longest side; 0 = no cap
	TargetWidth  uint // explicit dimensions; when either is set they override MaxDimension
	TargetHeight uint
	JPEGQuality  uint
	PNGQuality   uint // lossless: ImageMagick maps PNG "quality" to zlib level/filter
	WebPQuality  uint
	Strip        bool // remove metadata (EXIF/ICC/etc.)
}

OptimizeOptions controls a single-pass re-encode used to shrink an uploaded image without visible quality loss.

func DefaultOptimizeOptions added in v1.7.0

func DefaultOptimizeOptions() OptimizeOptions

DefaultOptimizeOptions builds the opt-in upload optimization options from the OPTIMIZE_* environment variables, falling back to visually-lossless defaults.

type Principal added in v1.8.0

type Principal struct {
	// Scoped is true when the caller presented a bucket-scoped token. The general
	// TOKEN yields the zero Principal, which is not restricted to one bucket.
	Scoped bool
	// Bucket is the single bucket a scoped principal may write to. Empty when
	// Scoped is false.
	Bucket string
}

Principal is the identity behind an authenticated request.

func PrincipalFrom added in v1.8.0

func PrincipalFrom(c *fiber.Ctx) Principal

PrincipalFrom returns the principal stored by the auth middleware. A missing principal yields the zero value, i.e. the unrestricted general token, so a route wired without the bucket-aware middleware keeps its previous behaviour.

func ResolvePrincipal added in v1.8.0

func ResolvePrincipal(c *fiber.Ctx) (Principal, error)

ResolvePrincipal authenticates a request against either the general TOKEN or a bucket-scoped token.

Order matters. The general TOKEN is compared first and as a whole string, because a general token is free to contain a ':' and must never be reinterpreted as a "<bucket>:<secret>" pair. Parsing first would break every existing deployment whose TOKEN happens to contain a colon.

For a bucket-scoped token the bucket prefix is attacker-controlled input and grants nothing on its own: the secret is compared, in constant time, against the entry for that exact bucket and no other.

type StatsService added in v1.5.0

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

func NewStatsService added in v1.5.0

func NewStatsService() *StatsService

func (*StatsService) AddUploadBytes added in v1.5.0

func (s *StatsService) AddUploadBytes(bytes int64)

func (*StatsService) DecrementActiveUploads added in v1.5.0

func (s *StatsService) DecrementActiveUploads()

func (*StatsService) GetActiveUploads added in v1.5.0

func (s *StatsService) GetActiveUploads() int

func (*StatsService) GetCPUUsage added in v1.5.0

func (s *StatsService) GetCPUUsage() float64

func (*StatsService) GetCacheHitRate added in v1.5.0

func (s *StatsService) GetCacheHitRate() float64

func (*StatsService) GetDiskUsage added in v1.5.0

func (s *StatsService) GetDiskUsage() map[string]int64

func (*StatsService) GetMemoryUsage added in v1.5.0

func (s *StatsService) GetMemoryUsage() float64

func (*StatsService) GetRecentErrors added in v1.5.0

func (s *StatsService) GetRecentErrors() []string

func (*StatsService) GetUploadSpeed added in v1.5.0

func (s *StatsService) GetUploadSpeed() float64

func (*StatsService) IncrementActiveUploads added in v1.5.0

func (s *StatsService) IncrementActiveUploads()

func (*StatsService) IncrementCacheHit added in v1.5.0

func (s *StatsService) IncrementCacheHit()

func (*StatsService) IncrementCacheMiss added in v1.5.0

func (s *StatsService) IncrementCacheMiss()

func (*StatsService) LogError added in v1.5.0

func (s *StatsService) LogError(err string)

Jump to

Keyboard shortcuts

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