CADDY_FILE_SERVER

package module
v0.0.0-...-f8ae9fb Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2024 License: MIT Imports: 21 Imported by: 0

README

Build Static Releases Build Docker

Caddy Image Processor

This repository contains a CaddyServer module for processing images on the fly using libvips.

Features

  • Automatic image processing based on URL query parameters
  • Supports resizing, rotating, cropping, quality adjustments, format conversion, and more
  • Efficient processing using libvips

Prerequisites

  • libvips installed on your system
  • libvips-dev installed on your system (only for xcaddy build)

Installation and Configuration

Using Docker
  • Pull the Docker image from the GitHub Container Registry:
    docker pull ghcr.io/quix-labs/caddy-image-processor:latest
    
Using xcaddy
  • Before building the module, ensure you have xcaddy installed on your system. You can install it using the following command:

    go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
    
  • To build this module into Caddy, run the following command:

    CGO_ENABLED=1 xcaddy build --with github.com/quix-labs/caddy-image-processor
    

    This command compiles Caddy with the image processing module included.

Using prebuilt assets
  • You can also install the tool using release assets.

    Download the appropriate package from the Releases page, and then follow the instructions provided for your specific platform.

Usage

Using Docker
docker run -p 80:80 -v $PWD/Caddyfile:/etc/caddy/Caddyfile -d ghcr.io/quix-labs/caddy-image-processor:latest

Your can see more information in the official docker documentation for caddy

Using xcaddy build / prebuilt assets
/path/to/your/caddy run --config /etc/caddy/Caddyfile

Your can see more information in the official documentation for caddy

Example Caddyfile

Using file_server
localhost {
    root /your-images-directory
    file_server
    image_processor
}
Using reverse_proxy
localhost {
    reverse_proxy your-domain.com
    image_processor
}

In this example, all requests undergo processing by the image processor module before being served by the caddy.

Available Query Parameters

Param Name Description Type
h Height Image height Integer
w Width Image width Integer
ah AreaHeight Area height Integer
aw AreaWidth Area width Integer
t Top Y-coordinate of the top-left corner Integer
l Left X-coordinate of the top-left corner Integer
q Quality Image quality (JPEG compression) Integer (default 75)
cp Compression Compression level (0-9, 0 = lossless) Integer
z Zoom Zoom level Integer
crop Crop Whether cropping is enabled Boolean
en Enlarge Whether enlargement is enabled Boolean
em Embed Whether embedding is enabled Boolean
flip Flip Whether vertical flipping is enabled Boolean
flop Flop Whether horizontal flipping is enabled Boolean
force Force Whether to force action Boolean
nar NoAutoRotate Whether auto-rotation is disabled Boolean
np NoProfile Whether profile is disabled Boolean
itl Interlace Whether interlacing is enabled Boolean (default true)
smd StripMetadata Whether to strip metadata Boolean (default true)
tr Trim Whether trimming is enabled Boolean
ll Lossless Whether compression is lossless Boolean
th Threshold Color threshold Float
g Gamma Gamma correction Float
br Brightness Brightness Float
c Contrast Contrast Float
r Rotate Rotation angle (45, 90, 135, 180, 235, 270, 315) Integer
b GaussianBlur Gaussian blur level Integer
bg Background Background color (white, black, red, magenta, blue, cyan, green, yellow, or hexadecimal format #RRGGBB) Color
fm Type Image type (jpg, png, gif, webp, avif) Image Type (default original)

Examples

Advanced Configuration

This configuration allows you to control error handling with on_fail and on_security_fail.

You can also manage query parameter processing using allowed_params and disallowed_params.

This gives you fine-grained control over image processing in your Caddy server.

Example with on_fail and Security Configuration
localhost:80 {
    root test-dataset
    file_server
	
    image_processor {
	    
        # Serve original image if image in unprocessable
        on_fail bypass	    
        
        # Return 500 Internal Server Error if processing fails
        # on_fail abort	    
        
        security {

            # Use ignore to remove param from processing, all valid param are processed
            on_security_fail ignore

            # Use abort to return 400 Bad Request when fails
            # on_security_fail abort

            # Use bypass to serve original image without processing
            # on_security_fail bypass

            # Explicitely disable rotate capabilities
            disallowed_params r
            
            # As an alternative use this to only accept width and height processing 
            # allowed_params w h 
            
            constraints {
                h range 60 480

                w {
                    values 60 130 240 480 637

                    # Shortcut range 60 637
                    range {
                        from 60
                        to 637
                    }
                }
            }
        }
    }
}
Explanation:
  • on_fail:

    • bypass (default value): If any error occurs, the original, unprocessed image will be returned.
    • abort: If an error occurs, a 500 Internal Server Error response will be returned.
  • on_security_fail:

    • ignore (default value): If any security checks fail, they are ignored, and the image processing continues.
    • bypass: If any security checks fail, the original, unprocessed image will be returned.
    • abort: If any security checks fail, a 400 Bad Request response will be returned.
  • Security Configuration (disallowed_params vs allowed_params):

    • disallowed_params: Specifies which query parameters are not allowed.

      For example, parameters like w (width) and r (rotation) can be restricted.

    • allowed_params: Specify which query parameters are allowed. As an alternative to disallowed_params.

    • Important: You cannot use both allowed_params and disallowed_params in the same configuration.

    • constraints: You san specify constraints for each parameter (see example)

Planned Features

The following features are planned for future implementation:

  • Sharp compliance: fit,...

Development

To contribute to the development of Caddy Image Processor, follow these steps:

  1. Make sure you have Go installed on your system.

  2. Clone this repository to your local machine:

    git clone https://github.com/quix-labs/caddy-image-processor.git
    
  3. Navigate to the project directory:

  4. Install xcaddy if you haven't already:

    go get -u github.com/caddyserver/xcaddy/cmd/xcaddy
    
  5. Make your changes in the source code.

  6. Run tests to ensure your changes haven't introduced any issues:

    make test
    
  7. If tests pass, you can build the project:

    make build
    
  8. To run the project in development mode, use the following command:

    make run
    
  9. Once you're satisfied with your changes, create a pull request to the main branch of the repository for review.

Credits

License

The MIT License (MIT). Please see License File for more information.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BypassRequestError = errors.New("bypass request")

Functions

func RegisterConstraintType

func RegisterConstraintType(factory func() Constraint)

Types

type AbortRequestError

type AbortRequestError struct {
	Msg string
}

func (*AbortRequestError) Error

func (e *AbortRequestError) Error() string

type Constraint

type Constraint interface {
	Validate(param string) error
	ValidateParam(param string, value string) error
	UnmarshalCaddyfile(d *caddyfile.Dispenser) error
	ID() string
}

type Constraints

type Constraints map[string][]Constraint

Constraints represent constraints as {params:[{type:..., customConfig..}]}

func (*Constraints) MarshalJSON

func (cs *Constraints) MarshalJSON() ([]byte, error)

MarshalJSON serializes Constraints to JSON, adding a `type` field to each entry.

func (*Constraints) ProcessRequestForm

func (cs *Constraints) ProcessRequestForm(form *url.Values, onSecurityFail OnSecurityFail) error

func (*Constraints) UnmarshalCaddyfile

func (cs *Constraints) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*Constraints) UnmarshalJSON

