security

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package security provides authentication, TLS management, admin auth, and web application firewall (WAF) for the gateway.

Index

Constants

View Source
const (
	// AuthFailureUnauthenticated is a request with no credentials, or ones
	// no provider accepted.
	AuthFailureUnauthenticated = "unauthenticated"

	// AuthFailureForbidden is a request whose credentials were accepted
	// but don't carry the route's scopes, or that a provider answered 403.
	AuthFailureForbidden = "forbidden"

	// AuthFailureUnavailable is a request that couldn't be checked: an auth
	// service that was down or answered 5xx.
	AuthFailureUnavailable = "unavailable"
)

The classes AuthFailureClass sorts a failed authentication into.

Variables

This section is empty.

Functions

func AuthFailureClass

func AuthFailureClass(err error) string

AuthFailureClass sorts an error from Auth.Authenticate into one of the AuthFailure classes. It looks through the whole chain, so a forward-auth service that was down counts as unavailable even though the gateway answers the client 401.

func DropAuthHeaders

func DropAuthHeaders(h http.Header)

DropAuthHeaders deletes the identity headers ForwardAuthHeaders sets (X-Auth-Subject, X-Auth-Provider, X-Auth-Scopes, X-Auth-Role and X-Auth-Email) from h. The proxy calls it on every inbound request before authentication, so the copies an upstream sees are always ones the gateway set. Other X-Auth- headers, such as a token an API key provider reads, are left alone.

func ValidateTLSConfig

func ValidateTLSConfig(config TLSConfig) error

ValidateTLSConfig checks that the TLS configuration is valid.

Types

type APIKeyAuthProvider

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

APIKeyAuthProvider validates requests using API keys in headers or query params.

func NewAPIKeyAuthProvider

func NewAPIKeyAuthProvider(name, header, queryParam string, keys []*APIKeyEntry) *APIKeyAuthProvider

NewAPIKeyAuthProvider creates an API key auth provider.

func (*APIKeyAuthProvider) Authenticate

func (p *APIKeyAuthProvider) Authenticate(_ context.Context, r *http.Request) (*AuthContext, error)

func (*APIKeyAuthProvider) Name

func (p *APIKeyAuthProvider) Name() string

type APIKeyEntry

