httpx

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: MIT Imports: 24 Imported by: 3

Documentation

Index

Constants

View Source
const (
	HeaderXHost = "host"

	NonceName     = "nonce"
	TimestampName = "timestamp"
	SignatureName = "Signature"
)
View Source
const (
	// ExtractorLimit is arbitrary number to limit values extractor can return. this limits possible resource exhaustion
	// attack vector
	ExtractorLimit = 20
)

Variables

View Source
var (
	AlgorithmSha256 = &Algorithm{"sha256", sha256.New}
	AlgorithmSha1   = &Algorithm{"sha1", sha1.New}

	ErrUnknownAlgorithm = errors.New("unknown algorithm")
	ErrInvalidSignature = errors.New("invalid signature")
)
View Source
var DefaultSignerConfig = SignerConfig{
	AuthLookup:          "header:Authorization",
	Algorithm:           *AlgorithmSha1,
	AuthHeaderDelimiter: ", ",
	Delimiter:           "\n",
	DateFormat:          "",
	TimestampKey:        TimestampName,
	NonceKey:            NonceName,
	NonceLen:            10,
}

Functions

func EscapePath added in v0.4.0

func EscapePath(path string, encodeSep bool) string

EscapePath escapes part of a URL path in Amazon style

func FormatSignTime added in v0.4.0

func FormatSignTime(t time.Time, layout string) string

FormatSignTime format time to string by layout, if layout is empty, return unix timestamp.

func GetSignedRequestSignature added in v0.4.0

func GetSignedRequestSignature(r *http.Request, header, scheme, delt string) (string, error)

GetSignedRequestSignature attempts to extract the signature of the request. Returning an error if the request is unsigned, or unable to extract the signature.

func NewClient

func NewClient(cfg *ClientConfig) (c *http.Client, err error)

NewClient creates a new HTTP client.

OAuth2 Client from Configuration is use client credentials flow.You can use TokenSource to custom Source.

func NewTransport

func NewTransport(cfg TransportConfig) (http.RoundTripper, error)

NewTransport creates a new HTTP transport base on TransportConfig and http.DefaultTransport.

func ParseSignTime added in v0.4.0

func ParseSignTime(layout string, str string) (time.Time, error)

ParseSignTime parse string to time by layout, if layout is empty, parse as unix timestamp.

func ValuesFromCanonical added in v0.4.0

func ValuesFromCanonical(src, deli1, deli2 string) map[string]string

ValuesFromCanonical attempts to extract the value of a canonical string. a canonical string is a string of key value pairs separated by deli1 and deli2

func ValuesFromHeader added in v0.4.0

func ValuesFromHeader(r *http.Request, header string, valuePrefix string, prefixLen int) ([]string, error)

ValuesFromHeader returns functions that extract values from the request header. valuePrefix is a parameter to remove the first part (prefix) of the extracted value. This is useful if header value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to remove is `<auth-scheme> ` note the space at the end. In the case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `. In the case of NewJWT tokens `Authorization: Bearer <token>` prefix is `Bearer `. If the prefix is left empty, the whole value is returned.

Types

type Algorithm added in v0.4.0

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

func (*Algorithm) UnmarshalText added in v0.4.0

func (a *Algorithm) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Authorization

type Authorization struct {
	Type        string `yaml:"type,omitempty" json:"type,omitempty"`
	Credentials string `yaml:"credentials,omitempty" json:"credentials,omitempty"`
}

Authorization contains HTTP authorization credentials.

type BasicAuth

type BasicAuth struct {
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password,omitempty" json:"password,omitempty"`
}

BasicAuth contains basic HTTP authentication credentials.

type ClientConfig

type ClientConfig struct {
	TransportConfig
	Timeout time.Duration `yaml:"timeout" json:"timeout"`
	// The HTTP basic authentication credentials for the targets.
	BasicAuth *BasicAuth `yaml:"basicAuth,omitempty" json:"basicAuth,omitempty"`
	// The HTTP authorization credentials for the targets.
	Authorization *Authorization `yaml:"authorization,omitempty" json:"authorization,omitempty"`
	// The OAuth2 client credentials used to fetch a token for the targets.
	OAuth2 *OAuth2Config `yaml:"oauth2,omitempty" json:"oauth2,omitempty"`
	// contains filtered or unexported fields
}

