httputil

package
v0.25.2 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: Apache-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package

Index

Constants

View Source
const (
	HeaderAuthorization    = "Authorization"
	HeaderReferrer         = "Referer"
	HeaderImpersonateGroup = "Impersonate-Group"
	HeaderUpgrade          = "Upgrade"
)

Standard headers

View Source
const (
	// HeaderPomeriumAuthorization is the header key for a pomerium authorization JWT. It
	// can be used in place of the standard authorization header if that header is being
	// used by upstream applications.
	HeaderPomeriumAuthorization = "x-pomerium-authorization"
	// HeaderPomeriumResponse is set when pomerium itself creates a response,
	// as opposed to the upstream application and can be used to distinguish
	// between an application error, and a pomerium related error when debugging.
	// Especially useful when working with single page apps (SPA).
	HeaderPomeriumResponse = "x-pomerium-intercepted-response"
	// HeaderPomeriumJWTAssertion is the header key containing JWT signed user details.
	HeaderPomeriumJWTAssertion = "x-pomerium-jwt-assertion"
	// HeaderPomeriumJWTAssertionFor carries over original user identity from a chain of network calls.
	HeaderPomeriumJWTAssertionFor = "x-pomerium-jwt-assertion-for"
	// HeaderPomeriumReproxyPolicy is the header key containing the policy to reproxy a request to.
	HeaderPomeriumReproxyPolicy = "x-pomerium-reproxy-policy"
	// HeaderPomeriumReproxyPolicyHMAC is an HMAC of the HeaderPomeriumReproxyPolicy header.
	HeaderPomeriumReproxyPolicyHMAC = "x-pomerium-reproxy-policy-hmac"
	// HeaderPomeriumRoutingKey is a string used for routing user requests to a consistent upstream server.
	HeaderPomeriumRoutingKey = "x-pomerium-routing-key"
)

Pomerium headers contain information added to a request.

View Source
const (
	// StatusDeviceUnauthorized is the status code returned when a client's
	// device credential is not authorized to access a page.
	StatusDeviceUnauthorized = 450
	// StatusInvalidClientCertificate is the status code returned when a
	// client's certificate is invalid. This is the same status code used
	// by nginx for this purpose.
	StatusInvalidClientCertificate = 495
)
View Source
const AuthorizationTypePomerium = "Pomerium"

AuthorizationTypePomerium is for Authorization: Pomerium JWT... headers

Variables

View Source
var CanonicalHeaderKey = log.CanonicalHeaderKey

CanonicalHeaderKey re-exports the log.CanonicalHeaderKey function to avoid an import cycle.

View Source
var ErrCookieTooLarge = errors.New("cookie too large")

ErrCookieTooLarge indicates that a cookie is too large.

View Source
var ErrTokenRevoked = errors.New("token expired or revoked")

ErrTokenRevoked signifies a token revocation or expiration error

View Source
var HeadersContentSecurityPolicy = map[string]string{
	"Content-Security-Policy": "default-src 'none'; style-src 'self' 'unsafe-inline' data:; img-src * data:; script-src 'self' 'unsafe-inline'; font-src data:",
	"Referrer-Policy":         "Same-origin",
}

HeadersContentSecurityPolicy are the content security headers added to the service's handlers by default includes profile photo exceptions for supported identity providers. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src

Functions

func AddBrandingOptionsToMap added in v0.19.0

func AddBrandingOptionsToMap(dst map[string]any, brandingOptions BrandingOptions)

AddBrandingOptionsToMap adds the branding options to the map.

func CSRFFailureHandler added in v0.4.0

func CSRFFailureHandler(_ http.ResponseWriter, r *http.Request) error

CSRFFailureHandler sets a HTTP 403 Forbidden status and writes the CSRF failure reason to the response.

func DashboardSubrouter added in v0.17.0

func DashboardSubrouter(parent *mux.Router) *mux.Router

DashboardSubrouter returns the .pomerium sub router.

func DetailsText added in v0.15.6

func DetailsText(code int) string

DetailsText returns extra details for an HTTP status code. It returns StatusText if not found.

func Do added in v0.15.0

func Do(ctx context.Context, method, endpoint, userAgent string, headers map[string]string, params url.Values, response interface{}) error

Do provides a simple helper interface to make HTTP requests

func GetClientIP added in v0.22.0

func GetClientIP(r *http.Request) string

GetClientIP returns the client IP address from the request.

func GetClientIPAddress added in v0.18.0

func GetClientIPAddress(r *http.Request) string

GetClientIPAddress gets a client's IP address for an HTTP request.

func GetInsecureTransport added in v0.21.0

func GetInsecureTransport() *http.Transport

GetInsecureTransport gets an insecure HTTP transport.

func GetSignedOutRedirectURICookie added in v0.25.0

func GetSignedOutRedirectURICookie(w http.ResponseWriter, r *http.Request) (string, bool)

GetSignedOutRedirectURICookie gets the redirect uri cookie for the signed-out page.

func NewLoggingClient added in v0.15.0

func NewLoggingClient(base *http.Client, name string, customize ...func(event *zerolog.Event) *zerolog.Event) *http.Client

NewLoggingClient creates a new http.Client that will log requests.

func NewLoggingRoundTripper added in v0.15.0

func NewLoggingRoundTripper(base http.RoundTripper, customize ...func(event *zerolog.Event) *zerolog.Event) http.RoundTripper

NewLoggingRoundTripper creates a http.RoundTripper that will log requests.