func (cs *Constraints) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes JSON into Constraints, dynamically instantiating types using the registry.

func (*Constraints) Validate

func (cs *Constraints) Validate() error

type Middleware

type Middleware struct {
	OnFail   OnFail           `json:"on_fail,omitempty"`
	Security *SecurityOptions `json:"security,omitempty"`
	// contains filtered or unexported fields
}

Middleware allow user to do image processing on the fly using libvips With simple queries parameters you can resize, convert, crop your served images

func (*Middleware) CaddyModule

func (*Middleware) CaddyModule() caddy.ModuleInfo

func (*Middleware) Provision

func (m *Middleware) Provision(ctx caddy.Context) error

func (*Middleware) ServeHTTP

func (m *Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error

func (*Middleware) UnmarshalCaddyfile

func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*Middleware) Validate

func (m *Middleware) Validate() error

type OnFail

type OnFail string

OnFail represents the possible values for the "on_fail" directive.

const (
	// OnFailAbort returns a 500 Internal Server Error to the client.
	OnFailAbort OnFail = "abort"

	// OnFailBypass forces the response to return the initial (unprocessed) image.
	OnFailBypass OnFail = "bypass"
)

type OnSecurityFail

type OnSecurityFail string
const (
	// OnSecurityFailIgnore Deletes invalid parameters from the request but continues processing.
	OnSecurityFailIgnore OnSecurityFail = "ignore"

	// OnSecurityFailAbort Returns a 400 Bad Request error to the client.
	OnSecurityFailAbort OnSecurityFail = "abort"

	// OnSecurityFailBypass Forces the response to return the initial (unprocessed) image.
	OnSecurityFailBypass OnSecurityFail = "bypass"
)

type RangeConstraint

type RangeConstraint struct {
	From int `json:"from,omitempty"`
	To   int `json:"to,omitempty"`
}

func (*RangeConstraint) ID

func (r *RangeConstraint) ID() string

func (*RangeConstraint) UnmarshalCaddyfile

func (r *RangeConstraint) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*RangeConstraint) Validate

func (r *RangeConstraint) Validate(param string) error

func (*RangeConstraint) ValidateParam

func (r *RangeConstraint) ValidateParam(param string, value string) error

type SecurityOptions

type SecurityOptions struct {
	OnSecurityFail   OnSecurityFail `json:"on_security_fail,omitempty"`
	AllowedParams    *[]string      `json:"allowed_params,omitempty"`
	DisallowedParams *[]string      `json:"disallowed_params,omitempty"`
	Constraints      *Constraints   `json:"constraints,omitempty"`
}

func (*SecurityOptions) ProcessRequestForm

func (s *SecurityOptions) ProcessRequestForm(form *url.Values) error

ProcessRequestForm Ensures that all security constraints are applied. May also remove specific parameters if they are not allowed.

func (*SecurityOptions) Provision

func (s *SecurityOptions) Provision(ctx caddy.Context) error

Provision Set default values if not defined

func (*SecurityOptions) UnmarshalCaddyfile

func (s *SecurityOptions) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*SecurityOptions) Validate

func (s *SecurityOptions) Validate() error

Validate ensure security parameters are correctly defined

type ValuesConstraint

type ValuesConstraint struct {
	Values []int `json:"values"`
}

func (*ValuesConstraint) ID

func (r *ValuesConstraint) ID() string

func (*ValuesConstraint) UnmarshalCaddyfile

func (r *ValuesConstraint) UnmarshalCaddyfile(d *caddyfile.Dispenser) error

func (*ValuesConstraint) Validate

func (r *ValuesConstraint) Validate(param string) error

func (*ValuesConstraint) ValidateParam

func (r *ValuesConstraint) ValidateParam(param string, value string) error

Jump to

Keyboard shortcuts

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