ClientConfig is for an extension http.Client. It can be used to configure a client with configuration.

func NewClientConfig added in v0.4.0

func NewClientConfig(cnf *conf.Configuration, opts ...Option) (cfg *ClientConfig, err error)

NewClientConfig creates a new ClientConfig by options.

func (*ClientConfig) Client added in v0.4.0

func (c *ClientConfig) Client(ctx context.Context, t *oauth2.Token) (*http.Client, error)

Client returns an HTTP client using the provided token.

func (*ClientConfig) Exchange added in v0.4.0

func (c *ClientConfig) Exchange(ctx context.Context, code string, opts ...oauth2.AuthCodeOption) (*oauth2.Token, error)

Exchange converts an authorization code into a token if you use oauth2 config.

func (*ClientConfig) TokenSource added in v0.4.0

func (c *ClientConfig) TokenSource(ctx context.Context) oauth2.TokenSource

TokenSource returns a default token source base on clientcredentials.Config. it called in NewClient

func (*ClientConfig) Validate

func (c *ClientConfig) Validate() error

type DefaultSigner added in v0.4.0

type DefaultSigner struct {
	*SignerConfig
}

func (*DefaultSigner) AttachData added in v0.4.0

func (s *DefaultSigner) AttachData(_ *SigningCtx) error

func (*DefaultSigner) AttachRequest added in v0.4.0

func (s *DefaultSigner) AttachRequest(r *http.Request, ctx *SigningCtx)

AttachRequest attach the signature to http request.

func (*DefaultSigner) BuildBodyDigest added in v0.4.0

func (s *DefaultSigner) BuildBodyDigest(r *http.Request, ctx *SigningCtx) (err error)

func (*DefaultSigner) BuildCanonicalHeaders added in v0.4.0

func (s *DefaultSigner) BuildCanonicalHeaders(r *http.Request, ctx *SigningCtx) error

BuildCanonicalHeaders implements Signer interface. if a scope-key in the header is empty, it will be ignored.

func (*DefaultSigner) BuildCanonicalQueryString added in v0.4.0

func (s *DefaultSigner) BuildCanonicalQueryString(r *http.Request, ctx *SigningCtx) error

func (*DefaultSigner) BuildCanonicalRequest added in v0.4.0

func (s *DefaultSigner) BuildCanonicalRequest(r *http.Request, ctx *SigningCtx) (err error)

func (*DefaultSigner) BuildCanonicalUri added in v0.4.0

func (s *DefaultSigner) BuildCanonicalUri(r *http.Request, ctx *SigningCtx) error

func (*DefaultSigner) CalculateSignature added in v0.4.0

func (s *DefaultSigner) CalculateSignature(ctx *SigningCtx) error

func (*DefaultSigner) StringToSign added in v0.4.0

func (s *DefaultSigner) StringToSign(ctx *SigningCtx) error

type Middleware added in v0.4.0

type Middleware func(http.RoundTripper) http.RoundTripper

Middleware is our middleware creation functionality.

func BaseAuth added in v0.4.0

func BaseAuth(username, password string) Middleware

BaseAuth is a middleware that adds basic auth to the request.

type OAuth2Config added in v0.4.0

type OAuth2Config struct {
	oauth2.Config `yaml:",inline" json:",inline"`
	// StoreKey is the name of the cache driver which is used to store token.
	// Default is empty. If StoreKey is empty, the token will not be cached.
	StoreKey       string `json:"storeKey" yaml:"storeKey"`
	EndpointParams url.Values
	// contains filtered or unexported fields
}

OAuth2Config is a wrapper around oauth2.Config that allows for custom.

func (*OAuth2Config) SetOAuthStorage added in v0.4.0

func (oa *OAuth2Config) SetOAuthStorage(ts TokenStorage) error

SetOAuthStorage set TokenStorage to OAuth2Config

type Option added in v0.4.0

type Option func(c *ClientConfig)

func WithBase added in v0.4.0

func WithBase(base http.RoundTripper) Option

func WithMiddleware added in v0.4.0

func WithMiddleware(middleware ...Middleware) Option

func WithTokenSource added in v0.4.0

