middleware

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2023 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package middleware provides set of middleware functions that can be used to authenticate and authorize requests in HTTP server.It also supports handling CORS, propagating headers, integrating with New Relic APM, and enabling distributed tracing using OpenTelemetry.

Index

Constants

View Source
const (
	ErrInvalidToken    = Error("invalid_token")
	ErrInvalidRequest  = Error("invalid_request")
	ErrServiceDown     = Error("service_unavailable")
	ErrInvalidHeader   = Error("invalid_header")
	ErrMissingHeader   = Error("missing_header")
	ErrUnauthorised    = Error("missing_permission")
	ErrUnauthenticated = Error("failed_auth")
	ErrInvalidAppKey   = Error("app_key_should_be_more_than_12_bytes")
)
View Source
const (
	ClientIPKey            clientIP            = "clientIP"
	AuthenticatedUserIDKey authenticatedUserID = "authUserID"
	AuthorizationHeader    authorizationHeader = "authorization"
	B3TraceIDKey           b3TraceID           = "b3traceID"
)
View Source
const CorrelationIDKey contextKey = "correlationID"
View Source
const ErrorMessage message = "errorMessage"

ErrorMessage is a constant used for error logging.

Variables

View Source
var (
	ErrorTypesStats = prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: "zs_server_error",
		Help: "Counter of HTTP Server Error",
	}, []string{"type", "path", "method"})
)

Functions

func AllowedCORSHeader

func AllowedCORSHeader() []string

AllowedCORSHeader returns the HTTP headers used for CORS configuration in web applications.

func CORS

func CORS(envHeaders map[string]string) func(inner http.Handler) http.Handler

CORS an HTTP middleware that sets headers based on the provided envHeaders configuration

func ErrorResponse

func ErrorResponse(w http.ResponseWriter, r *http.Request, logger logger, err errors.MultipleErrors)

ErrorResponse sends an HTTP error response, logging the error, handling various content types, and setting appropriate headers.

func ExemptPath

func ExemptPath(r *http.Request) bool

ExemptPath checks if the path of an HTTP request matches specific patterns used for metrics, health checks, or Swagger documentation

func FetchErrResponseWithCode

func FetchErrResponseWithCode(statusCode int, reason, code string) *errors.MultipleErrors

FetchErrResponseWithCode constructs an error response object. It includes a timestamp with the current time in RFC3339 format and the local time zone.

func GetDescription

func GetDescription(err error) (description string, statusCode int)

GetDescription maps specific error types to their corresponding descriptions and HTTP status codes.

func GetIPAddress

func GetIPAddress(r *http.Request) string

GetIPAddress extracts and returns the client's IP address from the X-Forwarded-For header, sequence in which IPs are typically added. If the header is empty or does not contain valid IPs, it falls back to using the RemoteAddr from the request.

func LDAP

func LDAP(logger log.Logger, options *LDAPOptions) func(inner http.Handler) http.Handler

LDAP middleware enables basic authentication for inter-service calls using gofr.dev LDAP

func Logging

func Logging(logger logger, omitHeaders string) func(inner http.Handler) http.Handler

Logging is a middleware which logs response status and time in microseconds along with other data.

func NewRelic

func NewRelic(appname, license string) func(http.Handler) http.Handler

NewRelic is a middleware that registers all the endpoints and sends the data to newrelic server

func PrometheusMiddleware

func PrometheusMiddleware(next http.Handler) http.Handler

PrometheusMiddleware implements mux.MiddlewareFunc.

func PropagateHeaders

func PropagateHeaders(inner http.Handler) http.Handler

PropagateHeaders propagates all the required headers through the context

func PushDeprecatedFeature

func PushDeprecatedFeature(featureName string)

PushDeprecatedFeature increments a Prometheus metric with labels

func PushSystemStats

func PushSystemStats()

PushSystemStats push metrics for system stats

func Recover

func Recover(logger logger) func(inner http.Handler) http.Handler

Recover handles error by allowing the inner HTTP handler to recover from panics.

func Trace

