easytls

package module
v1.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2019 License: MIT Imports: 20 Imported by: 2

README

easy-tls

A set of packages for quickly and easily developing TLS-enabled Web Servers and Clients.

Documentation

Overview

Package easytls is intended to provide a simplification and abstraction layer for quickly creating HTTP(S) enabled web applications. This module intends to provide a simple API to illustrate the parameters needed for proper TLS security, as well as providing simpler methods for performing standard HTTP(S) operations

This package implements two fundamental types, SimpleServer and SimpleClient. These represent a slightly higher level of abstraction for HTTP(S) Servers and Clients. Each of these is a thin wrapper over the standard library http.Client and http.Server, but with common elements abstracted away.

The full TLS settings of this module are defined within the tls-bundle.go file, and the TLSBundle struct. This is intended to allow for commonly required TLS settings to be implemented without explicitly constructing the tls.Config. For example, the full set of accepted Root and Client CA's to trust can be specified by adding the filepaths to the certificates into the AuthorityCertificate slice. These will be read, loaded, and added to a tls.CertPool in the correct format for use with the tls.Config. Likewise with the KeyPair substructs for the Client certificates. The goal of this struct is to allow for common TLS settings such as an application with a dedicated client/server TLS pair to be defined by the paths to the necessary TLS resources, rather than the implementer needing to remember and tick every box along the way.

The SimpleServer struct is heavily based on the gorilla/mux router, as most of the middleware/handler registration is based on that, although work is being done to allow this to work with the default http.ServeMux. A SimpleServer is built from a TLSBundle and an Address to listen on, and can be completed by adding a configured Router. This Router is by default initialized with NotFound and MethodNotAccepted handlers, returning the corresponding error codes. Further routes can be added, typically formatted as SimpleHandlers. This is basic grouping of the HTTP Handler to call, the methods it accepts, and the path to match on. The goal of this is to provide a way to programatically register routes, so that routes can be defined succinctly.

A SimpleServer can be built into a Reverse Proxy. By supplying the Server with a SimpleClient to use to forward the traffic, and the function which determines the remote host to forward to based on the incoming request, a full Reverse Proxy can be constructed. Depending on the TLS and HTTP protocol levels of each component, this Reverse Proxy can easily be used as an HTTP<->HTTPS converter, an HTTP/1.x <-> HTTP/2.0 converter, or any other standard reverse proxy functionality.

The SimpleClient struct is effectively a wrapper of the http.Client, with a more easily accessible flag to determine whether or not TLS is enabled. This also provides explicit functions for each of the Standard HTTP methods, along with a common API for accessing them. Building requests is completely abstracted away, with the limitation of not allowing multipart requests.

Index

Constants

This section is empty.

Variables

View Source
var ClientFrameworkVersion = SemanticVersion{
	MajorRelease: 1,
	MinorRelease: 0,
	Build:        16,
}

ClientFrameworkVersion represents the current Semantic Version of the Client-side Plugin agent framework

View Source
var ServerFrameworkVersion = SemanticVersion{
	MajorRelease: 1,
	MinorRelease: 0,
	Build:        16,
}

ServerFrameworkVersion represents the current Semantic Version of the Server-side Plugin agent framework

Functions

func Accepts added in v1.0.18

func Accepts(Is, AcceptsMin, AcceptsMax SemanticVersion) bool

Accepts determines if a given version is accepted for a set of minimum and maximum acceptable versions

func AddHandlers added in v1.0.1

func AddHandlers(verbose bool, s *SimpleServer, r *mux.Router, Handlers ...SimpleHandler)

AddHandlers will add the given handlers to the router, with the verbose flag determining if a log message should be generated for each added route.

func AddMiddlewares added in v1.0.1

func AddMiddlewares(r *mux.Router, middlewares ...MiddlewareHandler)

AddMiddlewares is a convenience wrapper for the mux.Router "Use" function

