middlewares

package
v0.0.0-...-4b98c26 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2021 License: AGPL-3.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InternetExplorer = "Internet Explorer"
	Edge             = "Edge"
	Firefox          = "Firefox"
	Chrome           = "Chrome"
	Chromium         = "Chromium"
	Opera            = "Opera"
	Safari           = "Safari"
	Android          = "Android"
	Electron         = "Electron"
)

Some constants for the browser names

View Source
const MaxAgeCORS = "43200"

MaxAgeCORS is used to cache the CORS header for 12 hours

Variables

View Source
var (
	// DefaultCSRFConfig is the default CSRF middleware config.
	DefaultCSRFConfig = CSRFConfig{
		Skipper:        middleware.DefaultSkipper,
		TokenLength:    32,
		TokenLookup:    "header:" + echo.HeaderXCSRFToken,
		ContextKey:     "csrf",
		CookieName:     "_csrf",
		CookieMaxAge:   86400,
		CookieSameSite: http.SameSiteLaxMode,
	}
)
View Source
var ErrForbidden = echo.NewHTTPError(http.StatusForbidden)

ErrForbidden is used to send a forbidden response when the request does not have the right permissions.

View Source
var ErrMissingSource = echo.NewHTTPError(http.StatusBadRequest, "No Source in request")

ErrMissingSource is used to send a bad request when the SourceURL is missing from the request

FuncsMap is a the helper functions used in templates. It is filled in web/statik but declared here to avoid circular imports.

Functions

func Accept

func Accept(args ...AcceptOptions) echo.MiddlewareFunc

Accept is a middleware resolving the better content-type offering for the HTTP request, given the `Accept` header and the middleware options.

func AcceptJSON

func AcceptJSON(next echo.HandlerFunc) echo.HandlerFunc

AcceptJSON is an echo middleware that checks that the HTTP Accept header is compatible with application/json

func AcceptedContentType

func AcceptedContentType(c echo.Context) string

AcceptedContentType returns the accepted content-type store from the Accept middleware.

func Allow

func Allow(c echo.Context, v permission.Verb, o permission.Fetcher) error

Allow validates the validable object against the context permission set

func AllowForKonnector

func AllowForKonnector(c echo.Context, slug string) error

AllowForKonnector checks that the permissions is valid and comes from the konnector with the given slug.

func AllowInstallApp

func AllowInstallApp(c echo.Context, appType consts.AppType, sourceURL string, v permission.Verb) error

AllowInstallApp checks that the current context is tied to the store app, which is the only app authorized to install or update other apps. It also allow the cozy-stack apps commands to work (CLI).

func AllowLogout

func AllowLogout(c echo.Context) bool

AllowLogout checks if the current permission allows logging out. all apps can trigger a logout.

func AllowOnFields

func AllowOnFields(c echo.Context, v permission.Verb, o permission.Fetcher, fields ...string) error

AllowOnFields validates the validable object againt the context permission set and ensure the selector validates the given fields.

func AllowTypeAndID

func AllowTypeAndID(c echo.Context, v permission.Verb, doctype, id string) error

AllowTypeAndID validates a type & ID against the context permission set

func AllowVFS

func AllowVFS(c echo.Context, v permission.Verb, o vfs.Fetcher) error

AllowVFS validates a vfs.Fetcher against the context permission set

func AllowWholeType

func AllowWholeType(c echo.Context, v permission.Verb, doctype string) error

AllowWholeType validates that the context permission set can use a verb on the whold doctype

func AppendCSPRule

func AppendCSPRule(c echo.Context, ruleType string, appendedValues ...string)

AppendCSPRule allows to patch inline the CSP headers to add a new rule.

func BasicAuth

func BasicAuth(secretFileName string) echo.MiddlewareFunc

BasicAuth use HTTP basic authentication to authenticate a user. The secret of the user should be stored in a file with the specified name, stored in one of the the config.Paths directories.

The format of the secret is the same as our hashed passwords in database: a scrypt hash with a salt contained in the value.

func BottomNavigationBar

func BottomNavigationBar(c echo.Context) bool

BottomNavigationBar returns true if the navigation bar of the browser is at the bottom of the screen (Firefox Mobile).

func BuildTemplates

func BuildTemplates()

BuildTemplates ensure that the cozy-ui can be injected in templates

func CORS

func CORS(opts CORSOptions) echo.MiddlewareFunc

CORS returns a Cross-Origin Resource Sharing (CORS) middleware. See: https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS

func CSRF

func CSRF() echo.MiddlewareFunc

CSRF returns a Cross-Site Request Forgery (CSRF) middleware. See: https://en.wikipedia.org/wiki/Cross-site_request_forgery

func CSRFWithConfig

func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc

CSRFWithConfig returns a CSRF middleware with config. See `CSRF()`.

func CacheControl

func CacheControl(opts CacheOptions) echo.MiddlewareFunc

CacheControl returns a middleware to handle HTTP caching options.

func CanWriteToAnyDirectory

func CanWriteToAnyDirectory(c echo.Context) error

CanWriteToAnyDirectory checks that the context permission allows to write to a directory on the VFS.

