http

package
v0.17.2 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2021 License: AGPL-3.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuditLog

func AuditLog(logger *log.Logger, roles *auth.Roles, f http.HandlerFunc) http.HandlerFunc

AuditLog returns a handler function that wraps f and logs the HTTP request and response before sending the response status code back to the client.

func EnforcePolicies

func EnforcePolicies(roles *auth.Roles, f http.HandlerFunc) http.HandlerFunc

EnforcePolicies returns an http.Handler that verifies the request using policy/role based identity authentication before calling f.

If the request is not authorized it will return an error to the client and does not call f.

func Error

func Error(w http.ResponseWriter, err error) error

Error sends the given err as JSON error response to w.

If err has a 'Status() int' method then Error sets the response status code to err.Status(). Otherwise, it will send 500 (internal server error).

If err is nil then Error will send the status code 500 and an empty JSON response body - i.e. '{}'.

func ErrorTrailer added in v0.13.0

func ErrorTrailer(w http.ResponseWriter, err error)

ErrorTrailer sends the given err as JSON error to w as HTTP trailer.

ErrorTrailer should be used to communicate an error to the client if the error occurred after a response has been sent to client.

A caller of ErrorTrailer has to pre-define the:

  • Status
  • Error

trailers via http.ResponseWriter.Header().Set("Trailer", "Status, Error")

If err has a 'Status() int' method then Error sets the response status code to err.Status(). Otherwise, it will send 500 (internal server error).

If err is nil then ErrorTrailer will send the status code 500 and an empty JSON error - i.e. '{}'.

func HandleAssignIdentity

func HandleAssignIdentity(roles *auth.Roles) http.HandlerFunc

func HandleCreateKey

func HandleCreateKey(manager *key.Manager) http.HandlerFunc

HandleCreateKey returns a handler function that generates a new random Secret and stores in the Store under the request name, if it doesn't exist.

It infers the name of the new Secret from the request URL - in particular from the URL's path base. See: https://golang.org/pkg/path/#Base

func HandleDecryptKey

func HandleDecryptKey(manager *key.Manager) http.HandlerFunc

HandleDecryptKey returns an http.HandlerFunc that decrypts and verifies a ciphertext sent by the client produced by HandleEncryptKey or HandleGenerateKey.

If the client has provided a context value during encryption / key generation then the client has to provide the same context value again.

func HandleDeleteKey

func HandleDeleteKey(manager *key.Manager) http.HandlerFunc

func HandleDeletePolicy

func HandleDeletePolicy(roles *auth.Roles) http.HandlerFunc

func HandleEncryptKey added in v0.10.0

func HandleEncryptKey(manager *key.Manager) http.HandlerFunc

HandleEncryptKey returns an http.HandlerFunc that encrypts and authenticates a plaintext message sent by the client.

It should be used to encrypt small amounts of data - like other cryptographic keys or small metadata objects. HandleEncryptKey should not be used to encrypt large data streams.

If the client provides an optional context value the returned http.HandlerFunc will authenticate but not encrypt the context value. The client has to provide the same context value again for decryption.

func HandleForgetIdentity

func HandleForgetIdentity(roles *auth.Roles) http.HandlerFunc

func HandleGenerateKey

func HandleGenerateKey(manager *key.Manager) http.HandlerFunc

HandleGenerateKey returns an http.HandlerFunc that generates a data encryption key (DEK) at random and returns the plaintext and ciphertext version of the DEK to the client. The DEK ciphertext is the DEK plaintext encrypted with the secret key from the store.

HandleGenerateKey behaves as HandleEncryptKey where the plaintext is a randomly generated key.

If the client provides an optional context value the returned http.HandlerFunc will authenticate but not encrypt the context value. The client has to provide the same context value again for decryption.

func HandleImportKey

func HandleImportKey(manager *key.Manager) http.HandlerFunc

HandleImportKey returns a handler function that reads a secret value from the request body and stores in the Store under the request name, if it doesn't exist.

It infers the name of the new Secret from the request URL - in particular from the URL's path base. See: https://golang.org/pkg/path/#Base

func HandleListIdentities

func HandleListIdentities(roles *auth.Roles) http.HandlerFunc

func HandleListKeys added in v0.13.0

func HandleListKeys(manager *key.Manager) http.HandlerFunc

HandleListKeys returns an http.HandlerFunc that lists all keys stored by the secret.Store that match the glob pattern specified by the client.

If an error occurs after a response has been written to the client the returned http.HandlerFunc sends an HTTP trailer containing this error. The client is expected to check for an error trailer and only consider the listing complete if it receives no such trailer.

func HandleListPolicies

func HandleListPolicies(roles *auth.Roles) http.HandlerFunc

func HandleMetrics added in v0.12.0

func HandleMetrics(metrics *metric.Metrics) http.HandlerFunc

HandleMetrics returns an HTTP handler that collects all outstanding metrics information and writes them to the client.

func HandleReadPolicy

