{"modulePath":"github.com/weiwolves/pkg","version":"v0.0.0-20200322065615-581c8d33cff6","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package signed\n\nPackage signed provides a middleware to sign responses and validate requests.\n\nThe middlewares can add the signature to the HTTP header or to the HTTP trailer or stores them internally. Store the hashes internally allows a transparent validation mechanism.\n\nWith the use of HTTPS between two parties this package might not be needed.\n\nIf you consider to use a 3rd untrusted participant then this package may help you. For example the 3rd participant is a mobile app. This app requests a product and a dynamic unique calculated price from the backend. The backend sends the product and its price to the mobile app. The app displays the information to the user. The user might add the product with that price to the cart by sending the product and the price back to the backend. The app uses the initial request which the app has received from the backend. The mobile app now simply forwards the unchanged first request bytes back to the backend. The backend can verify the request body by recalculating the hash found in the header.\n\nTODO(CyS) create a flowchart to demonstrate the usage.\n\n[https://tools.ietf.org/html/draft-thomson-http-content-signature-00](https://tools.ietf.org/html/draft-thomson-http-content-signature-00) [https://tools.ietf.org/html/draft-burke-content-signature-00](https://tools.ietf.org/html/draft-burke-content-signature-00)\n\n## Constants\n\n```go\nconst (\n\tHeaderContentSignature = \"Content-Signature\"\n\tHeaderContentHMAC      = \"Content-Hmac\"\n)\n```\nContent\\* constants are used as HTTP header key names.\n\n```go\nconst DefaultHashName = `sha256`\n```\nDefaultHashName identifies the default hash when creating a new scoped configuration. You must register this name before using this package via:\n\n\thashpool.Register(`sha256`, sha256.New)\n\nIf you would like to use different hashes you must registered them also in the hashpool package.\n\n## Types\n\n```go\ntype Cacher interface {\n\tSet(hash []byte, ttl time.Duration) error\n\tHas(hash []byte) bool\n}\n```\nCacher defines a custom cache type in conjunction with Transparent hashing. It will be used as an underlying storage for the hash values. In middleware WithResponseSignature a hash gets added to the Cacher with a time to live (TTL). The middleware WithRequestSignatureValidation checks if the hashed body matches the cache. The Cacher implementation itself must handle the ttl and the constant time comparison.\n\n```go\ntype ContentHMAC struct {\n\t// Algorithm parameter is used if the client and server agree on a\n\t// non-standard digital signature algorithm.  The full list of supported\n\t// signature mechanisms is listed below. REQUIRED.\n\tAlgorithm string\n\t// HeaderKey (optional) a field name in the HTTP header, defaults to\n\t// Content-HMAC.\n\tHeaderName string\n\t// EncodeFn (optional) defines the byte to string encoding function.\n\t// Defaults to hex.EncodeString.\n\tEncodeFn\n\t// DecodeFn (optional) defines the string to byte decoding function.\n\t// Defaults to hex.DecodeString.\n\tDecodeFn\n}\n```\nContentHMAC writes a simple Content-HMAC header. It can additionally parse a request and return the raw signature.\n\n```go\nfunc NewContentHMAC(algorithm string) *ContentHMAC\n```\nNewContentHMAC creates a new header HMAC object with default hex encoding/decoding to write and parse the Content-HMAC field.\n\n```go\nfunc (h *ContentHMAC) HeaderKey() string\n```\nHeaderKey returns the name of the header key\n\n```go\nfunc (h *ContentHMAC) Parse(r *http.Request) (signature []byte, _ error)\n```\nParse looks up the header or trailer for the HeaderKey Content-HMAC in an HTTP request and extracts the raw decoded signature. Errors can have the behaviour: NotFound or NotValid.\n\n```go\nfunc (h *ContentHMAC) Write(w http.ResponseWriter, signature []byte)\n```\nWrites writes the signature into the response. Content-HMAC: \\\u003chash mechanism\u003e \\\u003cencoded binary HMAC\u003e Content-HMAC: sha1 f1wOnLLwcTexwCSRCNXEAKPDm+U=\n\n```go\ntype ContentSignature struct {\n\t// KeyID field is an opaque string that the server/client can use to look up\n\t// the component they need to validate the signature. It could be an SSH key\n\t// fingerprint, an LDAP DN, etc. REQUIRED.\n\tKeyID string\n\t// Separator defines the field separator and defaults to colon.\n\tSeparator rune\n\tContentHMAC\n}\n```\nContentSignature represents an HTTP Header or Trailer entry with the default header key Content-Signature.\n\n```go\nfunc NewContentSignature(keyID, algorithm string) *ContentSignature\n```\nNewContentSignature creates a new header signature object with default hex encoding/decoding to write and parse the Content-Signature field.\n\n```go\nfunc (s *ContentSignature) HeaderKey() string\n```\nHeaderKey returns the name of the header key\n\n```go\nfunc (s *ContentSignature) Parse(r *http.Request) (signature []byte, _ error)\n```\nParse looks up the header or trailer for the HeaderKey Content-Signature in an HTTP request and extracts the raw decoded signature. Errors can have the behaviour: NotFound or NotValid.\n\n```go\nfunc (s *ContentSignature) Write(w http.ResponseWriter, signature []byte)\n```\nWrite writes the content signature header using an encoder, which can be hex or base64.\n\nSignature parameter is an encoded digital signature generated by the client.  The client uses the \\`algorithm\\` and \\`headers\\` request parameters to form a canonicalized \\`signing string\\`.  This \\`signing string\\` is then signed with the key associated with \\`keyId\\` and the algorithm corresponding to \\`algorithm\\`.  The \\`signature\\` parameter is then set to the encoding of the signature.\n\n\tContent-Signature: keyId=\"rsa-key-1\",algorithm=\"rsa-sha256\",signature=\"Hex|Base64(RSA-SHA256(signing string))\"\n\tContent-Signature: keyId=\"hmac-key-1\",algorithm=\"hmac-sha1\",signature=\"Hex|Base64(HMAC-SHA1(signing string))\"\n\n```go\ntype DecodeFn func(s string) ([]byte, error)\n```\nDecodeFn decodes a raw signature from the header to a byte slice. Useful types are hex.DecodeString or base64.StdEncoding.DecodeString.\n\n```go\ntype EncodeFn func(src []byte) string\n```\nEncodeFn encodes a raw signature byte slice to a string. Useful types are hex.EncodeToString or base64.StdEncoding.EncodeToString.\n\n```go\ntype HeaderParseWriter interface {\n\tHeaderKey() string\n\t// Write writes a signature to the HTTP response header.\n\tWrite(w http.ResponseWriter, signature []byte)\n\t// Parse parses from a request the necessary data to find the signature hash\n\t// and returns the raw signatures byte slice for further validation.\n\tParse(r *http.Request) (signature []byte, err error)\n}\n```\nHeaderParseWriter knows how to read and write the HTTP header in regards to the hash.\n\n```go\ntype Option func(*Service) error\n```\nOption can be used as an argument in NewService to configure it with different settings.\n\n```go\nfunc OptionsError(err error) []Option\n```\nOptionsError helper function to be used within the backend package or other sub-packages whose functions may return an OptionFactoryFunc.\n\n```go\nfunc WithAllowedMethods(methods []string, scopeIDs ...scope.TypeID) Option\n```\nWithAllowedMethods sets the allowed HTTP methods which can transport a signature hash.\n\n```go\nfunc WithDebugLog(w io.Writer) Option\n```\nWithDebugLog creates a new standard library based logger with debug mode enabled. The passed writer must be thread safe.\n\n```go\nfunc WithDefaultConfig(h scope.TypeID) Option\n```\nWithDefaultConfig applies the default signed configuration settings based for a specific scope. This function overwrites any previous set options.\n\nDefault settings: InTrailer activated, Content-HMAC header with sha256, allowed HTTP methods set to POST, PUT, PATCH and password for the HMAC SHA 256 from a cryptographically random source with a length of 64 bytes. Example:\n\n\ts := MustNewService(WithDefaultConfig(scope.Store,1), WithOtherSettings(scope.Store, 1, ...))\n\n```go\nfunc WithDisable(isDisabled bool, scopeIDs ...scope.TypeID) Option\n```\nWithDisable disables the current service and calls the next HTTP handler.\n\nThe variadic \"scopeIDs\" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no \"scopeIDs\" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.\n\n```go\nfunc WithErrorHandler(eh mw.ErrorHandler, scopeIDs ...scope.TypeID) Option\n```\nWithErrorHandler adds a custom error handler. Gets called in the http.Handler after the scope can be extracted from the context.Context and the configuration has been found and is valid. The default error handler prints the error to the user and returns a http.StatusServiceUnavailable.\n\nThe variadic \"scopeIDs\" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no \"scopeIDs\" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.\n\n```go\nfunc WithHash(name string, key []byte, scopeIDs ...scope.TypeID) Option\n```\nWithHash sets the hashing algorithm to create a new hash and verify an incoming hash. Please use only cryptographically secure hash algorithms.\n\n```go\nfunc WithHeaderHandler(pw HeaderParseWriter, scopeIDs ...scope.TypeID) Option\n```\nWithHeaderHandler sets the writer and the parser. The writer knows how to write the hash value into the HTTP header. The parser knows how and where to extract the hash value from the header or even the trailer. Compatible types in this package are ContentHMAC, ContentSignature and Transparent.\n\n```go\nfunc WithLogger(l log.Logger) Option\n```\nWithLogger convenient helper function to apply a logger to the Service type.\n\n```go\nfunc WithMarkPartiallyApplied(partially bool, scopeIDs ...scope.TypeID) Option\n```\nWithMarkPartiallyApplied if set to true marks a configuration for a scope as partially applied with functional options set via source code. The internal service knows that it must trigger additionally the OptionFactoryFunc to load configuration from a backend. Useful in the case where parts of the configurations are coming from backend storages and other parts like http handler have been set via code. This function should only be applied in case you work with WithOptionFactory().\n\nThe variadic \"scopeIDs\" argument define to which scope the value gets applied and from which parent scope should be inherited. Setting no \"scopeIDs\" sets the value to the default scope. Setting one scope.TypeID defines the primary scope to which the value will be applied. Subsequent scope.TypeID are defining the fall back parent scopes to inherit the default or previously applied configuration from.\n\n```go\nfunc WithOptionFactory(f OptionFactoryFunc) Option\n```\nWithOptionFactory applies a function which lazily loads the options from a slow backend (config.Getter) depending on the incoming scope within a request. For example applies the backend configuration to the service.\n\nOnce this option function has been set all other manually set option functions, which accept a scope and a scope ID as an argument, will NOT be overwritten by the new values retrieved from the configuration service.\n\n\tcfgStruct, err := backendsigned.NewConfigStructure()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbe := backendsigned.New(cfgStruct)\n\n\tsrv := signed.MustNewService(\n\t\tsigned.WithOptionFactory(be.PrepareOptions()),\n\t)\n\n```go\nfunc WithRootConfig(cg config.Getter) Option\n```\nWithRootConfig sets the root configuration service to retrieve the scoped base configuration. If you set the option WithOptionFactory() then the option WithRootConfig() does not need to be set as it won't get used.\n\n```go\nfunc WithServiceErrorHandler(eh mw.ErrorHandler) Option\n```\nWithServiceErrorHandler sets the error handler on the Service object. Convenient helper function.\n\n```go\nfunc WithTrailer(inTrailer bool, scopeIDs ...scope.TypeID) Option\n```\nWithTrailer allows to write the hash sum into the trailer. The middleware switches to stream based hash calculation which results in faster processing instead of writing into a buffer. Make sure that your client can process HTTP trailers.\n\n```go\nfunc WithTransparent(c Cacher, ttl time.Duration, scopeIDs ...scope.TypeID) Option\n```\nWithTransparent allows to write the hashes into the Cacher with a time-to-live. Responses will not get a header key attached and requests won't get inspected for a header key which might contain the hash value.\n\n```go\ntype OptionFactories struct {\n\t// contains filtered or unexported fields\n}\n```\nOptionFactories allows to register multiple OptionFactoryFunc identified by their names. Those OptionFactoryFuncs will be loaded in the backend package depending on the configured name under a certain path. This type is embedded in the backendsigned.Configuration type.\n\n```go\nfunc NewOptionFactories() *OptionFactories\n```\nNewOptionFactories creates a new struct and initializes the internal map for the registration of different option factories.\n\n```go\nfunc (of *OptionFactories) Deregister(name string)\n```\nDeregister removes a functional option factory from the internal register.\n\n```go\nfunc (of *OptionFactories) Lookup(name string) (OptionFactoryFunc, error)\n```\nLookup returns a functional option factory identified by name or an error if the entry doesn't exists. May return a NotFound error behaviour.\n\n```go\nfunc (of *OptionFactories) Names() []string\n```\nNames returns an unordered list of names of all registered functional option factories.\n\n```go\nfunc (of *OptionFactories) Register(name string, factory OptionFactoryFunc)\n```\nRegister adds another functional option factory to the internal register. Overwrites existing entries.\n\n```go\ntype OptionFactoryFunc func(config.Scoped) []Option\n```\nOptionFactoryFunc a closure around a scoped configuration to figure out which options should be returned depending on the scope brought to you during a request.\n\n```go\ntype ScopedConfig struct {\n\n\t// Disabled set to true to disable content signing.\n\tDisabled bool\n\t// InTrailer set to true and the signature will be added to the HTTP Trailer for\n\t// responses.\n\tInTrailer bool\n\t// HeaderParseWriter see description of interface HeaderParseWriter\n\tHeaderParseWriter\n\t// AllowedMethods list of allowed HTTP methods. Must be upper case.\n\tAllowedMethods []string\n\t// TransparentCacher stores the calculated hashes in memory with a TTL. The hash\n\t// won't get written into the HTTP response. If enable you must set the\n\t// Cacher field in the Service struct.\n\tTransparentCacher Cacher\n\t// TransparentTTL defines the time to live for a hash within the Cacher\n\t// interface.\n\tTransparentTTL time.Duration\n\t// contains filtered or unexported fields\n}\n```\nScopedConfig scoped based configuration and should not be embedded into your own types. Call ScopedConfig.ScopeHash to know to which scope this configuration has been bound to.\n\n```go\nfunc (sc *ScopedConfig) CalculateHash(r *http.Request) ([]byte, error)\n```\nCalculateHash calculates the hash sum from the request body. The full body gets read into a buffer. This buffer gets assigned to the r.Body to make a read possible for the next consumer.\n\n```go\nfunc (sc *ScopedConfig) ValidateBody(r *http.Request) error\n```\nValidateBody uses the HTTPParser to extract the hash signature. It then hashes the body and compares the hash of the body with the hash value found in the HTTP header. Hash comparison via constant time.\n\n```go\ntype Service struct {\n\t// contains filtered or unexported fields\n}\n```\nService creates a middleware that facilitates using a hash function to sign a HTTP body and validate the HTTP body of a request.\n\n```go\nfunc MustNew(opts ...Option) *Service\n```\nMustNew same as New() but panics on error. Use only during app start up process.\n\n```go\nfunc New(opts ...Option) (*Service, error)\n```\nNew creates a new signing middleware for signature creation and validation. The scope.Default and any other scopes have these default settings: InTrailer activated, Content-HMAC header with sha256, allowed HTTP methods set to POST, PUT, PATCH and password for the HMAC SHA 256 from a cryptographically random source with a length of 64 bytes.\n\n```go\nfunc (s *Service) ClearCache() error\n```\nClearCache clears the internal map storing all scoped configurations. You must reapply all functional options. TODO(CyS) all previously applied options will be automatically reapplied.\n\n```go\nfunc (s *Service) ConfigByScope(websiteID, storeID int64) (ScopedConfig, error)\n```\nConfigByScope creates a new scoped configuration depending on the Service.useWebsite flag. If useWebsite==true the scoped configuration contains only the website-\u003edefault scope despite setting a store scope. If an OptionFactory is set the configuration gets loaded from the backend. A nil root config causes a panic.\n\n```go\nfunc (s *Service) ConfigByScopeID(current scope.TypeID, parent scope.TypeID) (scpCfg ScopedConfig, _ error)\n```\nConfigByScopeID returns the correct configuration for a scope and may fall back to the next higher scope: store -\u003e website -\u003e default. If \\`current\\` TypeID is Store, then the \\`parent\\` can only be Website or Default. If an entry for a scope cannot be found the next higher scope gets looked up and the pointer of the next higher scope gets assigned to the current scope. This prevents redundant configurations and enables us to change one scope configuration with an impact on all other scopes which depend on the parent scope. A zero \\`parent\\` triggers no further look ups. This function does not load any configuration (config.Getter related) from the backend and accesses the internal map of the Service directly.\n\nImportant: a \"current\" scope cannot have multiple \"parent\" scopes.\n\n```go\nfunc (s *Service) ConfigByScopedGetter(scpGet config.Scoped) (ScopedConfig, error)\n```\nConfigByScopedGetter returns the internal configuration depending on the ScopedGetter. Mainly used within the middleware.  If you have applied the option WithOptionFactory() the configuration will be pulled out only one time from the backend configuration service. The field optionInflight handles the guaranteed atomic single loading for each scope.\n\n```go\nfunc (s *Service) DebugCache(w io.Writer) error\n```\nDebugCache uses Sprintf to write an ordered list (by scope.TypeID) into a writer. Only usable for debugging.\n\n```go\nfunc (s *Service) Options(opts ...Option) error\n```\nOptions applies option at creation time or refreshes them.\n\n```go\nfunc (s *Service) WithRequestSignatureValidation(next http.Handler) http.Handler\n```\nWithRequestSignatureValidation extracts from the header or trailer the hash value and hashes the body of the incoming request and compares those two hashes. On success the next handler will be called otherwise the scope based error handler.\n\n```go\nfunc (s *Service) WithResponseSignature(next http.Handler) http.Handler\n```\nWithResponseSignature hashes the data written to http.ResponseWriter and adds the hash to the HTTP header. For large data sets use the option InTrailer to provide stream based hashing but the hash gets written into the HTTP trailer. Not all clients can read the HTTP trailer.\n\n```go\ntype Transparent struct {\n\tTTL time.Duration\n\t// contains filtered or unexported fields\n}\n```\nTransparent stores the calculated hashes in memory with a TTL using the Cacher interface. The hash won't get written into the HTTP response.\n\n```go\nfunc MakeTransparent(c Cacher, ttl time.Duration) Transparent\n```\nMakeTransparent creates a new hash writer. Parse is a noop.\n\n```go\nfunc (t Transparent) HeaderKey() string\n```\nHeaderKey returns an empty string.\n\n```go\nfunc (t Transparent) Parse(_ *http.Request) ([]byte, error)\n```\nParse returns always nil,nil.\n\n```go\nfunc (t Transparent) Write(_ http.ResponseWriter, signature []byte)\n```\nWrite sets the signature into the cache with the TTL.\n\n","path":"github.com/weiwolves/pkg/net/signed","name":"signed","synopsis":"Package signed provides a middleware to sign responses and validate requests.","isRedistributable":true}
