{"modulePath":"github.com/stacklok/securecookie","version":"v0.0.0-20230605113208-db3c8f8bddac","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package securecookie\n\nPackage securecookie encodes and decodes authenticated and optionally encrypted cookie values.\n\nSecure cookies can't be forged, because their values are validated using HMAC. When encrypted, the content is also inaccessible to malicious eyes.\n\nTo use it, first create a new SecureCookie instance:\n\n\tvar hashKey = []byte(\"very-secret\")\n\tvar blockKey = []byte(\"a-lot-secret\")\n\tvar s = securecookie.New(hashKey, blockKey)\n\nThe hashKey is required, used to authenticate the cookie value using HMAC. It is recommended to use a key with 32 or 64 bytes.\n\nThe blockKey is optional, used to encrypt the cookie value -- set it to nil to not use encryption. If set, the length must correspond to the block size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.\n\nStrong keys can be created using the convenience function GenerateRandomKey().\n\nOnce a SecureCookie instance is set, use it to encode a cookie value:\n\n\tfunc SetCookieHandler(w http.ResponseWriter, r *http.Request) {\n\t\tvalue := map[string]string{\n\t\t\t\"foo\": \"bar\",\n\t\t}\n\t\tif encoded, err := s.Encode(\"cookie-name\", value); err == nil {\n\t\t\tcookie := \u0026http.Cookie{\n\t\t\t\tName:  \"cookie-name\",\n\t\t\t\tValue: encoded,\n\t\t\t\tPath:  \"/\",\n\t\t\t}\n\t\t\thttp.SetCookie(w, cookie)\n\t\t}\n\t}\n\nLater, use the same SecureCookie instance to decode and validate a cookie value:\n\n\tfunc ReadCookieHandler(w http.ResponseWriter, r *http.Request) {\n\t\tif cookie, err := r.Cookie(\"cookie-name\"); err == nil {\n\t\t\tvalue := make(map[string]string)\n\t\t\tif err = s2.Decode(\"cookie-name\", cookie.Value, \u0026value); err == nil {\n\t\t\t\tfmt.Fprintf(w, \"The value of foo is %q\", value[\"foo\"])\n\t\t\t}\n\t\t}\n\t}\n\nWe stored a map\\[string]string, but secure cookies can hold any value that can be encoded using encoding/gob. To store custom types, they must be registered first using gob.Register(). For basic types this is not needed; it works out of the box.\n\n## Variables\n\n```go\nvar (\n\n\t// ErrMacInvalid indicates that cookie decoding failed because the HMAC\n\t// could not be extracted and verified.  Direct use of this error\n\t// variable is deprecated; it is public only for legacy compatibility,\n\t// and may be privatized in the future, as it is rarely useful to\n\t// distinguish between this error and other Error implementations.\n\tErrMacInvalid = cookieError{/* contains filtered or unexported fields */}\n)\n```\n\n## Functions\n\n```go\nfunc DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error\n```\nDecodeMulti decodes a cookie value using a group of codecs.\n\nThe codecs are tried in order. Multiple codecs are accepted to allow key rotation.\n\nOn error, may return a MultiError.\n\n```go\nfunc EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error)\n```\nEncodeMulti encodes a cookie value using a group of codecs.\n\nThe codecs are tried in order. Multiple codecs are accepted to allow key rotation.\n\nOn error, may return a MultiError.\n\n```go\nfunc GenerateRandomKey(length int) []byte\n```\nGenerateRandomKey creates a random key with the given length in bytes. On failure, returns nil.\n\nNote that keys created using \\`GenerateRandomKey()\\` are not automatically persisted. New keys will be created when the application is restarted, and previously issued cookies will not be able to be decoded.\n\nCallers should explicitly check for the possibility of a nil return, treat it as a failure of the system random number generator, and not continue.\n\n## Types\n\n```go\ntype Codec interface {\n\tEncode(name string, value interface{}) (string, error)\n\tDecode(name, value string, dst interface{}) error\n}\n```\nCodec defines an interface to encode and decode cookie values.\n\n```go\nfunc CodecsFromPairs(keyPairs ...[]byte) []Codec\n```\nCodecsFromPairs returns a slice of SecureCookie instances.\n\nIt is a convenience function to create a list of codecs for key rotation. Note that the generated Codecs will have the default options applied: callers should iterate over each Codec and type-assert the underlying \\*SecureCookie to change these.\n\nExample:\n\n\tcodecs := securecookie.CodecsFromPairs(\n\t     []byte(\"new-hash-key\"),\n\t     []byte(\"new-block-key\"),\n\t     []byte(\"old-hash-key\"),\n\t     []byte(\"old-block-key\"),\n\t )\n\n\t// Modify each instance.\n\tfor _, s := range codecs {\n\t       if cookie, ok := s.(*securecookie.SecureCookie); ok {\n\t           cookie.MaxAge(86400 * 7)\n\t           cookie.SetSerializer(securecookie.JSONEncoder{})\n\t           cookie.HashFunc(sha512.New512_256)\n\t       }\n\t   }\n\n```go\ntype Error interface {\n\terror\n\n\t// IsUsage returns true for errors indicating the client code probably\n\t// uses this library incorrectly.  For example, the client may have\n\t// failed to provide a valid hash key, or may have failed to configure\n\t// the Serializer adequately for encoding value.\n\tIsUsage() bool\n\n\t// IsDecode returns true for errors indicating that a cookie could not\n\t// be decoded and validated.  Since cookies are usually untrusted\n\t// user-provided input, errors of this type should be expected.\n\t// Usually, the proper action is simply to reject the request.\n\tIsDecode() bool\n\n\t// IsInternal returns true for unexpected errors occurring in the\n\t// securecookie implementation.\n\tIsInternal() bool\n\n\t// Cause, if it returns a non-nil value, indicates that this error was\n\t// propagated from some underlying library.  If this method returns nil,\n\t// this error was raised directly by this library.\n\t//\n\t// Cause is provided principally for debugging/logging purposes; it is\n\t// rare that application logic should perform meaningfully different\n\t// logic based on Cause.  See, for example, the caveats described on\n\t// (MultiError).Cause().\n\tCause() error\n}\n```\nError is the interface of all errors returned by functions in this library.\n\n```go\ntype GobEncoder struct{}\n```\nGobEncoder encodes cookie values using encoding/gob. This is the simplest encoder and can handle complex types via gob.Register.\n\n```go\nfunc (e GobEncoder) Deserialize(src []byte, dst interface{}) error\n```\nDeserialize decodes a value using gob.\n\n```go\nfunc (e GobEncoder) Serialize(src interface{}) ([]byte, error)\n```\nSerialize encodes a value using gob.\n\n```go\ntype JSONEncoder struct{}\n```\nJSONEncoder encodes cookie values using encoding/json. Users who wish to encode complex types need to satisfy the json.Marshaller and json.Unmarshaller interfaces.\n\n```go\nfunc (e JSONEncoder) Deserialize(src []byte, dst interface{}) error\n```\nDeserialize decodes a value using encoding/json.\n\n```go\nfunc (e JSONEncoder) Serialize(src interface{}) ([]byte, error)\n```\nSerialize encodes a value using encoding/json.\n\n```go\ntype MultiError []error\n```\nMultiError groups multiple errors.\n\n```go\nfunc (m MultiError) Cause() error\n```\nCause returns nil for MultiError; there is no unique underlying cause in the general case.\n\nNote: we could conceivably return a non-nil Cause only when there is exactly one child error with a Cause.  However, it would be brittle for client code to rely on the arity of causes inside a MultiError, so we have opted not to provide this functionality.  Clients which really wish to access the Causes of the underlying errors are free to iterate through the errors themselves.\n\n```go\nfunc (m MultiError) Error() string\n```\n\n```go\nfunc (m MultiError) IsDecode() bool\n```\n\n```go\nfunc (m MultiError) IsInternal() bool\n```\n\n```go\nfunc (m MultiError) IsUsage() bool\n```\n\n```go\ntype NopEncoder struct{}\n```\nNopEncoder does not encode cookie values, and instead simply accepts a \\[]byte (as an interface{}) and returns a \\[]byte. This is particularly useful when you encoding an object upstream and do not wish to re-encode it.\n\n```go\nfunc (e NopEncoder) Deserialize(src []byte, dst interface{}) error\n```\nDeserialize passes a \\[]byte through as-is.\n\n```go\nfunc (e NopEncoder) Serialize(src interface{}) ([]byte, error)\n```\nSerialize passes a \\[]byte through as-is.\n\n```go\ntype SecureCookie struct {\n\t// contains filtered or unexported fields\n}\n```\nSecureCookie encodes and decodes authenticated and optionally encrypted cookie values.\n\n```go\nfunc New(hashKey, blockKey []byte) *SecureCookie\n```\nNew returns a new SecureCookie.\n\nhashKey is required, used to authenticate values using HMAC. Create it using GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes.\n\nblockKey is optional, used to encrypt values. Create it using GenerateRandomKey(). The key length must correspond to the key size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. The default encoder used for cookie serialization is encoding/gob.\n\nNote that keys created using GenerateRandomKey() are not automatically persisted. New keys will be created when the application is restarted, and previously issued cookies will not be able to be decoded.\n\n```go\nfunc (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie\n```\nBlockFunc sets the encryption function used to create a cipher.Block.\n\nDefault is crypto/aes.New.\n\n```go\nfunc (s *SecureCookie) Decode(name, value string, dst interface{}) error\n```\nDecode decodes a cookie value.\n\nIt decodes, verifies a message authentication code, optionally decrypts and finally deserializes the value.\n\nThe name argument is the cookie name. It must be the same name used when it was stored. The value argument is the encoded cookie value. The dst argument is where the cookie will be decoded. It must be a pointer.\n\n```go\nfunc (s *SecureCookie) Encode(name string, value interface{}) (string, error)\n```\nEncode encodes a cookie value.\n\nIt serializes, optionally encrypts, signs with a message authentication code, and finally encodes the value.\n\nThe name argument is the cookie name. It is stored with the encoded value. The value argument is the value to be encoded. It can be any value that can be encoded using the currently selected serializer; see SetSerializer().\n\nIt is the client's responsibility to ensure that value, when encoded using the current serialization/encryption settings on s and then base64-encoded, is shorter than the maximum permissible length.\n\n```go\nfunc (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie\n```\nHashFunc sets the hash function used to create HMAC.\n\nDefault is crypto/sha256.New.\n\n```go\nfunc (s *SecureCookie) MaxAge(value int) *SecureCookie\n```\nMaxAge restricts the maximum age, in seconds, for the cookie value.\n\nDefault is 86400 \\* 30. Set it to 0 for no restriction.\n\n```go\nfunc (s *SecureCookie) MaxLength(value int) *SecureCookie\n```\nMaxLength restricts the maximum length, in bytes, for the cookie value.\n\nDefault is 4096, which is the maximum value accepted by Internet Explorer.\n\n```go\nfunc (s *SecureCookie) MinAge(value int) *SecureCookie\n```\nMinAge restricts the minimum age, in seconds, for the cookie value.\n\nDefault is 0 (no restriction).\n\n```go\nfunc (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie\n```\nEncoding sets the encoding/serialization method for cookies.\n\nDefault is encoding/gob.  To encode special structures using encoding/gob, they must be registered first using gob.Register().\n\n```go\ntype Serializer interface {\n\tSerialize(src interface{}) ([]byte, error)\n\tDeserialize(src []byte, dst interface{}) error\n}\n```\nSerializer provides an interface for providing custom serializers for cookie values.\n\n","path":"github.com/stacklok/securecookie","name":"securecookie","synopsis":"Package securecookie encodes and decodes authenticated and optionally encrypted cookie values.","isRedistributable":true}