func MiddlewareDefaultLogger added in v1.0.18

func MiddlewareDefaultLogger(next http.Handler) http.Handler

MiddlewareDefaultLogger provides a simple logging middleware, to view incoming connections as they arrive.

func MiddlewareLimitConnectionRate added in v1.0.18

func MiddlewareLimitConnectionRate(CycleTime time.Duration, verbose bool) func(http.Handler) http.Handler

MiddlewareLimitConnectionRate will limit the server to a maximum of one connection per CycleTime.

func MiddlewareLimitMaxConnections added in v1.0.18

func MiddlewareLimitMaxConnections(ConnectionLimit int, verbose bool) func(http.Handler) http.Handler

MiddlewareLimitMaxConnections will provide a mechanism to strictly limit the maximum number of connections served.

func NewDefaultRouter added in v1.0.1

func NewDefaultRouter() *mux.Router

NewDefaultRouter will initialize a new HTTP Router, based on the gorilla/mux implementation.

func NewRouter added in v1.0.0

func NewRouter(s *SimpleServer, Handlers []SimpleHandler, Middlewares ...MiddlewareHandler) *mux.Router

NewRouter will build a new complex router, with the given routes, and middlewares. More can be added later, if needed.

func NewTLSConfig

func NewTLSConfig(TLS *TLSBundle) (*tls.Config, error)

NewTLSConfig will convert the TLSBundle, containing the filenames of the relevant certificates and Authorization policy, into a workable tls.Config object, ready to be used by either a SimpleClient or SimpleServer application.

Types

type ClientPlugin added in v1.0.18

type ClientPlugin struct {

	// A Client Plugin is composed of a generic plugin plus an API Contract.
	Plugin

	// A ClientPlugin must implement the full API Contract.
	ClientPluginAPI
}

ClientPlugin represents a EasyTLS-compatible Plugin to be used with an EasyTLS SimpleClient.

func InitializeClientPlugin added in v1.0.18

func InitializeClientPlugin(Filename string, FrameworkVersion SemanticVersion) (*ClientPlugin, error)

InitializeClientPlugin will initialize and return a Client Plugin, ready to be registered by a Client Plugin Agent.

type ClientPluginAPI added in v1.0.18

type ClientPluginAPI struct {

	// Start a plugin.
	//
	// This will provide a SimpleClient object for the Plugin to use for any HTTP(S) operations it should take.
	// If a non-nil error is returned, this indicates that the initialization failed, and the Stop command should be used.
	// No Plugins should function if Init returns a non-nil error.
	Init func(*SimpleClient) error
}

ClientPluginAPI represents the API contract a Client-Plugin must satisfy to be used by this framework.

type ClientPluginAgent added in v1.0.18

type ClientPluginAgent struct {
	PluginSearchFolder string
	// contains filtered or unexported fields
}

ClientPluginAgent represents the a Plugin Manager agent to be used with a SimpleClient.

func NewClientAgent added in v1.0.18

func NewClientAgent(Client *SimpleClient, Version SemanticVersion, PluginFolder string, Logger io.WriteCloser) (*ClientPluginAgent, error)

NewClientAgent will create a new Client Plugin agent, ready to register plugins.

func (*ClientPluginAgent) Close added in v1.0.18

func (CA *ClientPluginAgent) Close() error

Close down the plugin agent.

func (*ClientPluginAgent) RegisterPlugins added in v1.0.18

func (CA *ClientPluginAgent) RegisterPlugins() error

RegisterPlugins will configure and register all of the plugins in the previously specified PluginFolder. This will not start any of the plugins, but will only load the necessary symbols from them.

func (*ClientPluginAgent) Run added in v1.0.18

func (CA *ClientPluginAgent) Run(blocking bool) error

Run will start the ClientPlugin Agent, starting each of the registered plugins. blocking represents if the rest of the application should block on this call or not.

func (*ClientPluginAgent) Stop added in v1.0.18

