common

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2023 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func InstallDefaultAuthorizationServerConfigValues

func InstallDefaultAuthorizationServerConfigValues()

InstallDefaultAuthorizationServerConfigValues installs default config parameters in viper

func ModifyLogMetadataByAccessAuthorizeParam

func ModifyLogMetadataByAccessAuthorizeParam(ctxt context.Context, theTags log.Fields)

ModifyLogMetadataByAccessAuthorizeParam update log metadata with info from AccessAuthorizeParam

@param ctxt context.Context - a request context
@param theTags log.Fields - a log metadata to update

Types

type APIConfig

type APIConfig struct {
	// Endpoint sets API endpoint related parameters
	Endpoint EndpointConfig `mapstructure:"endPoint" json:"endPoint" validate:"required,dive"`
	// RequestLogging sets API request logging parameters
	RequestLogging HTTPRequestLogging `mapstructure:"requestLogging" json:"requestLogging" validate:"required,dive"`
}

APIConfig defines API settings for a submodule

type APIServerConfig

type APIServerConfig struct {
	// Enabled whether this API is enabled
	Enabled bool `mapstructure:"enabled" json:"enabled"`
	// Server defines HTTP server parameters
	Server HTTPServerConfig `mapstructure:"service" json:"service" validate:"required_with=Enabled,dive"`
	// APIs defines API settings for a submodule
	APIs APIConfig `mapstructure:"apis" json:"apis" validate:"required_with=Enabled,dive"`
}

APIServerConfig defines HTTP API / server parameters

type AccessAuthorizeParam

type AccessAuthorizeParam struct {
	// UserID is the ID of the user needing access
	UserID string `json:"user_id" validate:"required,user_id"`
	// Method is the method used
	Method string `json:"method" validate:"required,oneof=GET HEAD PUT POST PATCH DELETE OPTIONS"`
	// Path is the request Path needing access check
	Path string `json:"path" validate:"required,uri"`
	// Host is the Host needing access check
	Host string `json:"host" validate:"required,fqdn"`
}

AccessAuthorizeParam contains the authorization request parameters, stored in request context

func (*AccessAuthorizeParam) String

func (i *AccessAuthorizeParam) String() string

String implements toString for object

func (*AccessAuthorizeParam) UpdateLogTags

func (i *AccessAuthorizeParam) UpdateLogTags(tags log.Fields)

UpdateLogTags updates Apex log.Fields map with values from the parameter

@param tags log.Fields - log.Fields to update

type AccessAuthorizeParamKey

type AccessAuthorizeParamKey struct{}

AccessAuthorizeParamKey associated key for AccessAuthorizeParam when storing in request context

type AuthenticateRequestParamLocConfig added in v0.5.2

type AuthenticateRequestParamLocConfig struct {
	// Host is the host / FQDN of the request being authenticated
	Host string `mapstructure:"host" json:"host" validate:"required"`
	// Path is the URI path of the request being authenticated
	Path string `mapstructure:"path" json:"path" validate:"required"`
	// Method is the HTTP method of the request being authenticated
	Method string `mapstructure:"method" json:"method" validate:"required"`
}

AuthenticateRequestParamLocConfig defines which HTTP headers to parse to get the parameters of a REST request to authenticate. It is expected that the component (i.e. a proxy) requesting authentication for a request will provide the needed values through these headers when it contacts the authentication server.

type AuthenticationConfig

type AuthenticationConfig struct {
	// TargetAudience if specified, the token must contain an "aud" claim which matches this value.
	TargetAudience *string `mapstructure:"targetAudience,omitempty" json:"target_audience,omitempty" validate:"omitempty"`
	// TargetClaims sets which claims to parse from a token to get key parameters regarding a user.
	TargetClaims OpenIDClaimsOfInterestConfig `mapstructure:"targetClaims" json:"target_claims" validate:"required,dive"`
	// RequestParamLocation sets which HTTP headers to parse to get the parameters of
	// a REST request to authenticate. It is expected that the component (i.e. a proxy) requesting
	// authentication for a request will provide the needed values through these headers when it
	// contacts the authentication server.
	RequestParamLocation AuthenticateRequestParamLocConfig `mapstructure:"requestParamHeaders" json:"requestParamHeaders" validate:"required,dive"`
	// Introspection define OAuth2 token introspect operation config
	Introspection IntrospectionConfig `mapstructure:"introspect" json:"introspect" validate:"required,dive"`
	// Bypass authentication bypass rules
	Bypass *AuthnBypassConfig `mapstructure:"bypass,omitempty" json:"bypass,omitempty" validate:"omitempty,dive"`
}

