cookies

package
v13.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Overview

Package cookies encodes values into cookies that a browser can hold and this service can later trust, and builds the *http.Cookie carrying them.

Two keys are required, both base64 in config, and they do different jobs. The hash key authenticates: the encoded value carries an HMAC-SHA256 over the cookie's name, a timestamp, and the payload, so a tampered cookie fails to decode. The block key encrypts the payload with AES, so the value is opaque to the client as well. Because the name is inside the MAC, a cookie's value does not verify under a different name.

That is confidentiality and integrity, not revocation. A cookie remains valid for as long as its MAC verifies and its timestamp is inside the configured lifetime, so nothing here can withdraw one that has already been issued — a session that must be revocable needs server-side state, and the sessions package is where that lives.

Config.Lifetime bounds the MAC-protected timestamp as well as the cookie's own MaxAge and Expires. Leaving it unset does not mean "no limit": the underlying codec then falls back to its own thirty-day ceiling, which is almost never what the rest of the configuration intends.

Key handling

The block key must be a valid AES key length — 16, 24, or 32 bytes decoded — and NewCookieManager checks it, wrapping errors.ErrUnrecognizedInputValue with the decoded length and never with the key. The check is here rather than left to the codec because securecookie stores its cipher error on the codec instead of returning it: a wrong-sized key used to build a manager without complaint and fail on the first Encode or Decode, which is a startup mistake surfacing at whichever request first needed a cookie.

There is one key pair, not a ring. Rotating either key invalidates every outstanding cookie at once, and there is no window in which cookies signed under the old key still verify.

The attributes are not optional

BuildCookie always sets HttpOnly and Path=/, and takes Secure, Domain, SameSite, and the expiry from config. SameSite defaults to Lax, and configuring None is rejected unless SecureOnly is also set, because browsers silently drop a SameSite=None cookie that is not Secure — a validation error at startup is the only place that failure is visible.

Index

Constants

View Source
const (
	SameSiteLax    = "lax"
	SameSiteStrict = "strict"
	SameSiteNone   = "none"
)

SameSite policy values accepted by Config.SameSite (case-insensitive). An empty value defaults to Lax.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Domain                string        `env:"DOMAIN"      json:"domain,omitempty"                yaml:"domain,omitempty"`
	Base64EncodedHashKey  string        `env:"HASH_KEY"    json:"base64EncodedHashKey,omitempty"  yaml:"base64EncodedHashKey,omitempty"`
	Base64EncodedBlockKey string        `env:"BLOCK_KEY"   json:"base64EncodedBlockKey,omitempty" yaml:"base64EncodedBlockKey,omitempty"`
	SameSite              string        `env:"SAME_SITE"   json:"sameSite,omitempty"              yaml:"sameSite,omitempty"`
	Lifetime              time.Duration `env:"LIFETIME"    json:"lifetime,omitempty"              yaml:"lifetime,omitempty"`
	SecureOnly            bool          `env:"SECURE_ONLY" json:"secureOnly,omitempty"            yaml:"secureOnly,omitempty"`
}

func (*Config) ValidateWithContext

func (c *Config) ValidateWithContext(ctx context.Context) error

type Manager

type Manager interface {
	Encode(ctx context.Context, name string, value any) (string, error)
	Decode(ctx context.Context, name, value string, dst any) error
	BuildCookie(ctx context.Context, name string, value any) (*http.Cookie, error)
}

type Option

type Option func(*options)

Option configures the Manager this package constructs. The zero configuration works: an absent logger logs nowhere and an absent tracer provider traces nowhere.

func WithLogger

func WithLogger(logger logging.Logger) Option

WithLogger attaches a logger.

A decode failure is the one worth having: it means a cookie this deployment issued no longer verifies, which is a rotated key or a forgery attempt, and neither is visible in a span nobody sampled.

func WithTracerProvider

func WithTracerProvider(tracerProvider tracing.Provider) Option

WithTracerProvider attaches a tracer provider, enabling spans on every operation.

type SecureCookieManager

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

SecureCookieManager is the Manager backed by gorilla/securecookie. It is exported, and returned by NewCookieManager, so a caller can depend on the manager it built rather than on the Manager seam.

func NewCookieManager

func NewCookieManager(cfg *Config, opts ...Option) (*SecureCookieManager, error)

NewCookieManager returns a new Manager.

The decoded block key is checked against the AES key sizes here rather than left to the codec. securecookie.New runs BlockFunc(aes.NewCipher) internally and stores the resulting error on the codec instead of returning it, so a wrong-sized key built a manager with a nil error and failed on the first Encode or Decode — at whichever request first needed a cookie, rather than at startup where the key was configured.

func (*SecureCookieManager) BuildCookie

func (m *SecureCookieManager) BuildCookie(ctx context.Context, name string, value any) (*http.Cookie, error)

BuildCookie encodes value and returns a ready-to-set *http.Cookie carrying the manager's configured security attributes: Secure from SecureOnly, Domain, SameSite, and MaxAge/Expires from Lifetime, plus a non-negotiable HttpOnly default. Callers hand the result to http.SetCookie.

func (*SecureCookieManager) Decode

func (m *SecureCookieManager) Decode(ctx context.Context, name, value string, dst any) error

Decode wraps securecookie's Decode method.

func (*SecureCookieManager) Encode

func (m *SecureCookieManager) Encode(ctx context.Context, name string, value any) (string, error)

Encode wraps securecookie's Encode method.

Directories

Path Synopsis
Package cookiescfg registers a cookies.Manager with a do injector.
Package cookiescfg registers a cookies.Manager with a do injector.

Jump to

Keyboard shortcuts

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