func (CA *ClientPluginAgent) Stop() error

Stop will cause ALL of the currentlyRunning Plugins to safely stop.

type KeyPair

type KeyPair struct {
	Certificate string
	Key         string
}

KeyPair represents the filenames to a pair of matching TLS Key/Certificate files.

type MiddlewareHandler added in v1.0.0

type MiddlewareHandler func(http.Handler) http.Handler

MiddlewareHandler represents the general format for a Middleware handler.

type Plugin added in v1.0.18

type Plugin struct {

	// Filename represents purely the filename component of the plugin file.
	Filename string

	// Filepath represents the full path to the plugin file.
	Filepath string

	// All Plugins implement the basic API Contract.
	// This must be a struct and not an interface because the actual function bodies will be returned from loading the plugin file.
	PluginAPI
}

Plugin represents the most generic features and functionality of a Plugin Object

type PluginAPI added in v1.0.18

type PluginAPI struct {

	// Query the current status of the plugin.
	//
	// This must return an output-only unbuffered channel, allowing the plugin to directly send status messages as they are generated.
	// If this channel is not read from, it will not block itself, and will only present the most recent message.
	Status func() (<-chan PluginStatus, error)

	// Query the Semantic Versioning compatabilities of the plugin.
	//
	// This will accept the Semantic Version of the Plugin at hand and compare it against it's set of acceptable framework versions.  A nil error implies compatability.
	Version func(SemanticVersion) error

	// Query the Name of the Plugin.
	//
	// This must return the name of the plugin, in canonical format.
	Name func() (string, error)

	// Stop the plugin.
	//
	// This must trigger a full stop of any internal behaviours of the plugin, only returning once ALL internal behaviours have halted.  This should return any and all errors which arise during shutdown and are not explicitly handled by the shutdown.  The Agent makes no guarantee on how long AFTER receiving the return value from this call the application will run for, so this must represent the FINAL valid state of a plugin.
	Stop func() error
}

PluginAPI represents the base API contract which must be satisfied by ANY plugin.

type PluginStatus added in v1.0.18

type PluginStatus struct {
	Message string
	Error   error
	IsFatal bool
}

PluginStatus represents a single status message from a given EasyTLS-compliant plugin.

func (PluginStatus) String added in v1.0.18

func (S PluginStatus) String() string

type ReverseProxyRouterFunc added in v1.0.18

type ReverseProxyRouterFunc func(*http.Request) string

ReverseProxyRouterFunc will take a request, and determine which URL Host to forward it to. This result must be an IP:Port combination as standard in the http package.

type SemanticVersion added in v1.0.18

type SemanticVersion struct {
	MajorRelease int
	MinorRelease int
	Build        int
}

SemanticVersion represents a useable semantic version number. This can be used to assert compatability between plugins, agents, and frameworks.

func ParseVersion added in v1.0.18

func ParseVersion(v string) (*SemanticVersion, error)

ParseVersion allows for a SemanticVersion to be recovered from its string representation.

func (*SemanticVersion) String added in v1.0.18

func (v *SemanticVersion) String() string

type ServerPlugin added in v1.0.18

type ServerPlugin struct {

	// A Server Plugin is composed of a generic plugin plus an API Contract.
	Plugin

	// A ServerPlugin must implement the full API Contract.
	ServerPluginAPI
}

ServerPlugin represents a EasyTLS-compatible Plugin to be used with an EasyTLS SimpleServer.

func InitializeServerPlugin added in v1.0.18

func InitializeServerPlugin(Filename string, FrameworkVersion SemanticVersion) (*ServerPlugin, error)

InitializeServerPlugin will initialize and return a Server Plugin, ready to be registered by a Server Plugin Agent.

type ServerPluginAPI added in v1.0.18

type ServerPluginAPI struct {

	// Start a plugin.
	//
	// This will initialize the plugin, and return the set of Routes it can provide back to the SimpleServer.
	Init func() ([]SimpleHandler, error)
}