func NewRouter added in v0.4.0

func NewRouter() *mux.Router

NewRouter returns a new router instance.

func NewServer added in v0.4.0

func NewServer(opt *ServerOptions, h http.Handler, wg *sync.WaitGroup) (*http.Server, error)

NewServer creates a new HTTP server given a set of options, handler, and waitgroup. It is the callers responsibility to close the resturned server.

func PomeriumJWTHeaderName added in v0.10.0

func PomeriumJWTHeaderName(claim string) string

PomeriumJWTHeaderName returns the header name set by pomerium for given JWT claim field.

func Redirect added in v0.5.0

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)

Redirect wraps the std libs's redirect method indicating that pomerium is the origin of the response.

func RedirectHandler added in v0.2.0

func RedirectHandler() http.Handler

RedirectHandler takes an incoming request and redirects to its HTTPS counterpart

func RenderJSON added in v0.11.0

func RenderJSON(w http.ResponseWriter, code int, v interface{})

RenderJSON replies to the request with the specified struct as JSON and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be application/json.

func SetSignedOutRedirectURICookie added in v0.25.0

func SetSignedOutRedirectURICookie(w http.ResponseWriter, redirectURI string)

SetSignedOutRedirectURICookie sets the redirect uri cookie for the signed-out page.

func Shutdown added in v0.2.0

func Shutdown(srv *http.Server)

Shutdown attempts to shut down the server when a os interrupt or sigterm signal are received without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return ErrServerClosed.

func StatusText added in v0.14.0

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns http.StatusText if not found.

Types

type BrandingOptions added in v0.19.0

type BrandingOptions interface {
	GetPrimaryColor() string
	GetSecondaryColor() string
	GetDarkmodePrimaryColor() string
	GetDarkmodeSecondaryColor() string
	GetLogoUrl() string
	GetFaviconUrl() string
	GetErrorMessageFirstParagraph() string
}

The BrandingOptions customize the user info and error pages.

type CookieChunker added in v0.21.0

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

A CookieChunker breaks up a large cookie into multiple pieces.

func NewCookieChunker added in v0.21.0

func NewCookieChunker(options ...CookieChunkerOption) *CookieChunker

NewCookieChunker creates a new CookieChunker.

func (*CookieChunker) LoadCookie added in v0.21.0

func (cc *CookieChunker) LoadCookie(r *http.Request, name string) (*http.Cookie, error)

LoadCookie loads a chunked cookie.

func (*CookieChunker) SetCookie added in v0.21.0

func (cc *CookieChunker) SetCookie(w http.ResponseWriter, cookie *http.Cookie) error

SetCookie sets a chunked cookie.

type CookieChunkerOption added in v0.21.0

type CookieChunkerOption func(cfg *cookieChunkerConfig)

A CookieChunkerOption customizes the cookie chunker.

func WithCookieChunkerChunkSize added in v0.21.0

func WithCookieChunkerChunkSize(chunkSize int) CookieChunkerOption

WithCookieChunkerChunkSize sets the chunk size for the cookie chunker.

func WithCookieChunkerMaxChunks added in v0.21.0

func WithCookieChunkerMaxChunks(maxChunks int) CookieChunkerOption

WithCookieChunkerMaxChunks sets the maximum number of chunks for the cookie chunker.

type HTTPError

type HTTPError struct {
	// HTTP status codes as registered with IANA.
	Status int
	// Err is the wrapped error.
	Err         error
	Description string
	// DebugURL is the URL to the debug endpoint.
	DebugURL *url.URL
	// The request ID.
	RequestID string

	BrandingOptions BrandingOptions
}

HTTPError contains an HTTP status code and wrapped error.

func NewError added in v0.6.0

func NewError(status int, err error) *HTTPError

NewError returns an error that contains a HTTP status and error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the `error` interface.

func (*HTTPError) ErrorResponse added in v0.6.0

func (e *HTTPError) ErrorResponse(ctx context.Context, w http.ResponseWriter, r *http.Request)

ErrorResponse replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w.

func (*HTTPError) Unwrap added in v0.6.0

func (e *HTTPError) Unwrap() error

Unwrap implements the `error` Unwrap interface.

func (*HTTPError) WithDescription added in v0.21.0

func (e *HTTPError) WithDescription(description string) *HTTPError

WithDescription sets the description in the HTTP error.

type HandlerFunc added in v0.6.0

type HandlerFunc func(http.ResponseWriter, *http.Request) error

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

adapted from std library to support error wrapping

func (HandlerFunc) ServeHTTP added in v0.6.0

func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP calls f(w, r) error.

type ServerOptions added in v0.2.0

type ServerOptions struct {
	// Addr specifies the host and port on which the server should serve
	// HTTPS requests. If empty, ":443" is used.
	Addr string

	// TLSConfig is the tls configuration used to setup the HTTPS server.
	TLSConfig *tls.Config

	// InsecureServer when enabled disables all transport security.
	// In this mode, Pomerium is susceptible to man-in-the-middle attacks.
	// This should be used only for testing.
	Insecure bool

	// Service is an optional field that helps define what the server's role is.
	Service string

	// Timeouts
	ReadHeaderTimeout time.Duration
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
}

ServerOptions contains the configurations settings for a http server.

Directories

Path Synopsis
Package reproxy contains a handler for re-proxying traffic through the http controlplane.
Package reproxy contains a handler for re-proxying traffic through the http controlplane.

Jump to

Keyboard shortcuts

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