func CheckInstanceBlocked

func CheckInstanceBlocked(next echo.HandlerFunc) echo.HandlerFunc

CheckInstanceBlocked is a middleware that blocks the routing access (for instance if the term-of-services have not been signed and have reach its deadline)

func CheckInstanceDeleting

func CheckInstanceDeleting(next echo.HandlerFunc) echo.HandlerFunc

CheckInstanceDeleting is a middleware that blocks the routing access for instances with the deleting flag set.

func CheckOnboardingNotFinished

func CheckOnboardingNotFinished(next echo.HandlerFunc) echo.HandlerFunc

CheckOnboardingNotFinished checks if there is the instance needs to complete its onboarding

func CheckRegisterToken

func CheckRegisterToken(c echo.Context, i *instance.Instance) bool

CheckRegisterToken returns true if the registerToken is set and match the one from the instance.

func CheckTOSDeadlineExpired

func CheckTOSDeadlineExpired(next echo.HandlerFunc) echo.HandlerFunc

CheckTOSDeadlineExpired checks if there is not signed ToS and the deadline is exceeded

func CheckUserAgent

func CheckUserAgent(next echo.HandlerFunc) echo.HandlerFunc

CheckUserAgent is a middleware that shows an HTML page of error when a browser that is not supported try to load a webapp.

func Compose

func Compose(handler echo.HandlerFunc, mws ...echo.MiddlewareFunc) echo.HandlerFunc

Compose can be used to compose a list of middlewares together with a main handler function. It returns a new handler that should be the composition of all the middlwares with the initial handler.

func ContentTypeJSON

func ContentTypeJSON(next echo.HandlerFunc) echo.HandlerFunc

ContentTypeJSON is an echo middleware that checks that the HTTP Content-Type header is compatible with application/json

func CryptoPolyfill

func CryptoPolyfill(c echo.Context) bool

CryptoPolyfill returns true if the browser can't use its window.crypto API to hash the password with PBKDF2. It is the case for Edge, but also for most browsers in development mode, because this API is only available in secure more (HTTPS or localhost).

func ExtractClaims

func ExtractClaims(c echo.Context, instance *instance.Instance, token string) (*permission.Claims, error)

ExtractClaims parse a JWT, and extracts its claims (if valid).

func Favicon

func Favicon(i *instance.Instance) template.HTML

Favicon returns a helper to insert the favicons in an HTML template.

func GetForOauth

func GetForOauth(instance *instance.Instance, claims *permission.Claims, c interface{}) (*permission.Permission, error)

GetForOauth create a non-persisted permissions doc from a oauth token scopes

func GetInstance

func GetInstance(c echo.Context) *instance.Instance

GetInstance will return the instance linked to the given echo context or panic if none exists

func GetInstanceSafe

func GetInstanceSafe(c echo.Context) (*instance.Instance, bool)

GetInstanceSafe will return the instance linked to the given echo context

func GetOAuthClient

func GetOAuthClient(c echo.Context) (*oauth.Client, bool)

GetOAuthClient returns the OAuth client used for making the HTTP request.

func GetPermission

func GetPermission(c echo.Context) (*permission.Permission, error)

GetPermission extracts the permission from the echo context and checks their validity

func GetRequestToken

func GetRequestToken(c echo.Context) string

GetRequestToken retrieves the token from the incoming request.

func GetSession

func GetSession(c echo.Context) (sess *session.Session, ok bool)

GetSession returns the sessions associated with the given context.

func GetSourceID

func GetSourceID(c echo.Context) (slug string, err error)

GetSourceID returns the sourceID of the permissions associated with the given context.

func HasWebAppToken

func HasWebAppToken(c echo.Context) bool

HasWebAppToken returns true if the request comes from a web app (with a token).

func IsLoggedIn

func IsLoggedIn(c echo.Context) bool

IsLoggedIn returns true if the context has a valid session cookie.

func LoadSession

func LoadSession(next echo.HandlerFunc) echo.HandlerFunc

LoadSession is a middlewares that loads the session and stores it the request context.

func NeedInstance

func NeedInstance(next echo.HandlerFunc) echo.HandlerFunc

NeedInstance is an echo middleware which will display an error if there is no instance.

func ParseJWT

func ParseJWT(c echo.Context, instance *instance.Instance, token string) (*permission.Permission, error)

ParseJWT parses a JSON Web Token, and returns the associated permissions.

func RecoverWithConfig

func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc

RecoverWithConfig returns a Recover middleware with config.

func Secure

func Secure(conf *SecureConfig) echo.MiddlewareFunc

Secure returns a Middlefunc that can be used to define all the necessary secure headers. It is configurable with a SecureConfig object.

func ThemeCSS

func ThemeCSS(i *instance.Instance) template.HTML

ThemeCSS returns an HTML template for inserting the HTML tag for the custom CSS theme

Types

type AcceptOptions

type AcceptOptions struct {
	DefaultContentTypeOffer string
	Offers                  []string
}

AcceptOptions can be used to parameterize the the Accept middleware: the default content-type in case no offer is accepted, and the list of offers to select from.

