Documentation
¶
Overview ¶
Package authmode defines common types and utilities for auth modes.
Index ¶
- Constants
- Variables
- func FindAuthTokenByLocation(body *AuthenticateRequestData, location *authscheme.TokenLocation) (string, error)
- func GetAuthModeHeader(headers map[string]string) string
- func GetClientIPLocations() []string
- func NewAuthFieldRequiredError(authMode AuthMode, name string) error
- func SerializeSessionVariablesHasuraGraphQLEngine(sessionVariables map[string]any) (map[string]string, error)
- func ValidateTokenLocation(tokenLocation authscheme.TokenLocation) (authscheme.TokenLocation, error)
- type AuthMode
- type AuthenticateRequestData
- type AuthenticatedOutput
- type Authenticator
- type ClientIPLocation
- func (j ClientIPLocation) IsValid() bool
- func (ClientIPLocation) JSONSchema() *jsonschema.Schema
- func (j ClientIPLocation) MarshalJSON() ([]byte, error)
- func (j ClientIPLocation) MarshalText() ([]byte, error)
- func (j ClientIPLocation) String() string
- func (j *ClientIPLocation) UnmarshalJSON(input []byte) error
- func (j *ClientIPLocation) UnmarshalText(text []byte) error
- type HasuraV2PostRequestBody
- type RelyAuthAllowListConfig
- type RelyAuthAllowListMatcherRule
- type RelyAuthHeaderRules
- type RelyAuthIPAllowList
- type RelyAuthIPAllowListConfig
- type RelyAuthModeInterface
- type RelyAuthSecurityRules
- type RelyAuthSecurityRulesConfig
- type RelyAuthSettings
- type RelyAuthentication
- type RelyAuthenticator
- type RelyAuthenticatorOption
- func WithCustomAttributes(attrs []attribute.KeyValue) RelyAuthenticatorOption
- func WithCustomEnvGetter(getEnv goenvconf.GetEnvFunc) RelyAuthenticatorOption
- func WithHTTPClient(client *gohttpc.Client) RelyAuthenticatorOption
- func WithLogger(logger *slog.Logger) RelyAuthenticatorOption
- func WithPrefix(prefix string) RelyAuthenticatorOption
- type RelyAuthenticatorOptions
Constants ¶
const ( // XHasuraDefaultRole is the constant string of the x-hasura-default-role header name. XHasuraDefaultRole = "x-hasura-default-role" // XHasuraAllowedRoles is the constant string of the x-hasura-allowed-roles header name. XHasuraAllowedRoles = "x-hasura-allowed-roles" // XHasuraRole is the constant string of the x-hasura-role header name. XHasuraRole = "x-hasura-role" // XHasuraAuthMode is the constant string of the x-hasura-auth-mode header name. XHasuraAuthMode = "x-hasura-auth-mode" // XRelyAuthMode is the constant string of the x-rely-auth-mode header name. XRelyAuthMode = "x-rely-auth-mode" // XRelyAuthID is the constant string of the x-rely-auth-id header name. XRelyAuthID = "x-rely-auth-id" )
Variables ¶
var ( // ErrAuthConfigRequired occurs when the auth config is null. ErrAuthConfigRequired = errors.New("auth definition is empty") // ErrAuthModeRequired occurs when the auth mode is null. ErrAuthModeRequired = errors.New("auth mode is empty") // ErrAuthConfigValueRequired occurs when the auth value is empty. ErrAuthConfigValueRequired = errors.New("auth definition value is empty") // ErrOnlyOneNoAuthModeAllowed occurs when there are many auth config definitions with noAuth mode. ErrOnlyOneNoAuthModeAllowed = errors.New("only one noAuth config is allowed") // ErrAuthFieldRequired occurs when a field in the auth config is empty. ErrAuthFieldRequired = errors.New("required field") // ErrAuthTokenNotFound occurs when the API key or token is not found. ErrAuthTokenNotFound = errors.New("auth token not found") // ErrUnsupportedAuthMode occurs when the auth mode is unsupported. ErrUnsupportedAuthMode = errors.New("unsupported auth mode") // ErrEmptyAllowedIPs occurs when the allowed IPs config is empty. ErrEmptyAllowedIPs = errors.New("allowed IPs config is empty") // ErrInvalidSubnet occurs when the subnet string is invalid. ErrInvalidSubnet = errors.New("invalid IP or subnet") // ErrInvalidIP occurs when the IP string is invalid. ErrInvalidIP = errors.New("invalid IP") // ErrIPNotFound occurs when the IP does not exist in request headers. ErrIPNotFound = errors.New("ip not found") // ErrInvalidHeader occurs when the header does not satisfy the security rule. ErrInvalidHeader = errors.New("invalid header") // ErrInvalidClientIPLocation occurs when the client IP location enum is invalid. ErrInvalidClientIPLocation = fmt.Errorf( "invalid Client IP location. Expected one of %v", GetClientIPLocations(), ) // ErrClientIPHeaderRequired occurs when headers are required if client IP is header. ErrClientIPHeaderRequired = errors.New( "require at least 1 header name if the client IP location is header") )
Functions ¶
func FindAuthTokenByLocation ¶
func FindAuthTokenByLocation( body *AuthenticateRequestData, location *authscheme.TokenLocation, ) (string, error)
FindAuthTokenByLocation finds the authentication token or api key from the request.
func GetAuthModeHeader ¶ added in v0.0.2
GetAuthModeHeader gets the authentication mode from request headers. Note that headers must be converted to a string map with keys in lower-case.
func GetClientIPLocations ¶ added in v0.0.3
func GetClientIPLocations() []string
GetClientIPLocations get the list of forwarded IP position enum.
func NewAuthFieldRequiredError ¶
NewAuthFieldRequiredError creates a required auth field error.
func SerializeSessionVariablesHasuraGraphQLEngine ¶
func SerializeSessionVariablesHasuraGraphQLEngine( sessionVariables map[string]any, ) (map[string]string, error)
SerializeSessionVariablesHasuraGraphQLEngine serializes session variables to be compatible with Hasura GraphQL Engine.
func ValidateTokenLocation ¶
func ValidateTokenLocation( tokenLocation authscheme.TokenLocation, ) (authscheme.TokenLocation, error)
ValidateTokenLocation validates the token location.
Types ¶
type AuthMode ¶
type AuthMode string
AuthMode represents an authentication mode enum.
func GetSupportedAuthModes ¶
func GetSupportedAuthModes() []AuthMode
GetSupportedAuthModes gets the list of supported auth modes.
type AuthenticateRequestData ¶
type AuthenticateRequestData struct {
// URL of the original request.
URL string `json:"url,omitempty"`
// Request headers.
Headers map[string]string `json:"headers"`
// Raw request body.
Request json.RawMessage `json:"request"`
// Remote address.
RemoteAddr string `json:"-"`
}
AuthenticateRequestData contains the request body of the auth hook request.
type AuthenticatedOutput ¶
AuthenticatedOutput represents the authenticated output and authenticator metadata.
type Authenticator ¶
type Authenticator interface {
// Authenticate validates and authenticates the token from the auth webhook request.
Authenticate(ctx context.Context, body *AuthenticateRequestData) (AuthenticatedOutput, error)
}
Authenticator abstracts an authenticator struct for the Authenticate method.
type ClientIPLocation ¶ added in v0.0.3
type ClientIPLocation uint8
ClientIPLocation represents the location where the client IP should be parsed from.
const ( // ClientIPFromXForwardedFor represents the location of client IP read from the X-Forwarded-For header, // walking the chain right-to-left and skipping any IP that falls within one of the given trusted CIDR prefixes. // The first IP that is not trusted is the client. // ClientIPFromXForwardForTrustedProxies stores the client IP read from the X-Forwarded-For header, given the exact number of trusted reverse proxies between this server and the public internet. // It returns the IP at position len(xff) - numTrustedProxies in the merged X-Forwarded-For list — the IP added by the outermost of your trusted proxies, // the only IP in the chain that none of your proxies have allowed an attacker to forge. ClientIPFromXForwardedFor ClientIPLocation = iota // ClientIPFromHeader stores the client IP from a single-IP header set by your reverse proxy. // Only safe with headers your proxy unconditionally OVERWRITES on every request, e.g.: X-Real-IP, X-Client-IP, CF-Connecting-IP. // If the header reaches us with multiple values (misconfigured proxy that appends, or a downstream proxy not stripping a client-supplied value), // the LAST value wins — that's the one set by the hop closest to us, and therefore the most trusted. // Fail-closed if the last value doesn't parse: no client IP is set rather than falling back to earlier (less-trusted) values. // v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are stripped before storage. ClientIPFromHeader // ClientIPFromRemoteAddr stores the client IP read from the TCP RemoteAddr of the incoming request — the IP address of whoever opened the connection to this server. // Use this strategy when this server is directly connected to the public internet with NO reverse proxy in front of it. // Behind a reverse proxy, RemoteAddr is the proxy's IP, not the client's — use ClientIPFromHeader or ClientIPFromXFF instead. // IPv4 clients on a dual-stack listener surface as ::ffff:a.b.c.d; they fold to plain v4 before storage so one logical client maps to one key. // IPv6 zones are preserved (link-local connections may legitimately have one). ClientIPFromRemoteAddr )
func ParseClientIPLocation ¶ added in v0.0.3
func ParseClientIPLocation(value string) (ClientIPLocation, error)
ParseClientIPLocation parses a ClientIPLocation from string.
func (ClientIPLocation) IsValid ¶ added in v0.0.3
func (j ClientIPLocation) IsValid() bool
IsValid if the current instance is valid.
func (ClientIPLocation) JSONSchema ¶ added in v0.0.3
func (ClientIPLocation) JSONSchema() *jsonschema.Schema
JSONSchema defines a custom definition for JSON schema.
func (ClientIPLocation) MarshalJSON ¶ added in v0.0.3
func (j ClientIPLocation) MarshalJSON() ([]byte, error)
MarshalJSON marshals themselves into valid JSON.
func (ClientIPLocation) MarshalText ¶ added in v0.0.3
func (j ClientIPLocation) MarshalText() ([]byte, error)
MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
func (ClientIPLocation) String ¶ added in v0.0.3
func (j ClientIPLocation) String() string
String implements fmt.Stringer interface.
func (*ClientIPLocation) UnmarshalJSON ¶ added in v0.0.3
func (j *ClientIPLocation) UnmarshalJSON(input []byte) error
UnmarshalJSON unmarshals a JSON description of themselves.
func (*ClientIPLocation) UnmarshalText ¶ added in v0.0.3
func (j *ClientIPLocation) UnmarshalText(text []byte) error
UnmarshalText must be able to decode the form generated by MarshalText.
type HasuraV2PostRequestBody ¶
type HasuraV2PostRequestBody struct {
Variables map[string]any `json:"variables"`
OperationName string `json:"operationName,omitempty"`
Query string `json:"query"`
}
HasuraV2PostRequestBody holds the original body of the request. It's available in [Hasura GraphQL Engine v2](https://hasura.io/docs/2.0/auth/authentication/webhook/#post-request-example) only.
[Hasura GraphQL Engine v2](https://hasura.io/docs/2.0/auth/authentication/webhook/#post-request-example)
type RelyAuthAllowListConfig ¶ added in v0.0.3
type RelyAuthAllowListConfig struct {
// List of allowed patterns.
Include *goenvconf.EnvStringSlice `json:"include,omitempty" yaml:"include,omitempty"`
// List of disallowed patterns.
Exclude *goenvconf.EnvStringSlice `json:"exclude,omitempty" yaml:"exclude,omitempty"`
}
RelyAuthAllowListConfig represents a common setting for allow list.
func (RelyAuthAllowListConfig) Equal ¶ added in v0.0.3
func (hal RelyAuthAllowListConfig) Equal(target RelyAuthAllowListConfig) bool
Equal checks if the target value is equal.
func (RelyAuthAllowListConfig) IsZero ¶ added in v0.0.3
func (hal RelyAuthAllowListConfig) IsZero() bool
IsZero if the current instance is empty.
type RelyAuthAllowListMatcherRule ¶ added in v0.0.3
type RelyAuthAllowListMatcherRule struct {
// List of regular expressions that are allowed to access.
Include []*goutils.RegexpMatcher
// List of regular expressions that are denied to access.
Exclude []*goutils.RegexpMatcher
}
RelyAuthAllowListMatcherRule represents a matcher rule for a field.
func AllowListMatcherRuleFromConfig ¶ added in v0.0.3
func AllowListMatcherRuleFromConfig( conf RelyAuthAllowListConfig, getEnvFunc goenvconf.GetEnvFunc, ) (*RelyAuthAllowListMatcherRule, error)
AllowListMatcherRuleFromConfig creates an allow list matcher rule from config.
func (RelyAuthAllowListMatcherRule) IsValid ¶ added in v0.0.3
func (hr RelyAuthAllowListMatcherRule) IsValid(value string) bool
IsValid checks if the request satisfies the security rule.
type RelyAuthHeaderRules ¶ added in v0.0.2
type RelyAuthHeaderRules map[string]RelyAuthAllowListMatcherRule
RelyAuthHeaderRules represents a map of header rules.
func HeaderRulesFromConfig ¶ added in v0.0.3
func HeaderRulesFromConfig( conf map[string]RelyAuthAllowListConfig, getEnvFunc goenvconf.GetEnvFunc, ) (RelyAuthHeaderRules, error)
HeaderRulesFromConfig creates a header map with expression matchers from config.
func (RelyAuthHeaderRules) Validate ¶ added in v0.0.2
func (hr RelyAuthHeaderRules) Validate(body *AuthenticateRequestData) error
Validate checks if the request satisfies the security rule.
type RelyAuthIPAllowList ¶ added in v0.0.3
type RelyAuthIPAllowList struct {
goutils.ValidateIPOptions
Headers []string
Location ClientIPLocation
TrustedProxyIPPrefixes []*net.IPNet
NumTrustedProxies int32
}
RelyAuthIPAllowList holds security rules of the IP allow list from the parsed config.
func AllowedIPsFromConfig ¶ added in v0.0.3
func AllowedIPsFromConfig( conf *RelyAuthIPAllowListConfig, getEnvFunc goenvconf.GetEnvFunc, ) (*RelyAuthIPAllowList, error)
AllowedIPsFromConfig creates a RelyAuthIPAllowList instance from config.
func (*RelyAuthIPAllowList) GetClientIPs ¶ added in v0.0.3
func (rai *RelyAuthIPAllowList) GetClientIPs(data *AuthenticateRequestData) (net.IP, error)
GetClientIPs gets the client IPs from request data.
func (*RelyAuthIPAllowList) Validate ¶ added in v0.0.3
func (rai *RelyAuthIPAllowList) Validate(body *AuthenticateRequestData) error
Validate checks if the request satisfies the security rule.
type RelyAuthIPAllowListConfig ¶ added in v0.0.2
type RelyAuthIPAllowListConfig struct {
RelyAuthAllowListConfig `yaml:",inline"`
// The location of the IP to select. Default is the X-Forwarded-For header.
Location ClientIPLocation `json:"location,omitempty" yaml:"location,omitempty"`
// Allow public IPs only.
PublicOnly bool `json:"publicOnly,omitempty" yaml:"publicOnly,omitempty"`
// The exact number of trusted reverse proxies between this server and the public internet. Required if location=x_forwarded_for.
NumTrustedProxies int32 `json:"numTrustedProxies,omitempty" yaml:"numTrustedProxies,omitempty"`
// Proxy IPs must be in these trusted proxy prefixes. Ignore if empty. This configuration is available if location=x_forwarded_for.
TrustedProxyIPPrefixes []string `json:"trustedProxyIpPrefixes,omitempty" yaml:"trustedProxyIpPrefixes,omitempty"`
// The client IP could be in this header list. Required if location=header.
Headers []string `json:"headers,omitempty" yaml:"headers,omitempty"`
}
RelyAuthIPAllowListConfig represents a setting for IP allow list. Note that IP headers aren't safe and can be spoofed by the client. Therefore, make sure that the header of origin IPs is trusted. Read more details at https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For#security_and_privacy_concerns
func (RelyAuthIPAllowListConfig) Equal ¶ added in v0.0.2
func (hal RelyAuthIPAllowListConfig) Equal(target RelyAuthIPAllowListConfig) bool
Equal checks if the target value is equal.
func (RelyAuthIPAllowListConfig) IsZero ¶ added in v0.0.2
func (hal RelyAuthIPAllowListConfig) IsZero() bool
IsZero if the current instance is empty.
func (RelyAuthIPAllowListConfig) JSONSchemaExtend ¶ added in v0.0.3
func (RelyAuthIPAllowListConfig) JSONSchemaExtend(schema *jsonschema.Schema)
JSONSchemaExtend extends the JSON schema with custom fields.
type RelyAuthModeInterface ¶ added in v0.0.3
type RelyAuthModeInterface interface {
goutils.IsZeroer
// GetMode returns the auth mode of the current config.
GetMode() AuthMode
// Validate if the current instance is valid.
Validate() error
}
RelyAuthModeInterface abstracts the interface of an auth mode definition.
type RelyAuthSecurityRules ¶ added in v0.0.2
type RelyAuthSecurityRules struct {
// Configure the list of allowed IPs.
AllowedIPs *RelyAuthIPAllowList
// Configure the list of extra header rules.
HeaderRules RelyAuthHeaderRules
}
RelyAuthSecurityRules defines rules to harden the security.
func RelyAuthSecurityRulesFromConfig ¶ added in v0.0.2
func RelyAuthSecurityRulesFromConfig( conf *RelyAuthSecurityRulesConfig, getEnvFunc goenvconf.GetEnvFunc, ) (*RelyAuthSecurityRules, error)
RelyAuthSecurityRulesFromConfig creates a RelyAuthSecurityRules from configurations.
func (*RelyAuthSecurityRules) Validate ¶ added in v0.0.2
func (sr *RelyAuthSecurityRules) Validate(body *AuthenticateRequestData) error
Validate checks if the webhook request satisfies security rules.
type RelyAuthSecurityRulesConfig ¶ added in v0.0.2
type RelyAuthSecurityRulesConfig struct {
// Configure the list of allowed IPs.
AllowedIPs *RelyAuthIPAllowListConfig `json:"allowedIPs,omitempty" yaml:"allowedIPs,omitempty"`
// Configure the map of header rules.
HeaderRules map[string]RelyAuthAllowListConfig `json:"headerRules,omitempty" yaml:"headerRules,omitempty"`
}
RelyAuthSecurityRulesConfig defines configurations of security rules.
func (RelyAuthSecurityRulesConfig) Equal ¶ added in v0.0.2
func (es RelyAuthSecurityRulesConfig) Equal(target RelyAuthSecurityRulesConfig) bool
Equal checks if the target value is equal.
func (RelyAuthSecurityRulesConfig) IsZero ¶ added in v0.0.2
func (es RelyAuthSecurityRulesConfig) IsZero() bool
IsZero if the current instance is empty.
type RelyAuthSettings ¶
type RelyAuthSettings struct {
// The interval in seconds to reload JSON web keys from the remote URL.
// If the value is zero or negative, disables the process.
ReloadInterval int `json:"reloadInterval,omitempty" yaml:"reloadInterval,omitempty" jsonschema:"minimum=0,default=0"`
}
RelyAuthSettings holds global settings for the authenticators.
type RelyAuthentication ¶ added in v0.0.2
type RelyAuthentication struct {
RelyAuthenticator
SecurityRules *RelyAuthSecurityRules
}
RelyAuthentication is the wrapper of RelyAuthenticator with extra security rules.
func (*RelyAuthentication) Authenticate ¶ added in v0.0.2
func (ra *RelyAuthentication) Authenticate( ctx context.Context, body *AuthenticateRequestData, ) (AuthenticatedOutput, error)
Authenticate validates and authenticates the token from the auth webhook request.
type RelyAuthenticator ¶
type RelyAuthenticator interface {
Authenticator
// IDs returns identities of this authenticator.
IDs() []string
// GetMode returns the auth mode of the current authenticator.
Mode() AuthMode
// Close handles the resources cleaning.
Close() error
}
RelyAuthenticator abstracts the authenticator for the auth webhook.
type RelyAuthenticatorOption ¶
type RelyAuthenticatorOption func(*RelyAuthenticatorOptions)
RelyAuthenticatorOption abstracts a function to modify RelyAuthenticatorOptions.
func WithCustomAttributes ¶
func WithCustomAttributes(attrs []attribute.KeyValue) RelyAuthenticatorOption
WithCustomAttributes sets custom trace and metrics attributes to auth manager options.
func WithCustomEnvGetter ¶
func WithCustomEnvGetter( getEnv goenvconf.GetEnvFunc, ) RelyAuthenticatorOption
WithCustomEnvGetter returns a function to set the GetEnvFunc getter to RelyAuthenticatorOptions.
func WithHTTPClient ¶
func WithHTTPClient(client *gohttpc.Client) RelyAuthenticatorOption
WithHTTPClient sets the HTTP client to auth manager options.
func WithLogger ¶
func WithLogger(logger *slog.Logger) RelyAuthenticatorOption
WithLogger sets the logger to auth manager options.
func WithPrefix ¶
func WithPrefix(prefix string) RelyAuthenticatorOption
WithPrefix sets the prefix to auth manager options.
type RelyAuthenticatorOptions ¶
type RelyAuthenticatorOptions struct {
GetEnv goenvconf.GetEnvFunc
Logger *slog.Logger
HTTPClient *gohttpc.Client
CustomAttributes []attribute.KeyValue
// Prefix is used to create unique JWKS registration keys, allowing multiple authenticators
// to register the same JWKS URL independently.
Prefix string
}
RelyAuthenticatorOptions define common options for the authenticator.
func NewRelyAuthenticatorOptions ¶
func NewRelyAuthenticatorOptions(options ...RelyAuthenticatorOption) RelyAuthenticatorOptions
NewRelyAuthenticatorOptions creates a new RelyAuthenticatorOptions instance.
func (RelyAuthenticatorOptions) GetEnvFunc ¶
func (rao RelyAuthenticatorOptions) GetEnvFunc() goenvconf.GetEnvFunc
GetEnvFunc return the get-env function. Default is OS environment.