AuthenticationConfig describes the REST API authentication config

type AuthenticationSubmodule

type AuthenticationSubmodule struct {
	APIServerConfig      `mapstructure:",squash"`
	AuthenticationConfig `mapstructure:",squash"`
}

AuthenticationSubmodule defines authentication submodule config

type AuthnBypassConfig added in v0.5.2

type AuthnBypassConfig struct {
	// Rules the authentication bypass rules to check against
	Rules []AuthnBypassMatchEntry `mapstructure:"rules,omitempty" json:"rules,omitempty" validate:"omitempty,gte=1,dive"`
}

AuthnBypassConfig authentication bypass configuration

type AuthnBypassMatchEntry added in v0.5.2

type AuthnBypassMatchEntry struct {
	// MatchType indicates which request element this rules applies to
	MatchType string `mapstructure:"type" json:"type" validate:"required,oneof=method host path"`
	// Matches if a request property matches one of the possibilities, the request can
	// bypass authentication.
	Matches []string `mapstructure:"matches" json:"matches" validate:"required,gte=1"`
}

AuthnBypassMatchEntry one authentication bypass rule

type AuthorizationConfig

type AuthorizationConfig struct {
	// Rules is the list of TargetHostSpec supported by the server. The host of "*"
	// functions as a wildcard. If a request host is not explicitly listed here, it may match
	// against "*" if that was defined.
	Rules []HostAuthorizationConfig `mapstructure:"rules" json:"rules" validate:"required_with=Enabled,dive"`
	// RequestParamLocation sets which HTTP headers to parse to get the parameters of
	// a REST request to authorize. It is expected that the component (i.e. a proxy) requesting
	// authorization for a request will provide the needed values through these headers when it
	// contacts the authorization server.
	RequestParamLocation AuthorizeRequestParamLocConfig `mapstructure:"requestParamHeaders" json:"requestParamHeaders" validate:"required,dive"`
	// UnknownUser sets what actions to take when the request being authorized is made
	// by an unknown user
	UnknownUser UnknownUserActionConfig `mapstructure:"forUnknownUser" json:"forUnknownUser" validate:"required,dive"`
}

AuthorizationConfig describes the REST API authorization config

type AuthorizationServerConfig

type AuthorizationServerConfig struct {
	// Metrics metrics framework configuration
	Metrics MetricsConfig `mapstructure:"metrics" json:"metrics" validate:"required,dive"`
	// CustomRegex sets custom regex used by validator for custom field tags
	CustomRegex CustomValidationsConfig `mapstructure:"customValidationRegex" json:"customValidationRegex" validate:"required,dive"`
	// UserManagement are the user management submodule configs
	UserManagement UserManageSubmodule `mapstructure:"userManagement" json:"userManagement" validate:"required,dive"`
	// Authorization are the authorization submodule configs
	Authorization AuthorizationSubmodule `mapstructure:"authorize" json:"authorize" validate:"required,dive"`
	// Authentication are the authentication submodule configs
	Authentication AuthenticationSubmodule `mapstructure:"authenticate" json:"authenticate" validate:"required,dive"`
}

AuthorizationServerConfig is the authorization server config

func (AuthorizationServerConfig) Validate

func (c AuthorizationServerConfig) Validate() error

Validate the authorization server config

@return nil if valid, or an error

type AuthorizationSubmodule

type AuthorizationSubmodule struct {
	APIServerConfig     `mapstructure:",squash"`
	AuthorizationConfig `mapstructure:",squash"`
}

AuthorizationSubmodule defines authorization submodule config

type AuthorizeRequestParamLocConfig

type AuthorizeRequestParamLocConfig struct {
	// Host is the host / FQDN of the request being authorized
	Host string `mapstructure:"host" json:"host" validate:"required"`
	// Path is the URI path of the request being authorized
	Path string `mapstructure:"path" json:"path" validate:"required"`
	// Method is the HTTP method of the request being authorized
	Method string `mapstructure:"method" json:"method" validate:"required"`
	// UserID is the user ID of the user making the request
	UserID string `mapstructure:"userID" json:"userID" validate:"required"`
	// Username is the username of the user making the request
	Username string `mapstructure:"username" json:"username" validate:"required"`
	// FirstName is the first name / given name of the user making the request
	FirstName string `mapstructure:"firstName" json:"firstName" validate:"required"`
	// LastName is the last name / surname / family name of the user making the request
	LastName string `mapstructure:"lastName" json:"lastName" validate:"required"`
	// Email is the email of the user making the request
	Email string `mapstructure:"email" json:"email" validate:"required"`
}