type CORSOptions

type CORSOptions struct {
	MaxAge         time.Duration
	BlockList      []string
	AllowedMethods []string
}

CORSOptions contains different options to create a CORS middleware.

type CSPSource

type CSPSource int

CSPSource type are the different types of CSP headers sources definitions. Each source type defines a different acess policy.

const (
	// CSPSrcSelf is the 'self' option of a CSP source.
	CSPSrcSelf CSPSource = iota
	// CSPSrcNone is the 'none' option. It denies all domains as an eligible
	// source.
	CSPSrcNone
	// CSPSrcData is the 'data:' option of a CSP source.
	CSPSrcData
	// CSPSrcBlob is the 'blob:' option of a CSP source.
	CSPSrcBlob
	// CSPSrcParent adds the parent domain as an eligible CSP source.
	CSPSrcParent
	// CSPSrcWS adds the parent domain eligible for websocket.
	CSPSrcWS
	// CSPSrcSiblings adds all the siblings subdomains as eligibles CSP
	// sources.
	CSPSrcSiblings
	// CSPSrcAny is the '*' option. It allows any domain as an eligible source.
	CSPSrcAny
	// CSPUnsafeInline is the  'unsafe-inline' option. It allows to have inline
	// styles or scripts to be injected in the page.
	CSPUnsafeInline
	// CSPAllowList inserts a allowList of domains.
	CSPAllowList
)

type CSRFConfig

type CSRFConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// TokenLength is the length of the generated token.
	TokenLength int `yaml:"token_length"`

	// TokenLookup is a string in the form of "<source>:<key>" that is used
	// to extract token from the request.
	// Optional. Default value "header:X-CSRF-Token".
	// Possible values:
	// - "header:<name>"
	// - "form:<name>"
	// - "query:<name>"
	TokenLookup string `yaml:"token_lookup"`

	// Context key to store generated CSRF token into context.
	// Optional. Default value "csrf".
	ContextKey string `yaml:"context_key"`

	// Name of the CSRF cookie. This cookie will store CSRF token.
	// Optional. Default value "csrf".
	CookieName string `yaml:"cookie_name"`

	// Domain of the CSRF cookie.
	// Optional. Default value none.
	CookieDomain string `yaml:"cookie_domain"`

	// Path of the CSRF cookie.
	// Optional. Default value none.
	CookiePath string `yaml:"cookie_path"`

	// Max age (in seconds) of the CSRF cookie.
	// Optional. Default value 86400 (24hr).
	CookieMaxAge int `yaml:"cookie_max_age"`

	// Indicates if CSRF cookie is secure.
	// Optional. Default value false.
	CookieSecure bool `yaml:"cookie_secure"`

	// Indicates if CSRF cookie is HTTP only.
	// Optional. Default value false.
	CookieHTTPOnly bool `yaml:"cookie_http_only"`

	// Indicates the sameSite policy for the CSRF cookie.
	// Optional. Default value is lax.
	CookieSameSite http.SameSite `yaml:"cookie_same_site"`
}

CSRFConfig defines the config for CSRF middleware.

type CacheMode

type CacheMode int

CacheMode is an enum to define a cache-control mode

const (
	// NoCache is for the no-cache control mode
	NoCache CacheMode = iota + 1
	// NoStore is for the no-store control mode
	NoStore
)

type CacheOptions

type CacheOptions struct {
	MaxAge         time.Duration
	Private        bool
	MustRevalidate bool
	Mode           CacheMode
}

CacheOptions contains different options for the CacheControl middleware.

type RecoverConfig

type RecoverConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// Size of the stack to be printed.
	// Optional. Default value 4KB.
	StackSize int `json:"stack_size"`
}

RecoverConfig defines the config for Recover middleware.

type SecureConfig

type SecureConfig struct {
	HSTSMaxAge time.Duration

	CSPDefaultSrc     []CSPSource
	CSPScriptSrc      []CSPSource
	CSPFrameSrc       []CSPSource
	CSPConnectSrc     []CSPSource
	CSPFontSrc        []CSPSource
	CSPImgSrc         []CSPSource
	CSPManifestSrc    []CSPSource
	CSPMediaSrc       []CSPSource
	CSPObjectSrc      []CSPSource
	CSPStyleSrc       []CSPSource
	CSPWorkerSrc      []CSPSource
	CSPFrameAncestors []CSPSource

	CSPDefaultSrcAllowList     string
	CSPScriptSrcAllowList      string
	CSPFrameSrcAllowList       string
	CSPConnectSrcAllowList     string
	CSPFontSrcAllowList        string
	CSPImgSrcAllowList         string
	CSPManifestSrcAllowList    string
	CSPMediaSrcAllowList       string
	CSPObjectSrcAllowList      string
	CSPStyleSrcAllowList       string
	CSPWorkerSrcAllowList      string
	CSPFrameAncestorsAllowList string

	// context_name -> source -> allow_list
	CSPPerContext map[string]map[string]string
}

SecureConfig defines the config for Secure middleware.

Jump to

Keyboard shortcuts

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