ServerPluginAPI represents the API contract a Server-Plugin must satisfy to be used by this framework.

type ServerPluginAgent added in v1.0.18

type ServerPluginAgent struct {
	PluginSearchFolder string
	// contains filtered or unexported fields
}

ServerPluginAgent represents the a Plugin Manager agent to be used with a SimpleServer.

func NewServerAgent added in v1.0.18

func NewServerAgent(PluginFolder string, Logger io.WriteCloser) (*ServerPluginAgent, error)

NewServerAgent will create a new Server Plugin agent, ready to register plugins.

func (*ServerPluginAgent) Close added in v1.0.18

func (SA *ServerPluginAgent) Close() error

Close down the plugin agent.

func (*ServerPluginAgent) RegisterPlugins added in v1.0.18

func (SA *ServerPluginAgent) RegisterPlugins() error

RegisterPlugins will configure and register all of the plugins in the previously specified PluginFolder. This will not start any of the plugins, but will only load the necessary symbols from them.

func (*ServerPluginAgent) Run added in v1.0.18

func (SA *ServerPluginAgent) Run(blocking bool) error

Run will start the ServerPlugin Agent, starting each of the registered plugins. blocking represents if the rest of the application should block on this SAll or not.

func (*ServerPluginAgent) Stop added in v1.0.18

func (SA *ServerPluginAgent) Stop() error

Stop will SAuse ALL of the currentlyRunning Plugins to safely stop.

type SimpleClient added in v1.0.0

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

SimpleClient is an extension of the standard http.Client implementation, with additional utility functions and wrappers to simplify using it.

func NewClientHTTP added in v1.0.0

func NewClientHTTP() (*SimpleClient, error)

NewClientHTTP will create a new SimpleClient, with no TLS settings enabled. This will accept raw HTTP only.

func NewClientHTTPS added in v1.0.0

func NewClientHTTPS(TLS *TLSBundle) (*SimpleClient, error)

NewClientHTTPS will create a new TLS-Enabled SimpleClient. This will

func (*SimpleClient) Connect added in v1.0.0

func (C *SimpleClient) Connect(URL *url.URL, Headers map[string][]string) error

Connect will (Not yet implemented)

func (*SimpleClient) Delete added in v1.0.0

func (C *SimpleClient) Delete(URL *url.URL, Headers map[string][]string) error

Delete represents the abstraction of the HTTP Delete request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of this function.

func (*SimpleClient) Do added in v1.0.18

func (C *SimpleClient) Do(req *http.Request) (*http.Response, error)

Do will perform a single pre-formatted request.

func (*SimpleClient) Get added in v1.0.0

func (C *SimpleClient) Get(URL *url.URL, Headers map[string][]string) (*http.Response, error)

Get represents the abstraction of the HTTP Get request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of the caller.

func (*SimpleClient) Head added in v1.0.0

func (C *SimpleClient) Head(URL *url.URL, Headers map[string][]string) (http.Header, error)

Head represents the abstraction of the HTTP Head request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of this function, as Head only returns the headers.

func (*SimpleClient) IsTLS added in v1.0.18

func (C *SimpleClient) IsTLS() bool

IsTLS exposes whether the SimpleClient is TLS or not.

func (*SimpleClient) Options added in v1.0.0

func (C *SimpleClient) Options(URL *url.URL, Headers map[string][]string) (*http.Response, error)

Options represents the abstraction of the HTTP Options request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of the caller.

func (*SimpleClient) Patch added in v1.0.0

func (C *SimpleClient) Patch(URL *url.URL, Contents io.ReadCloser, Headers map[string][]string) (*http.Response, error)

Patch represents the abstraction of the HTTP Patch request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of this function.

func (*SimpleClient) Post added in v1.0.0