AuthorizeRequestParamLocConfig defines which HTTP headers to parse to get the parameters of a REST request to authorize. It is expected that the component (i.e. a proxy) requesting authorization for a request will provide the needed values through these headers when it contacts the authorization server.

type CustomFieldValidator

type CustomFieldValidator interface {
	/*
		RegisterWithValidator register with the validator this customer validation support

		 @param v *validator.Validate - the validator to register against
		 @return whether successful
	*/
	RegisterWithValidator(v *validator.Validate) error

	/*
		ValidateUserID custom user ID validation function

		 @param fl validator.FieldLevel - the field to validate
		 @return whether is valid
	*/
	ValidateUserID(fl validator.FieldLevel) bool

	/*
		ValidateUserName custom user name validation function

		 @param fl validator.FieldLevel - the field to validate
		 @return whether is valid
	*/
	ValidateUserName(fl validator.FieldLevel) bool

	/*
		ValidatePersonalName custom surname and family name validation function

		 @param fl validator.FieldLevel - the field to validate
		 @return whether is valid
	*/
	ValidatePersonalName(fl validator.FieldLevel) bool

	/*
		ValidateRoleName custom role name validation function

		 @param fl validator.FieldLevel - the field to validate
		 @return whether is valid
	*/
	ValidateRoleName(fl validator.FieldLevel) bool

	/*
		ValidatePermissionName custom permission name validation function

		 @param fl validator.FieldLevel - the field to validate
		 @return whether is valid
	*/
	ValidatePermissionName(fl validator.FieldLevel) bool
}

CustomFieldValidator support class for running custom validation of fields

func GetCustomFieldValidator

func GetCustomFieldValidator(
	userIDRegex string,
	usernameRegex string,
	nameRegex string,
	roleNameRegex string,
	permissionRegex string,
) (CustomFieldValidator, error)

GetCustomFieldValidator get new CustomFieldValidator instance

@param userIDRegex string - usr ID validation regex
@param usernameRegex string - username validation regex
@param nameRegex string - personal name validation regex
@param roleNameRegex string - role name validation regex
@param permissionRegex string - permission name validation regex
@return new CustomFieldValidator instance

type CustomValidationsConfig

type CustomValidationsConfig struct {
	// UserIDRegex is the regex pattern used to validate a user ID
	UserIDRegex string `mapstructure:"userID" json:"userID" validate:"required"`
	// UserNameRegex is the regex pattern used to validate a username
	UserNameRegex string `mapstructure:"username" json:"username" validate:"required"`
	// PersonalNameRegex is the regex pattern used to validate a personal name
	PersonalNameRegex string `mapstructure:"personalName" json:"personalName" validate:"required"`
	// RoleNameRegex is the regex pattern used to validate a role name
	RoleNameRegex string `mapstructure:"roleName" json:"roleName" validate:"required"`
	// PermissionRegex is the regex pattern used to validate a permission name
	PermissionRegex string `mapstructure:"permission" json:"permission" validate:"required"`
}

CustomValidationsConfig provides the custom validation regex patterns

func (CustomValidationsConfig) DefineCustomFieldValidator

func (c CustomValidationsConfig) DefineCustomFieldValidator() (CustomFieldValidator, error)

DefineCustomFieldValidator defines a CustomFieldValidator based on the config parameters

@return the defined CustomFieldValidator

type DatabaseConfig

type DatabaseConfig struct {
	// Host is the DB host
	Host string `json:"host" validate:"required"`
	// DB is the database name
	DB string `json:"db" validate:"required"`
	// User is the database user
	User string `json:"user" validate:"required"`
}

DatabaseConfig database related configuration

type EndpointConfig

type EndpointConfig struct {
	// PathPrefix is the end-point path prefix for the APIs
	PathPrefix string `mapstructure:"pathPrefix" json:"pathPrefix" validate:"required"`
}

EndpointConfig defines API endpoint config

type HTTPRequestLogging

type HTTPRequestLogging struct {
	// LogLevel output request logs at this level
	LogLevel goutils.HTTPRequestLogLevel `mapstructure:"logLevel" json:"logLevel" validate:"oneof=warn info debug"`
	// HealthLogLevel output health check logs at this level
	HealthLogLevel goutils.HTTPRequestLogLevel `mapstructure:"healthLogLevel" json:"healthLogLevel" validate:"oneof=warn info debug"`
	// RequestIDHeader is the HTTP header containing the API request ID
	RequestIDHeader string `mapstructure:"requestIDHeader" json:"requestIDHeader"`
	// DoNotLogHeaders is the list of headers to not include in logging metadata
	DoNotLogHeaders []string `mapstructure:"skipHeaders" json:"skipHeaders"`
}