func WithTokenSource(source oauth2.TokenSource) Option

WithTokenSource set oauth2 token source after oauth2 config initialized

func WithTokenStorage added in v0.4.0

func WithTokenStorage(storage TokenStorage) Option

WithTokenStorage set oauth2 token storage after oauth2 config initialized

type ProxyConfig

type ProxyConfig struct {
	// HTTP proxy server to use to connect to the targets.
	ProxyURL string `yaml:"proxyUrl,omitempty" json:"proxyUrl,omitempty"`
	// NoProxy contains addresses that should not use a proxy.
	NoProxy string `yaml:"noProxy,omitempty" json:"noProxy,omitempty"`
	// ProxyConnectHeader optionally specifies headers to send to
	// proxies during CONNECT requests. Assume that at least _some_ of
	// these headers are going to contain secrets and use Secret as the
	// value type instead of string.
	ProxyConnectHeader http.Header `yaml:"proxyConnectHeader,omitempty" json:"proxyConnectHeader,omitempty"`
}

func (ProxyConfig) ProxyFunc

func (p ProxyConfig) ProxyFunc() func(req *http.Request) (*url.URL, error)

func (ProxyConfig) Validate

func (p ProxyConfig) Validate() error

type Signature added in v0.4.0

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

Signature is sign executor for clients.

func NewSignature added in v0.4.0

func NewSignature(opts ...SignerOption) (*Signature, error)

NewSignature create signature by configuration and options.

func (*Signature) Sign added in v0.4.0

func (s *Signature) Sign(r *http.Request, nonce string, signTime time.Time) error

func (*Signature) Verify added in v0.4.0

func (s *Signature) Verify(r *http.Request, nonce string, signTime time.Time) (err error)

type Signer added in v0.4.0

type Signer interface {
	// BuildCanonicalRequest build and prepare data by canonical the request to use in sign action.
	BuildCanonicalRequest(r *http.Request, ctx *SigningCtx) error
	// AttachData attach data that need to sign.
	AttachData(ctx *SigningCtx) error
	// CalculateSignature calculate signature by ctx.
	CalculateSignature(ctx *SigningCtx) error
	// AttachRequest attach the signature to http request suck as set header, add the signature to request.
	AttachRequest(r *http.Request, ctx *SigningCtx)
}

func NewDefaultSigner added in v0.4.0

func NewDefaultSigner(config *SignerConfig) (Signer, error)

NewDefaultSigner create default signer with configuration

func NewTokenSigner added in v0.4.0

func NewTokenSigner(config *SignerConfig) (Signer, error)

type SignerConfig added in v0.4.0

type SignerConfig struct {
	// Credentials default id="" secret=""
	Credentials map[string]string `yaml:"credentials" json:"credentials"`
	// static values in signature
	Data map[string]string `yaml:"data" json:"data"`
	// SignedLookups will be ordered.
	SignedLookups map[string]string `yaml:"signedLookups" json:"signedLookups"`
	// SignatureLookup indicate where to find the whole Signature info. Default: header:Authorization
	AuthLookup string `yaml:"authLookup" json:"authLookup"`
	// AuthScheme indicate the scheme in authLookup
	AuthScheme string `yaml:"authScheme" json:"authScheme"`
	// AuthHeaders indicate the headers appended to auth header.
	AuthHeaders []string `yaml:"authHeaders" json:"authHeaders"`
	// AuthHeaderDelimiter is the delimiter used to separate fields in the header string.
	// Default value ", "
	AuthHeaderDelimiter string `yaml:"authHeaderDelimiter" json:"authHeaderDelimiter"`
	// TimestampKey is the name of timestamp in SignedLookups.
	TimestampKey string `yaml:"timestampKey" json:"timestampKey"`
	// NonceKey is the name of nonce.
	NonceKey   string    `yaml:"nonceKey" json:"nonceKey"`
	Algorithm  Algorithm `yaml:"algorithm" json:"algorithm"`
	DateFormat string    `yaml:"dateFormat" json:"dateFormat"`
	NonceLen   uint8     `yaml:"nonceLen" json:"nonceLen"`
	// Delimiter is the delimiter used to separate fields in the signature string.
	// Default value "\n"
	Delimiter string `yaml:"delimiter" json:"delimiter"`
	// UnsignedPayload calls BuildBodyDigest if false, default false.
	UnsignedPayload bool `yaml:"unsignedPayload" json:"unsignedPayload"`
	// default false
	DisableURIPathEscaping bool `yaml:"disableURIPathEscaping" json:"disableURIPathEscaping"`
	// just calculate string to sign, not attach to request
	Dry bool `yaml:"-" json:"-"`
	// ScopeHeaders is a list of http headers to be included in signature, parsed from SignedLookups.
	// ScopeHeaders must confirm sort func.
	ScopeHeaders []string `yaml:"-" json:"-"`
	// SignedQueries is a list of http queries to be included in signature.
	ScopeQueries []string `yaml:"-" json:"-"`
	// SignatureQueryKey parse from AuthLookup
	SignatureQueryKey string `yaml:"-" json:"-"`
	// SignatureHeaderKey parse from AuthLookup
	SignatureHeaderKey string `yaml:"-" json:"-"`
	// contains filtered or unexported fields
}