type APIKeyEntry struct {
	Key      string         `json:"key"`
	Subject  string         `json:"subject"`
	Scopes   []string       `json:"scopes,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

APIKeyEntry represents a registered API key with associated metadata.

type AdminAuthConfig

type AdminAuthConfig struct {
	// Enabled enables admin API authentication.
	Enabled bool `json:"enabled" yaml:"enabled"`

	// APIKeys is a list of valid API keys for admin access.
	APIKeys []string `json:"apiKeys,omitempty" yaml:"api_keys"`

	// Header is the header name containing the API key.
	// Defaults to "X-Admin-Key".
	Header string `json:"header,omitempty" yaml:"header"`
}

AdminAuthConfig configures authentication for admin API endpoints.

type AdminAuthMiddleware

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

AdminAuthMiddleware protects admin API endpoints with API key authentication.

func NewAdminAuthMiddleware

func NewAdminAuthMiddleware(config AdminAuthConfig) *AdminAuthMiddleware

NewAdminAuthMiddleware creates a new admin auth middleware.

func (*AdminAuthMiddleware) Wrap

Wrap returns an http.Handler that requires admin authentication.

func (*AdminAuthMiddleware) WrapFunc

func (m *AdminAuthMiddleware) WrapFunc(next http.HandlerFunc) http.Handler

WrapFunc is a convenience wrapper for http.HandlerFunc.

type Auth

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

Auth handles authentication for gateway requests. It operates at the HTTP transport level (before request proxying), supporting multiple auth strategies and per-route configuration.

func NewAuth

func NewAuth(config AuthConfig, logger forge.Logger) *Auth

NewAuth creates a new gateway auth handler.

func (*Auth) Authenticate

func (ga *Auth) Authenticate(r *http.Request, route Route) (*AuthContext, error)

Authenticate checks if a request is authenticated based on configuration. It supports:

  • Global auth (applied to all routes unless skipped)
  • Per-route auth overrides (specific providers, scopes, skip)
  • Multiple providers tried in order (OR logic)
  • Auth context forwarding to upstream via headers

func (*Auth) ForwardAuthHeaders

func (ga *Auth) ForwardAuthHeaders(r *http.Request, authCtx *AuthContext)

ForwardAuthHeaders adds authentication context to upstream request headers. This allows upstream services to access the authenticated user info without re-authenticating. It clears the five identity headers first, so a claim the token doesn't carry is never filled in from the request.

func (*Auth) RegisterProvider

func (ga *Auth) RegisterProvider(provider AuthProvider)

RegisterProvider registers a custom gateway-level auth provider.

A provider with background work, such as the JWT provider, runs with the gateway: Start starts it, Stop stops it. One registered while the gateway is already running is started here before RegisterProvider returns. That covers a Forge PhaseAfterRegister hook on Forge's default boot path, where those hooks run after the extensions start; with CentralMigrations they run before, and Start picks the provider up. A provider it replaces is stopped.

func (*Auth) SetForgeAuth

func (ga *Auth) SetForgeAuth(registry AuthRegistry)

SetForgeAuth sets the optional Forge auth extension integration.

func (*Auth) Start

func (ga *Auth) Start(ctx context.Context)

Start starts the registered providers that have background work, so the JWT provider holds its keys before the gateway takes traffic, and has RegisterProvider start any registered later. Gateway calls it from its own Start, and it does nothing while auth is disabled. A provider that isn't ready afterwards is logged and stays registered; the JWT provider rejects every token until it has a key.

func (*Auth) Stop

func (ga *Auth) Stop(ctx context.Context)

Stop stops the background work of every registered provider. Gateway calls it from its own Stop.

type AuthConfig

type AuthConfig struct {
	Enabled        bool     `json:"enabled" yaml:"enabled"`
	DefaultPolicy  string   `json:"defaultPolicy,omitempty" yaml:"default_policy"`
	Providers      []string `json:"providers,omitempty" yaml:"providers"`
	ForwardHeaders bool     `json:"forwardHeaders" yaml:"forward_headers"`
}

AuthConfig holds gateway-level auth settings.

type AuthContext

type AuthContext struct {
	// Subject is the authenticated entity (user ID, service ID, etc.)
	Subject string `json:"subject"`

	// Claims holds additional authentication claims (roles, permissions, etc.)
	Claims map[string]any `json:"claims,omitempty"`

	// Scopes holds OAuth2 scopes or permission strings
	Scopes []string `json:"scopes,omitempty"`

	// ProviderName identifies which auth provider authenticated this request
	ProviderName string `json:"providerName"`
}

AuthContext holds authenticated subject information for gateway requests.

func (*AuthContext) HasScope

func (a *AuthContext) HasScope(scope string) bool

HasScope checks if the auth context has a specific scope.

func (*AuthContext) HasScopes

func (a *AuthContext) HasScopes(scopes ...string) bool

HasScopes checks if the auth context has all specified scopes.

type AuthError

type AuthError struct {
	Code    int
	Message string
	// contains filtered or unexported fields
}

AuthError represents an authentication failure.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

Unwrap returns the provider error behind e, if there is one.

type AuthProvider

type AuthProvider interface {
	// Name returns the provider name.
	Name() string

	// Authenticate validates a request and returns an auth context or error.
	Authenticate(ctx context.Context, r *http.Request) (*AuthContext, error)
}

AuthProvider is the gateway's interface for authentication providers. This decouples the gateway from the concrete discovery.Service type.

type AuthRegistry

type AuthRegistry interface {
	// Get returns a provider by name.
	Get(name string) (AuthProvider, bool)

	// Has checks if a provider exists.
	Has(name string) bool

	// List returns all registered provider names.
	List() []string

	// Register adds a custom auth provider.
	Register(provider AuthProvider) error
}

AuthRegistry manages authentication providers for the gateway.

type BasePlugin

type BasePlugin struct {
	PluginName string
}

BasePlugin provides no-op defaults for gateway plugins, allowing plugins to override only the methods they care about.

func (*BasePlugin) Name

func (bp *BasePlugin) Name() string

type BearerTokenAuthProvider

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

BearerTokenAuthProvider validates Bearer tokens by forwarding them to a validation endpoint or using a configurable validation function.

func NewBearerTokenAuthProvider

func NewBearerTokenAuthProvider(name string, validate func(ctx context.Context, token string) (*AuthContext, error)) *BearerTokenAuthProvider

NewBearerTokenAuthProvider creates a bearer token auth provider with a custom validator.

func (*BearerTokenAuthProvider) Authenticate

func (p *BearerTokenAuthProvider) Authenticate(ctx context.Context, r *http.Request) (*AuthContext, error)

func (*BearerTokenAuthProvider) Name

func (p *BearerTokenAuthProvider) Name() string

type ForwardAuthProvider

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

ForwardAuthProvider delegates authentication to an external auth service. It sends the original request headers to the auth endpoint and uses the response to determine authentication status.

func NewForwardAuthProvider

func NewForwardAuthProvider(name, endpoint string, headers []string) *ForwardAuthProvider

NewForwardAuthProvider creates a forward auth provider.

func (*ForwardAuthProvider) Authenticate

func (p *ForwardAuthProvider) Authenticate(ctx context.Context, r *http.Request) (*AuthContext, error)

func (*ForwardAuthProvider) Name

func (p *ForwardAuthProvider) Name() string

type JWTAuthConfig

type JWTAuthConfig struct {
	// Name is the provider name.
	Name string `json:"name" yaml:"name"`

	// JWKSURL is the URL of the JSON Web Key Set the provider checks
	// signatures against. The provider loads it on its own, and it rejects
	// every token until it holds at least one key from it, so a provider
	// without a JWKSURL accepts nothing.
	JWKSURL string `json:"jwksUrl" yaml:"jwks_url"`

	// Issuer is the expected "iss" claim value.
	Issuer string `json:"issuer" yaml:"issuer"`

	// Audience is the expected "aud" claim value.
	Audience string `json:"audience" yaml:"audience"`

	// ScopesClaim is the JWT claim containing scopes (default: "scope").
	ScopesClaim string `json:"scopesClaim,omitempty" yaml:"scopes_claim"`

	// SubjectClaim is the JWT claim containing the subject (default: "sub").
	SubjectClaim string `json:"subjectClaim,omitempty" yaml:"subject_claim"`

	// RefreshInterval is how often to refresh the JWKS (default: 1h).
	RefreshInterval time.Duration `json:"refreshInterval,omitempty" yaml:"refresh_interval"`

	// Algorithms lists the signing algorithms the provider accepts. It
	// defaults to all it supports: RS256, RS384, RS512, ES256, ES384 and
	// ES512. Names outside that list are ignored, and "none" is never
	// accepted.
	Algorithms []string `json:"algorithms,omitempty" yaml:"algorithms"`
}

JWTAuthConfig configures JWT/OIDC authentication.

type JWTAuthProvider

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

JWTAuthProvider validates JWT tokens against keys from a JWKS.

It loads the JWKS itself: Start (which the gateway calls for every registered provider) fetches it and refreshes it every RefreshInterval, and a provider nobody started fetches it on the first token it sees and again whenever the keys are older than RefreshInterval. Until a fetch has produced a key, every token is rejected. A fetch that fails, or returns a set with no usable key in it, leaves the keys already loaded in place.

func NewJWTAuthProvider

func NewJWTAuthProvider(config JWTAuthConfig) *JWTAuthProvider

NewJWTAuthProvider creates a JWT auth provider. It holds no keys yet, so it rejects every token until its first JWKS fetch succeeds.

func (*JWTAuthProvider) Authenticate

func (p *JWTAuthProvider) Authenticate(ctx context.Context, r *http.Request) (*AuthContext, error)

Authenticate validates a JWT Bearer token.

func (*JWTAuthProvider) Name

func (p *JWTAuthProvider) Name() string

Name returns the provider name.

func (*JWTAuthProvider) Start

func (p *JWTAuthProvider) Start(ctx context.Context) error

Start fetches the JWKS and then refreshes it every RefreshInterval until ctx is done or Stop is called. While the provider holds no keys, the refresh retries sooner, backing off from a few seconds up to RefreshInterval. The first fetch runs before Start returns, under ctx's span; each later one is the root of its own trace.

The gateway calls Start for every registered provider, so you don't need to. Calling it again while the refresh runs does nothing. It returns an error when the provider still has no key afterwards, in which case the refresh keeps trying and every token is rejected until one loads.

func (*JWTAuthProvider) StartKeyRefresh

func (p *JWTAuthProvider) StartKeyRefresh(ctx context.Context)

StartKeyRefresh is Start without the error. The gateway starts the provider itself, so you only need this for a provider you use outside it, and even then the provider loads its keys on the first token.

func (*JWTAuthProvider) Stop

func (p *JWTAuthProvider) Stop(ctx context.Context) error

Stop ends the refresh Start began. The keys already loaded stay. It is safe to call when nothing is running.

type Route

type Route interface {
	GetID() string
	GetAuth() *RouteAuthConfig
}

Route is a minimal interface for gateway routes used by the security package.

type RouteAuthConfig

type RouteAuthConfig struct {
	Enabled     bool     `json:"enabled"`
	Providers   []string `json:"providers,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
	SkipAuth    bool     `json:"skipAuth,omitempty"`
	ForwardAuth bool     `json:"forwardAuth,omitempty"`
}