func HandleReadPolicy(roles *auth.Roles) http.HandlerFunc

func HandleStatus added in v0.16.1

func HandleStatus(version string, certificate *Certificate, log *xlog.Target) http.HandlerFunc

HandleStatus returns a handler function that returns status information, like server version and server up-time, as JSON object to the client.

The handler function should not return any internal data - like keystore backend, cache expiry, etc.

func HandleTraceAuditLog

func HandleTraceAuditLog(target *xlog.Target) http.HandlerFunc

HandleTraceAuditLog returns an HTTP handler that adds the client as a log target. The client will then receive all audit events.

The returned handler is a long-running server task that will wait for the client to close the connection resp. until the request context is done. Therefore, it will not work properly with (write) timeouts.

func HandleTraceErrorLog added in v0.7.0

func HandleTraceErrorLog(target *xlog.Target) http.HandlerFunc

HandleTraceErrorLog returns an HTTP handler that adds the client as a log target. The client will then receive all error events.

The returned handler is a long-running server task that will wait for the client to close the connection resp. until the request context is done. Therefore, it will not work properly with (write) timeouts.

In contrast to HandleTraceAuditLog, HandleTraceErrorLog wraps the http.ResponseWriter such that whatever log logs gets converted to the JSON:

{
  "message":"<log-output>",
}

func HandleVersion

func HandleVersion(version string) http.HandlerFunc

HandleVersion returns a handler function that returns the given version as JSON. In particular, it returns a JSON object:

{
  "version": "<version>"
}

func HandleWritePolicy

func HandleWritePolicy(roles *auth.Roles) http.HandlerFunc

func LimitRequestBody

func LimitRequestBody(n int64, f http.HandlerFunc) http.HandlerFunc

LimitRequestBody returns an http.HandlerFunc that limits the body of incoming requests to n bytes before calling f.

It should be used to limit the amount of data a client can send to prevent flooding/DoS attacks.

func RequireMethod

func RequireMethod(method string, f http.HandlerFunc) http.HandlerFunc

RequireMethod returns an http.HandlerFunc that checks whether the method of a client request matches the expected method before calling f.

If the client request method does not match the given method it returns an error and http.StatusMethodNotAllowed to the client.

func RetryReader added in v0.11.0

func RetryReader(r io.ReadSeeker) io.ReadSeeker

RetryReader returns an io.ReadSeeker that can be used as request body for retryable requests via Seek(0, io.SeekStart). The returned io.ReadSeeker implements io.Closer.

If r does not implement io.Closer RetryReader returns an io.ReadSeeker that implements io.Closer as nop.

func TLSProxy

func TLSProxy(proxy *auth.TLSProxy, f http.HandlerFunc) http.HandlerFunc

TLSProxy returns a handler function that checks if the request has been forwarded by a TLS proxy and, if so, verifies and adjusts the request such that handlers further down the stack can treat it as sent by the actual client.

Therefore, it replaces the proxy certificate in the TLS connection state with the client certificate forwarded by the proxy as part of the request headers.

func Timeout added in v0.13.0

func Timeout(after time.Duration, f http.HandlerFunc) http.HandlerFunc

Timeout returns an HTTP handler that aborts f after the given time limit.

The request times out when it takes longer then the given time limit to read the request body and write a response back to the client.

Once the timeout exceeds, any further Write call by f to the http.ResponseWriter will return http.ErrHandlerTimeout. Further, if the timeout exceeds before f writes an HTTP status code then Timeout will return 503 ServiceUnavailable to the client.

Timeout cancels the request context before aborting f.

func ValidatePath

func ValidatePath(apiPattern string, f http.HandlerFunc) http.HandlerFunc

ValidatePath returns an handler function that verifies that the request URL.Path matches apiPattern before calling f. If the path does not match the apiPattern it returns the bad request status code (400) to the client.

ValidatePath uses the standard library path glob matching for pattern matching.

Types

type AuditResponseWriter added in v0.13.0

type AuditResponseWriter struct {
	http.ResponseWriter

	// Logger will receive the kes.AuditEvent produced
	// on the first invocation of Write resp. WriteHeader.
	Logger *log.Logger

	URL      url.URL      // The request URL
	Identity kes.Identity // The client's X.509 identity
	Time     time.Time    // The time when we receive the request
	// contains filtered or unexported fields
}

AuditResponseWriter is an http.ResponseWriter that writes a kes.AuditEvent to a log.Logger after sending the response status code and before response body.

func (*AuditResponseWriter) Flush added in v0.13.0

func (w *AuditResponseWriter) Flush()

Flush flushes whatever has been written to w to the receiver.

func (*AuditResponseWriter) Write added in v0.13.0

func (w *AuditResponseWriter) Write(b []byte) (int, error)

Write writes b to the underlying http.ResponseWriter. If no status code has been sent via WriteHeader, Write sends the status code 200 OK.

func (*AuditResponseWriter) WriteHeader added in v0.13.0

func (w *AuditResponseWriter) WriteHeader(statusCode int)