SignerConfig is hold setting for Signer.

func NewSignerConfig added in v0.4.0

func NewSignerConfig(opts ...SignerOption) (*SignerConfig, error)

NewSignerConfig create signer config by configuration and options.

func (*SignerConfig) BuildSigner added in v0.4.0

func (s *SignerConfig) BuildSigner(opts ...SignerOption) (*Signature, error)

func (*SignerConfig) GetAccessKeyID added in v0.4.0

func (s *SignerConfig) GetAccessKeyID() string

func (*SignerConfig) GetAccessKeySecret added in v0.4.0

func (s *SignerConfig) GetAccessKeySecret() string

func (*SignerConfig) Validate added in v0.4.0

func (s *SignerConfig) Validate() error

type SignerOption added in v0.4.0

type SignerOption func(*SignerConfig)

func WithConfiguration added in v0.4.0

func WithConfiguration(cnf *conf.Configuration) SignerOption

func WithSigner added in v0.4.0

func WithSigner(newSigner func(config *SignerConfig) (Signer, error)) SignerOption

type SigningCtx added in v0.4.0

type SigningCtx struct {
	Request              *http.Request
	Nonce                string
	BodyDigest           string
	SignedHeaders        string
	CanonicalUri         string
	CanonicalQueryString string
	SignTime             time.Time
	Signature            string
	CredentialString     string
	StringToSign         string
	// CanonicalHeaders is built by sorted scope headers.
	CanonicalHeaders []string
	SignedVals       map[string]string
}

SigningCtx holds info for signature

type TokenSigner added in v0.4.0

type TokenSigner struct {
	*SignerConfig
	// contains filtered or unexported fields
}

TokenSigner is s simple signer used AccessToken to signature http request.

sign element: access_token;timestamp;url.

func (TokenSigner) AttachData added in v0.4.0

func (s TokenSigner) AttachData(_ *SigningCtx) error

func (TokenSigner) AttachRequest added in v0.4.0

func (s TokenSigner) AttachRequest(r *http.Request, ctx *SigningCtx)

func (TokenSigner) BuildCanonicalRequest added in v0.4.0

func (s TokenSigner) BuildCanonicalRequest(r *http.Request, ctx *SigningCtx) error

func (TokenSigner) CalculateSignature added in v0.4.0

func (s TokenSigner) CalculateSignature(ctx *SigningCtx) error

func (TokenSigner) StringToSign added in v0.4.0

func (s TokenSigner) StringToSign(ctx *SigningCtx) error

type TokenSource added in v0.4.0

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

func (*TokenSource) Token added in v0.4.0

func (t *TokenSource) Token() (*oauth2.Token, error)

type TokenStorage added in v0.4.0

type TokenStorage interface {
	Token() (*oauth2.Token, error)
	SetToken(*oauth2.Token) error
}

TokenStorage is an interface to store and retrieve oauth2 token

type TransportConfig

type TransportConfig struct {
	*ProxyConfig `yaml:",inline" json:",inline"`
	// TLSConfig to use to connect to the targets.
	TLS *conf.TLS `yaml:"tls,omitempty" json:"tls,omitempty"`
}

Jump to

Keyboard shortcuts

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