HTTPRequestLogging defines HTTP request logging parameters

type HTTPServerConfig

type HTTPServerConfig struct {
	// ListenOn is the interface the HTTP server will listen on
	ListenOn string `mapstructure:"listenOn" json:"listenOn" validate:"required,ip"`
	// Port is the port the HTTP server will listen on
	Port uint16 `mapstructure:"appPort" json:"appPort" validate:"required,gt=0,lt=65536"`
	// Timeouts sets the HTTP timeout settings
	Timeouts HTTPServerTimeoutConfig `mapstructure:"timeoutSecs" json:"timeoutSecs" validate:"required,dive"`
}

HTTPServerConfig defines the HTTP server parameters

type HTTPServerTimeoutConfig

type HTTPServerTimeoutConfig struct {
	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body in seconds. A zero or negative
	// value means there will be no timeout.
	ReadTimeout int `mapstructure:"read" json:"read" validate:"gte=0"`
	// WriteTimeout is the maximum duration before timing out
	// writes of the response in seconds. A zero or negative value
	// means there will be no timeout.
	WriteTimeout int `mapstructure:"write" json:"write" validate:"gte=0"`
	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled in seconds. If
	// IdleTimeout is zero, the value of ReadTimeout is used. If
	// both are zero, there is no timeout.
	IdleTimeout int `mapstructure:"idle" json:"idle" validate:"gte=0"`
}

HTTPServerTimeoutConfig defines the timeout settings for HTTP server

type HostAuthorizationConfig

type HostAuthorizationConfig struct {
	// Host is the hostname for this group of path authorizers
	Host string `mapstructure:"host" json:"host" validate:"required,fqdn|eq=*"`
	// TargetPaths is the list of path being checked for this host
	TargetPaths []PathAuthorizationConfig `mapstructure:"allowedPaths" json:"allowedPaths" validate:"required,gte=1,dive"`
}

HostAuthorizationConfig is a group path authorizations for a specific host

type IntrospectionConfig added in v0.4.0

type IntrospectionConfig struct {
	// Enabled whether introspection enabled
	Enabled bool `mapstructure:"enabled" json:"enabled"`
	// ReIntrospectInterval interval (sec) to periodically re-introspect cached tokens
	ReIntrospectInterval int `mapstructure:"recheckIntervalSec" json:"recheck_interval_sec" validate:"gte=30"`
	// CacheCleanInterval interval (sec) to periodically clear expired tokens from cache
	CacheCleanInterval int `mapstructure:"cacheCleanIntervalSec" json:"cache_clean_interval_sec" validate:"gte=30"`
	// CachePurgeInterval interval (sec) to periodically purge the token cache
	CachePurgeInterval int `mapstructure:"cachePurgeIntervalSec" json:"cache_purge_interval_sec" validate:"gte=60"`
}

IntrospectionConfig OAuth2 token introspect operation config

type MetricsConfig added in v0.5.1

type MetricsConfig struct {
	// Server defines HTTP server parameters
	Server HTTPServerConfig `mapstructure:"service" json:"service" validate:"required_with=Enabled,dive"`
	// MetricsEndpoint path to host the Prometheus metrics endpoint
	MetricsEndpoint string `mapstructure:"metricsEndpoint" json:"metricsEndpoint" validate:"required"`
	// MaxRequests max number of metrics requests in parallel to support
	MaxRequests int `mapstructure:"maxRequests" json:"maxRequests" validate:"gte=1"`
	// Features metrics framework features to enable
	Features MetricsFeatureConfig `mapstructure:"features" json:"features" validate:"gte=1"`
}

MetricsConfig application metrics config

type MetricsFeatureConfig added in v0.5.1

type MetricsFeatureConfig struct {
	// EnableAppMetrics whether to enable Golang application metrics
	EnableAppMetrics bool `mapstructure:"enableAppMetrics" json:"enableAppMetrics"`
}

MetricsFeatureConfig metrics framework features config

type OpenIDClaimsOfInterestConfig

type OpenIDClaimsOfInterestConfig struct {
	// UserIDClaim is the claim for containing the user ID
	UserIDClaim string `mapstructure:"userID" json:"userID" validate:"required"`
	// UsernameClaim is the claim containing the user Name
	UsernameClaim *string `mapstructure:"username,omitempty" json:"username,omitempty"`
	// FirstNameClaim is the claim containing the first name / given name of the user
	FirstNameClaim *string `mapstructure:"firstName,omitempty" json:"firstName,omitempty"`
	// LastNameClaim is the claim containing the last name / surname / family name of the user
	LastNameClaim *string `mapstructure:"lastName,omitempty" json:"lastName,omitempty"`
	// EmailClaim is the claim containing the email of the user
	EmailClaim *string `mapstructure:"email,omitempty" json:"email,omitempty"`
}