RouteAuthConfig defines per-route auth requirements.

type TLSConfig

type TLSConfig struct {
	Enabled            bool          `json:"enabled" yaml:"enabled"`
	CACertFile         string        `json:"caCertFile,omitempty" yaml:"ca_cert_file"`
	ClientCertFile     string        `json:"clientCertFile,omitempty" yaml:"client_cert_file"`
	ClientKeyFile      string        `json:"clientKeyFile,omitempty" yaml:"client_key_file"`
	InsecureSkipVerify bool          `json:"insecureSkipVerify,omitempty" yaml:"insecure_skip_verify"`
	MinVersion         string        `json:"minVersion,omitempty" yaml:"min_version"`
	CipherSuites       []string      `json:"cipherSuites,omitempty" yaml:"cipher_suites"`
	ReloadInterval     time.Duration `json:"reloadInterval,omitempty" yaml:"reload_interval"`
}

TLSConfig holds upstream TLS settings.

type TLSManager

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

TLSManager manages TLS configurations for upstream connections. It supports:

  • Global TLS configuration for all upstream connections
  • Per-target TLS overrides (specific CA certs, client certs for mTLS)
  • Automatic certificate reloading on a configurable interval
  • TLS version and cipher suite configuration
  • InsecureSkipVerify for development/testing