func Trace(appName, appVersion, tracerExporter string) func(inner http.Handler) http.Handler

Trace is a middleware which starts a span and the newly added context can be propagated and used for tracing

func ValidateHeaders

func ValidateHeaders(envHeaders string, logger logger) func(inner http.Handler) http.Handler

ValidateHeaders an HTTP middleware that checks and validates specified headers, and sets security-related response headers.

Types

type CacheEntry

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

CacheEntry represents entry in LdapCache.

type Error

type Error string

func (Error) Error

func (e Error) Error() string

Error returns the error message

type Header struct {
	Value         *http.Header
	IsBodyPresent bool
}

Header encapsulates the HTTP headers to be validated and checked.

type LDAPOptions

type LDAPOptions struct {
	// ex: "^/v2/promises-composite/$": MethodGroup[{Method: "POST", Group: "promises-composite-write"}]
	// in case same method is present in multiple elements in the array, first occurrence would be considered
	RegexToMethodGroup map[string][]MethodGroup

	// ex: ldapstage.gofr.dev:636
	Addr string

	// TimeOut is the authentication timeout in seconds, if not set,
	// there is no timeout
	TimeOut int

	// CacheInvalidationFrequency sets the frequency(in seconds) with
	// which the in memory cache of authenticated users is reset;
	// if this is value not set, then there is no invalidation.
	// By default there is no cache invalidation
	CacheInvalidationFrequency int

	// InsecureSkipVerify controls whether a client verifies the
	// server's certificate chain and host name.
	// If InsecureSkipVerify is true, TLS accepts any certificate
	// presented by the server and any host name in that certificate.
	// In this mode, TLS is susceptible to man-in-the-middle attacks.
	// This should be used only for testing.
	InsecureSkipVerify bool
}

LDAPOptions stores the configurations for LDAP middleware options

type Ldap

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

Ldap stores configuration options and an in-memory cache for LDAP authentication.

func NewLDAP

func NewLDAP(logger log.Logger, options *LDAPOptions) (l *Ldap)

NewLDAP is a factory function that creates and initializes an Ldap instance

func (*Ldap) Validate

func (l *Ldap) Validate(logger log.Logger, r *http.Request) error

Validate an HTTP request against configured patterns based on the authentication and group validation results.

type LdapCache

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

LdapCache represents the in-memory cache for LDAP authentication.

type LogDataKey

type LogDataKey string

type LogLine

type LogLine struct {
	CorrelationID  string                 `json:"correlationId"`
	Type           string                 `json:"type"`
	StartTimestamp time.Time              `json:"startTimestamp"`
	Duration       int64                  `json:"duration"`
	Method         string                 `json:"method"`
	IP             string                 `json:"ip"`
	URI            string                 `json:"uri"`
	Response       int                    `json:"responseCode"`
	Headers        map[string]string      `json:"headers"`
	AppData        map[string]interface{} `json:"appData"`
	ErrorMessage   string                 `json:"errorMessage,omitempty"`
}

LogLine represents a structured log entry, including various details like correlation ID, request method, response status, and more.

func (*LogLine) String

func (l *LogLine) String() string

String converts a LogLine object into its JSON representation

type MethodGroup

type MethodGroup struct {
	Method string
	Group  string
}

MethodGroup is struct to specify HTTP methods and their associated groups.

type StatusResponseWriter

type StatusResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

StatusResponseWriter defines own Response Writer to be used for logging of status - as http.ResponseWriter does not let us read status.

func (*StatusResponseWriter) WriteHeader

func (w *StatusResponseWriter) WriteHeader(status int)

WriteHeader updates the response status code and forwards the call to the underlying ResponseWriter

Directories

Path Synopsis
Package oauth provides a middleware for authenticating requests.This package provides functionality for token validation and integration with JSON Web Key (JWK) to verify JSON Web Tokens (JWT).
Package oauth provides a middleware for authenticating requests.This package provides functionality for token validation and integration with JSON Web Key (JWK) to verify JSON Web Tokens (JWT).

Jump to

Keyboard shortcuts

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