func (C *SimpleClient) Post(URL *url.URL, Contents io.ReadCloser, Headers map[string][]string) (*http.Response, error)

Post represents the abstraction of the HTTP Post request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of the caller.

func (*SimpleClient) Put added in v1.0.0

func (C *SimpleClient) Put(URL *url.URL, Contents io.ReadCloser, Headers map[string][]string) (*http.Response, error)

Put represents the abstraction of the HTTP Put request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of the caller.

func (*SimpleClient) Trace added in v1.0.0

func (C *SimpleClient) Trace(URL *url.URL, Headers map[string][]string) (*http.Response, error)

Trace represents the abstraction of the HTTP Trace request, accounting for creating the request, setting headers, and asserting a valid status code. Closing the response body is the responsibility of the caller.

type SimpleHandler added in v1.0.0

type SimpleHandler struct {
	Handler http.HandlerFunc
	Path    string
	Methods []string
}

SimpleHandler represents a simplification to the standard http handlerFuncs, allowing simpler registration and logging with Routers.

type SimpleServer added in v1.0.1

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

SimpleServer represents an extension to the standard http.Server

func NewServerHTTP added in v1.0.0

func NewServerHTTP(Addr string) (*SimpleServer, error)

NewServerHTTP will create a new http.Server, with no TLS settings enabled. This will accept raw HTTP only.

func NewServerHTTPS added in v1.0.0

func NewServerHTTPS(TLS *TLSBundle, Addr string) (*SimpleServer, error)

NewServerHTTPS will create a new TLS-Enabled http.Server. This will accept HTTPS, and fully initialize the server based on the TLSBundle provided.

func (*SimpleServer) Addr added in v1.0.18

func (S *SimpleServer) Addr() string

Addr exposes the underlying TCP address of the SimpleServer.

func (*SimpleServer) ConfigureReverseProxy added in v1.0.18

func (S *SimpleServer) ConfigureReverseProxy(Client *SimpleClient, RouteMatcher ReverseProxyRouterFunc, PathPrefix string, Middlewares ...MiddlewareHandler)

ConfigureReverseProxy will convert a freshly created SimpleServer into a ReverseProxy, forwarding all incoming traffic based on the RouteMatcher func provided. This will create the necessary HTTP handler, and configure the necessary routing.

func (*SimpleServer) EnableAboutHandler added in v1.0.4

func (S *SimpleServer) EnableAboutHandler(r *mux.Router)

EnableAboutHandler will enable and set up the "about" handler, to display the available routes. This must be the last route registered in order for the full set of routes to be displayed.

func (*SimpleServer) ListenAndServe added in v1.0.1

func (S *SimpleServer) ListenAndServe() error

ListenAndServe will start the SimpleServer, serving HTTPS if enabled, or HTTP if not

func (*SimpleServer) RegisterRouter added in v1.0.1

func (S *SimpleServer) RegisterRouter(r http.Handler)

RegisterRouter will register the given Handler (typically an *http.ServeMux or *mux.Router) as the http Handler for the server.

func (*SimpleServer) SetTimeouts added in v1.0.18

func (S *SimpleServer) SetTimeouts(ReadTimeout, ReadHeaderTimeout, WriteTimeout, IdleTimeout time.Duration)

SetTimeouts will set the given timeouts of the Server to what is passed. Set 0 to leave uninitialized.

func (*SimpleServer) Shutdown added in v1.0.1

func (S *SimpleServer) Shutdown() error

Shutdown will safely shut down the SimpleServer, returning any errors

type TLSBundle

type TLSBundle struct {
	AuthorityCertificates []string
	KeyPairs              []KeyPair
	Auth                  tls.ClientAuthType
	Enabled               bool `json:"-"`
}

TLSBundle represents the set of TLS information required by Dune to assert 2-way TLS verification.

Directories

Path Synopsis
This module represents a ...
This module represents a ...

Jump to

Keyboard shortcuts

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