func NewTLSManager

func NewTLSManager(config TLSConfig, logger forge.Logger) *TLSManager

NewTLSManager creates a new TLS manager.

func (*TLSManager) GlobalTLSConfig

func (tm *TLSManager) GlobalTLSConfig() *tls.Config

GlobalTLSConfig returns the current global TLS configuration. This is safe for concurrent use.

func (*TLSManager) LastReload

func (tm *TLSManager) LastReload() time.Time

LastReload returns the time of the last certificate reload.

func (*TLSManager) Reload

func (tm *TLSManager) Reload() error

Reload forces an immediate certificate reload.

func (*TLSManager) Start

func (tm *TLSManager) Start()

Start begins the certificate reload loop if configured.

func (*TLSManager) Stop

func (tm *TLSManager) Stop()

Stop stops the certificate reload loop. It is safe to call multiple times.

func (*TLSManager) TargetTLSConfig

func (tm *TLSManager) TargetTLSConfig(target Target) *tls.Config

TargetTLSConfig returns a TLS configuration for a specific target. If the target has per-target TLS overrides, those are used. Otherwise, the global TLS config is returned.

func (*TLSManager) TransportForTarget

func (tm *TLSManager) TransportForTarget(baseTransport *http.Transport, target Target) *http.Transport

TransportForTarget returns an http.Transport configured with the appropriate TLS settings for the given target.

type Target

type Target interface {
	GetID() string
	GetTLS() *TargetTLSConfig
}

Target is a minimal interface for upstream targets used by the TLS manager.

type TargetTLSConfig

type TargetTLSConfig struct {
	Enabled            bool   `json:"enabled"`
	CACertFile         string `json:"caCertFile,omitempty"`
	ClientCertFile     string `json:"clientCertFile,omitempty"`
	ClientKeyFile      string `json:"clientKeyFile,omitempty"`
	InsecureSkipVerify bool   `json:"insecureSkipVerify,omitempty"`
	ServerName         string `json:"serverName,omitempty"`
}

TargetTLSConfig holds per-target TLS configuration.

type WAF

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

WAF is a Web Application Firewall that blocks malicious requests.

func NewWAF

func NewWAF(cfg WAFConfig) *WAF

NewWAF creates a WAF with the given configuration.

func (*WAF) Check

func (w *WAF) Check(r *http.Request) *WAFViolation

Check inspects an HTTP request and returns a violation if the request is malicious, or nil if it passes.

type WAFConfig

type WAFConfig struct {
	Enabled            bool      `json:"enabled"`
	MaxBodySize        int64     `json:"maxBodySize"` // bytes, 0 = no limit
	BlockSQLi          bool      `json:"blockSqli"`
	BlockXSS           bool      `json:"blockXss"`
	BlockPathTraversal bool      `json:"blockPathTraversal"`
	CustomRules        []WAFRule `json:"customRules,omitempty"`
}

WAFConfig configures the Web Application Firewall.

type WAFPlugin

type WAFPlugin struct {
	BasePlugin
	// contains filtered or unexported fields
}

WAFPlugin wraps the WAF as a gateway plugin.

func NewWAFPlugin

func NewWAFPlugin(cfg WAFConfig) *WAFPlugin

NewWAFPlugin creates a WAF plugin.

func (*WAFPlugin) CheckRequest

func (p *WAFPlugin) CheckRequest(r *http.Request) error

CheckRequest checks the request against WAF rules. Returns an error if the request is blocked.

type WAFRule

type WAFRule struct {
	Name    string `json:"name"`
	Pattern string `json:"pattern"` // regex pattern
	Target  string `json:"target"`  // "path", "query", "header:<name>", "body"
	Action  string `json:"action"`  // "block" or "log"
}

WAFRule defines a custom WAF detection rule.

type WAFViolation

type WAFViolation struct {
	Rule    string `json:"rule"`
	Message string `json:"message"`
}

WAFViolation describes a blocked request.

Jump to

Keyboard shortcuts

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