WriteHeader writes the given statusCode to the underlying http.ResponseWriter and then writes a kes.AuditEvent to w's log.Logger.

WriteHeader does not produce another kes.AuditEvent when invoked again.

type Certificate added in v0.16.1

type Certificate struct {
	ErrorLog *xlog.Target
	// contains filtered or unexported fields
}

Certificate is a X.509 TLS certificate.

func LoadCertificate added in v0.16.1

func LoadCertificate(certFile, keyFile, password string) (*Certificate, error)

LoadCertificate returns a X.509 TLS certificate from the given certificate and private key files.

func (*Certificate) GetCertificate added in v0.16.1

func (c *Certificate) GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate returns a X.509 TLS certificate based on the TLS client hello.

func (*Certificate) ReloadAfter added in v0.16.1

func (c *Certificate) ReloadAfter(ctx context.Context, interval time.Duration)

ReloadAfter reloads the X.509 TLS certificate from its certificate resp. private key file periodically in an infinite loop.

Once the ctx.Done() channel returns ReloadAfter exits.

type FlushWriter added in v0.13.0

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

A FlushWriter wraps an io.Writer and performs a flush operation after every write call if the wrapped io.Writer implements http.Flusher.

A FlushWriter is useful when (small) data should be sent to the receiver as soon as possible.

A FlushWriter avoids latency added by buffering the data. However, it may impact performance since it may increase the number of OS syscalls.

func NewFlushWriter added in v0.13.0

func NewFlushWriter(w io.Writer) FlushWriter

NewFlushWriter returns a new FlushWriter that wraps w.

func (FlushWriter) Flush added in v0.13.0

func (w FlushWriter) Flush()

func (FlushWriter) Write added in v0.13.0

func (w FlushWriter) Write(p []byte) (int, error)

type Retry added in v0.11.0

type Retry struct {
	// Client is the underlying HTTP client.
	// Using Client directly bypasses the
	// retry mechanism.
	http.Client

	// N is the number of retry attempts. If a request
	// fails because of a temporary network error or
	// 5xx response code then Retry keeps sending the
	// same request N times before giving up and returning
	// the last error encountered.
	N uint

	// Delay is the duration Retry waits at least before
	// retrying a request.
	Delay time.Duration

	// Jitter is the maximum duration Retry adds to Delay.
	// Retry waits at most Delay + Jitter before retrying
	// a request.
	//
	// In particular, Retry chooses a pseudo-random
	// duration [0, Jitter) and adds it do Delay.
	Jitter time.Duration
}

Retry wraps an HTTP client and retries requests when they fail because of a temporary network error or a 5xx response status code.

Its zero value is a usable client that uses http.DefaultTransport and may retry a request a few times before giving up.

If a request contains a non-nil body then this body must implement io.Seeker. Any io.ReadSeeker can be turned into a request body via the RetryReader function.

Retry retries a request at most N times and waits at least Delay and at most Delay + Jitter before sending the request again. If not specified then Retry uses sane default values for N, Delay and Jitter.

func (*Retry) Do added in v0.11.0

func (r *Retry) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client and as specified by http.Client.

If the request fails due to a temporary network error or the server returns a 5xx response then Do retries the request N times.

If non-nil, the request body must implement io.Seeker.

Any returned error will be of type *url.Error. The url.Error value's Timeout method will report true if request timed out or was canceled.

func (*Retry) Get added in v0.11.0

func (r *Retry) Get(url string) (*http.Response, error)

Get issues a GET to the specified URL as specified by http.Client. It follows redirects after calling the underlying Client's CheckRedirect function.

If the GET fails due to a temporary network error or 5xx server response then GET retries the request N times.

func (*Retry) Head added in v0.11.0

func (r *Retry) Head(url string) (*http.Response, error)

Head issues a HEAD to the specified URL as specified by http.Client. It follows redirects after calling the underlying Client's CheckRedirect function.

If the HEAD fails due to a temporary network error or 5xx server response then Head retries the request N times.

func (*Retry) Post added in v0.11.0

func (r *Retry) Post(url, contentType string, body io.Reader) (*http.Response, error)

Post issues a POST to the specified URL as specified by http.Client. The provided body must implement io.Seeker and io.Closer. To obtain an io.Closer from an io.ReadSeeker refer to the RetryReader function.

Caller should close resp.Body when done reading from it.

If the POST fails due to a temporary network error or 5xx server response the Post retries the request N times.

See the Retry.Do method documentation for details on how redirects are handled.

func (*Retry) PostForm added in v0.11.0

func (r *Retry) PostForm(url string, data url.Values) (*http.Response, error)

PostForm issues a POST to the specified URL as specified by http.Client, with data's keys and values URL-encoded as the request body.

The Content-Type header is set to application/x-www-form-urlencoded.

If the POST fails due to a temporary network error or 5xx server response the Post retries the request N times.

See the Client.Do method documentation for details on how redirects are handled.

Jump to

Keyboard shortcuts

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