OpenIDClaimsOfInterestConfig sets which claims to parse from a token to get key parameters regarding a user.

Depending on the OpenID provider, these claims are present in the ID token, but may also be present in the access token; this is the case with KeyCloak.

type OpenIDIssuerConfig

type OpenIDIssuerConfig struct {
	// Issuer is the URL of the OpenID issuer
	Issuer string `json:"issuer" validate:"required,url"`
	// ClientID is the client ID to use during token introspection
	ClientID *string `json:"client_id" validate:"omitempty"`
	// ClientCred is the client credential to use during token introspection
	ClientCred *string `json:"client_cred" validate:"omitempty"`
	// CustomCA if provided, is the custom CA to use for the TLS session with this issuer.
	CustomCA *string `json:"http_tls_ca,omitempty" validate:"omitempty,file"`
	// RequestHostOverride if specified, use this as "Host" header when communicating with issuer
	RequestHostOverride *string `json:"host_override" validate:"omitempty"`
}

OpenIDIssuerConfig defines connection parameters to one OpenID issuer

type PathAuthorizationConfig

type PathAuthorizationConfig struct {
	// PathRegexPattern is the regex for matching against a request URI path
	PathRegexPattern string `mapstructure:"pathPattern" json:"pathPattern" validate:"required"`
	// AllowedMethods is the list of allowed permission for each specified request
	// method that is supportred by this URI. The method "*" functions as a wildcard.
	// If the request method is not explicitly listed here, it may match against "*" if that
	// was defined.
	AllowedMethods []PermissionForAPIMethodConfig `mapstructure:"allowedMethods" json:"allowedMethods" validate:"required,gte=1,dive"`
}

PathAuthorizationConfig a single path authorization specification

type PermissionForAPIMethodConfig

type PermissionForAPIMethodConfig struct {
	// Method specify the REST method these permissions are associated with. "*" is a wildcard.
	Method string `mapstructure:"method" json:"method" validate:"required,oneof=GET HEAD PUT POST PATCH DELETE OPTIONS *"`
	// Permissions is the list of user permissions allowed to use a method
	Permissions []string `mapstructure:"allowedPermissions" json:"allowedPermissions" validate:"required,gte=1,dive,user_permissions"`
}

PermissionForAPIMethodConfig lists the permissions needed use a method

type RegexCheck

type RegexCheck interface {
	/*
		Match checks whether this regex finds a match against the input

		 @param s []byte - the string against
		 @return whether the input matchs against the regex
	*/
	Match(s []byte) (bool, error)

	/*
		String returns an ASCII description of the object

		 @return an ASCII description of the object
	*/
	String() string
}

RegexCheck is a wrapper object to perform a regex check against a string

func NewRegexCheck

func NewRegexCheck(pattern string) (RegexCheck, error)

NewRegexCheck defines a new RegexCheck object

@param pattern string - regex pattern
@return the RegexCheck instance

type UnknownUserActionConfig

type UnknownUserActionConfig struct {
	// AutoAdd set whether automatically record the unknown user during the authorization process
	//
	// Note: This can be dangerous as it could lead to denial-of-service due to resource exhaustion.
	AutoAdd bool `mapstructure:"autoAdd" json:"autoAdd"`
}

UnknownUserActionConfig defines what actions to take when the request being authorized is made by an unknown user

type UserManageSubmodule

type UserManageSubmodule struct {
	APIServerConfig `mapstructure:",squash"`
	UserRolesConfig `mapstructure:",squash"`
}

UserManageSubmodule defines user management submodule config

type UserRoleConfig

type UserRoleConfig struct {
	// AssignedPermissions is the list of permissions assigned to a role
	AssignedPermissions []string `mapstructure:"permissions" json:"permissions" validate:"required,gte=1,dive,user_permissions"`
}

UserRoleConfig a single user role

type UserRolesConfig

type UserRolesConfig struct {
	// AvailableRoles is the set of roles supported by the system
	AvailableRoles map[string]UserRoleConfig `mapstructure:"userRoles" json:"userRoles" validate:"required_with=Enabled,dive"`
}

UserRolesConfig a group of user roles

Jump to

Keyboard shortcuts

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