Documentation
¶
Overview ¶
Package auth provides authentication and authorization functionality.
Index ¶
- Constants
- func APIKeyFromContext(ctx context.Context) (string, bool)
- func ContextWithAPIKey(ctx context.Context, apiKey string) context.Context
- func ContextWithProfileID(ctx context.Context, profileID string) context.Context
- func ContextWithRoles(ctx context.Context, roles []string) context.Context
- func ContextWithUser(ctx context.Context, userID string) context.Context
- func NewPerRPCCredentials(authenticator UpstreamAuthenticator) credentials.PerRPCCredentials
- func ProfileIDFromContext(ctx context.Context) (string, bool)
- func RolesFromContext(ctx context.Context) ([]string, bool)
- func UserFromContext(ctx context.Context) (string, bool)
- func ValidateAuthentication(ctx context.Context, config *configv1.Authentication, r *http.Request) error
- type APIKeyAuth
- type APIKeyAuthenticator
- type Authenticator
- type BasicAuth
- type BasicAuthenticator
- type BearerTokenAuth
- type Manager
- func (am *Manager) AddAuthenticator(serviceID string, authenticator Authenticator) error
- func (am *Manager) AddOAuth2Authenticator(ctx context.Context, serviceID string, config *OAuth2Config) error
- func (am *Manager) Authenticate(ctx context.Context, serviceID string, r *http.Request) (context.Context, error)
- func (am *Manager) GetAuthenticator(serviceID string) (Authenticator, bool)
- func (am *Manager) GetUser(id string) (*configv1.User, bool)
- func (am *Manager) HandleOAuthCallback(ctx context.Context, userID, serviceID, credentialID, code, redirectURL string) error
- func (am *Manager) InitiateOAuth(ctx context.Context, userID, serviceID, credentialID, redirectURL string) (string, string, error)
- func (am *Manager) RemoveAuthenticator(serviceID string)
- func (am *Manager) SetAPIKey(apiKey string)
- func (am *Manager) SetStorage(s storage.Storage)
- func (am *Manager) SetUsers(users []*configv1.User)
- type MockOAuth2Server
- type MockUpstreamAuthenticator
- type OAuth2Auth
- type OAuth2Authenticator
- type OAuth2Config
- type OIDCConfig
- type OIDCProvider
- type PerRPCCredentials
- type RBACEnforcer
- type TrustedHeaderAuthenticator
- type UpstreamAuthenticator
Constants ¶
const ( // UserContextKey is the context key for the user ID. UserContextKey authContextKey = "user_id" // ProfileIDContextKey is the context key for the profile ID. ProfileIDContextKey authContextKey = "profile_id" // APIKeyContextKey is the context key for the API Key. APIKeyContextKey authContextKey = "api_key" )
const RolesContextKey authContextKey = "user_roles"
RolesContextKey is the context key for the user roles.
Variables ¶
This section is empty.
Functions ¶
func APIKeyFromContext ¶
APIKeyFromContext returns the API Key from the context.
func ContextWithAPIKey ¶
ContextWithAPIKey returns a new context with the API Key.
func ContextWithProfileID ¶
ContextWithProfileID returns a new context with the profile ID.
func ContextWithRoles ¶
ContextWithRoles returns a new context with the user roles.
func ContextWithUser ¶
ContextWithUser returns a new context with the user ID.
func NewPerRPCCredentials ¶
func NewPerRPCCredentials(authenticator UpstreamAuthenticator) credentials.PerRPCCredentials
NewPerRPCCredentials creates a new gRPC PerRPCCredentials from an UpstreamAuthenticator. It returns nil if the provided authenticator is nil.
authenticator is the upstream authenticator to be used for generating gRPC request metadata.
func ProfileIDFromContext ¶
ProfileIDFromContext returns the profile ID from the context.
func RolesFromContext ¶
RolesFromContext returns the user roles from the context.
func UserFromContext ¶
UserFromContext returns the user ID from the context.
func ValidateAuthentication ¶
func ValidateAuthentication(ctx context.Context, config *configv1.Authentication, r *http.Request) error
ValidateAuthentication validates the authentication request against the provided configuration. It supports API Key and OAuth2 authentication methods.
Parameters:
- ctx: The context for the request.
- config: The authentication configuration.
- r: The HTTP request to validate.
Returns an error if validation fails or the method is unsupported.
Types ¶
type APIKeyAuth ¶
type APIKeyAuth struct {
ParamName string
Value *configv1.SecretValue
Location configv1.APIKeyAuth_Location
}
APIKeyAuth implements UpstreamAuthenticator for API key-based authentication. It adds a specified header with a static API key value to the request.
func (*APIKeyAuth) Authenticate ¶
func (a *APIKeyAuth) Authenticate(req *http.Request) error
Authenticate adds the configured API key to the request's header, query, or cookie.
Parameters:
- req: The HTTP request to be modified.
Returns:
- nil on success, or an error if the secret cannot be resolved.
type APIKeyAuthenticator ¶
type APIKeyAuthenticator struct {
ParamName string
In configv1.APIKeyAuth_Location
Value string
}
APIKeyAuthenticator provides an authentication mechanism based on a static API key. It implements the `Authenticator` interface and checks for the presence of a specific header, validating its value against a configured key.
func NewAPIKeyAuthenticator ¶
func NewAPIKeyAuthenticator(config *configv1.APIKeyAuth) *APIKeyAuthenticator
NewAPIKeyAuthenticator creates a new APIKeyAuthenticator from the provided configuration. It returns `nil` if the configuration is invalid (e.g., if the header name or key value is missing).
Parameters:
- config: The API key authentication settings, including the header parameter name and the key value.
Returns a new instance of APIKeyAuthenticator or `nil` if the configuration is invalid.
func (*APIKeyAuthenticator) Authenticate ¶
func (a *APIKeyAuthenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, error)
Authenticate verifies the API key in the request. It checks if the parameter specified by `ParamName` matches the expected `Value`.
If the API key is valid, the original context is returned with no error. If the key is invalid or missing, an "unauthorized" error is returned.
Parameters:
- ctx: The request context, which is returned unmodified on success.
- r: The HTTP request to authenticate.
Returns the original context and `nil` on success, or an error on failure. Authenticate verifies the API key in the request.
type Authenticator ¶
type Authenticator interface {
// Authenticate returns the authenticated user's context or an error.
Authenticate(ctx context.Context, r *http.Request) (context.Context, error)
}
Authenticator checks if a request is authenticated.
type BasicAuth ¶
type BasicAuth struct {
Username string
Password *configv1.SecretValue
}
BasicAuth implements UpstreamAuthenticator for basic HTTP authentication. It adds an "Authorization" header with the username and password.
type BasicAuthenticator ¶
BasicAuthenticator authenticates using HTTP Basic Auth and bcrypt password hashing.
func NewBasicAuthenticator ¶
func NewBasicAuthenticator(config *configv1.BasicAuth) *BasicAuthenticator
NewBasicAuthenticator creates a new BasicAuthenticator.
func (*BasicAuthenticator) Authenticate ¶
func (a *BasicAuthenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, error)
Authenticate validates the basic auth credentials.
type BearerTokenAuth ¶
type BearerTokenAuth struct {
Token *configv1.SecretValue
}
BearerTokenAuth implements UpstreamAuthenticator for bearer token-based authentication. It adds an "Authorization" header with a bearer token.
func (*BearerTokenAuth) Authenticate ¶
func (b *BearerTokenAuth) Authenticate(req *http.Request) error
Authenticate adds the bearer token to the request's "Authorization" header.
Parameters:
- req: The HTTP request to be modified.
Returns:
- nil on success, or an error if the secret cannot be resolved.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager oversees the authentication process for the server. It maintains a registry of authenticators, each associated with a specific service ID, and delegates the authentication of requests to the appropriate authenticator. This allows for different authentication strategies to be used for different services.
func NewManager ¶
func NewManager() *Manager
NewManager creates and initializes a new Manager with an empty authenticator registry. This manager can then be used to register and manage authenticators for various services.
func (*Manager) AddAuthenticator ¶
func (am *Manager) AddAuthenticator(serviceID string, authenticator Authenticator) error
AddAuthenticator registers an authenticator for a given service ID. If an authenticator is already registered for the same service ID, it will be overwritten.
Parameters:
- serviceID: The unique identifier for the service.
- authenticator: The authenticator to be associated with the service.
Returns an error if the provided authenticator is `nil`.
func (*Manager) AddOAuth2Authenticator ¶
func (am *Manager) AddOAuth2Authenticator(ctx context.Context, serviceID string, config *OAuth2Config) error
AddOAuth2Authenticator creates and registers a new OAuth2Authenticator for a given service ID. It initializes the authenticator using the provided OAuth2 configuration.
This is a convenience method that simplifies the process of setting up OAuth2 authentication for a service.
Parameters:
- ctx: The context for initializing the OIDC provider.
- serviceID: The unique identifier for the service.
- config: The OAuth2 configuration for the authenticator.
Returns an error if the authenticator cannot be created.
func (*Manager) Authenticate ¶
func (am *Manager) Authenticate(ctx context.Context, serviceID string, r *http.Request) (context.Context, error)
Authenticate authenticates a request for a specific service. It looks up the authenticator registered for the given service ID and, if found, uses it to validate the request.
If no authenticator is found for the service, the request is allowed to proceed without authentication.
Parameters:
- ctx: The request context.
- serviceID: The identifier of the service being accessed.
- r: The HTTP request to authenticate.
Returns a potentially modified context on success, or an error if authentication fails.
func (*Manager) GetAuthenticator ¶
func (am *Manager) GetAuthenticator(serviceID string) (Authenticator, bool)
GetAuthenticator retrieves the authenticator registered for a specific service.
Parameters:
- serviceID: The identifier of the service.
Returns the authenticator and a boolean indicating whether an authenticator was found.
func (*Manager) HandleOAuthCallback ¶
func (am *Manager) HandleOAuthCallback(ctx context.Context, userID, serviceID, credentialID, code, redirectURL string) error
HandleOAuthCallback handles the OAuth2 callback code exchange.
func (*Manager) InitiateOAuth ¶
func (am *Manager) InitiateOAuth(ctx context.Context, userID, serviceID, credentialID, redirectURL string) (string, string, error)
InitiateOAuth starts the OAuth2 flow for a given service or credential. It returns the authorization URL and the state parameter.
func (*Manager) RemoveAuthenticator ¶
RemoveAuthenticator removes the authenticator for a given service ID.
func (*Manager) SetStorage ¶
SetStorage sets the storage.
type MockOAuth2Server ¶
type MockOAuth2Server struct {
*httptest.Server
PrivateKey *rsa.PrivateKey
}
MockOAuth2Server serves as a mock OIDC/OAuth2 provider.
func NewMockOAuth2Server ¶
func NewMockOAuth2Server(t *testing.T) *MockOAuth2Server
NewMockOAuth2Server creates a new mock OAuth2 server.
func (*MockOAuth2Server) NewIDToken ¶
NewIDToken permits generating custom tokens signed by this server.
type MockUpstreamAuthenticator ¶
MockUpstreamAuthenticator is a mock implementation of UpstreamAuthenticator for testing.
func (*MockUpstreamAuthenticator) Authenticate ¶
func (m *MockUpstreamAuthenticator) Authenticate(req *http.Request) error
Authenticate executes the mock mock authentication function.
type OAuth2Auth ¶
type OAuth2Auth struct {
ClientID *configv1.SecretValue
ClientSecret *configv1.SecretValue
TokenURL string
Scopes []string
}
OAuth2Auth implements UpstreamAuthenticator for OAuth2 client credentials flow.
func (*OAuth2Auth) Authenticate ¶
func (o *OAuth2Auth) Authenticate(req *http.Request) error
Authenticate fetches a token and adds it to the request's "Authorization" header.
Parameters:
- req: The HTTP request to be modified.
Returns:
- nil on success, or an error if the token cannot be obtained.
type OAuth2Authenticator ¶
type OAuth2Authenticator struct {
// contains filtered or unexported fields
}
OAuth2Authenticator implements the Authenticator interface for OAuth2-based authentication using OpenID Connect (OIDC). It validates JWTs (JSON Web Tokens) presented in the HTTP Authorization header.
func NewOAuth2Authenticator ¶
func NewOAuth2Authenticator(ctx context.Context, config *OAuth2Config) (*OAuth2Authenticator, error)
NewOAuth2Authenticator creates a new OAuth2Authenticator with the provided configuration. It initializes the OIDC provider and creates a verifier for validating ID tokens.
Parameters:
- ctx: The context for the OIDC provider initialization.
- config: The OAuth2 configuration, including the issuer URL and client ID.
Returns:
- A new OAuth2Authenticator.
- An error if the OIDC provider cannot be initialized.
func (*OAuth2Authenticator) Authenticate ¶
func (a *OAuth2Authenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, error)
Authenticate validates the JWT from the Authorization header of the request. It checks for a "Bearer" token and verifies its signature, expiration, and claims against the OIDC provider.
Parameters:
- ctx: The request context.
- r: The HTTP request to authenticate.
Returns:
- The context with the user's identity (email) on success.
- An error if authentication fails.
type OAuth2Config ¶
type OAuth2Config struct {
// IssuerURL is the URL of the OIDC provider's issuer. This is used to
// fetch the provider's public keys for token validation.
IssuerURL string
// verify that the token's 'aud' claim matches this value.
//
// Deprecated: Use Audiences instead.
Audience string
// Audiences is the list of intended audiences of the JWT. The authenticator will
// verify that the token's 'aud' claim matches at least one of these values.
Audiences []string
}
OAuth2Config holds the configuration for OAuth2 authentication. It is used to configure the OAuth2Authenticator with the necessary parameters to validate JWTs against an OIDC provider.
type OIDCConfig ¶
OIDCConfig holds the configuration for the OIDC provider.
type OIDCProvider ¶
type OIDCProvider struct {
// contains filtered or unexported fields
}
OIDCProvider handles OIDC authentication flow.
func NewOIDCProvider ¶
func NewOIDCProvider(ctx context.Context, config OIDCConfig) (*OIDCProvider, error)
NewOIDCProvider creates a new OIDCProvider.
func (*OIDCProvider) HandleCallback ¶
func (p *OIDCProvider) HandleCallback(w http.ResponseWriter, r *http.Request)
HandleCallback handles the OIDC provider callback.
func (*OIDCProvider) HandleLogin ¶
func (p *OIDCProvider) HandleLogin(w http.ResponseWriter, r *http.Request)
HandleLogin initiates the OIDC login flow.
type PerRPCCredentials ¶
type PerRPCCredentials struct {
// contains filtered or unexported fields
}
PerRPCCredentials adapts an UpstreamAuthenticator to the gRPC credentials.PerRPCCredentials interface. It allows applying upstream authentication headers to outgoing gRPC requests.
func (*PerRPCCredentials) GetRequestMetadata ¶
func (c *PerRPCCredentials) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error)
GetRequestMetadata retrieves the authentication metadata for an outgoing gRPC request. It uses the wrapped UpstreamAuthenticator to generate the necessary headers and transforms them into gRPC metadata.
ctx is the context for the request. uri is the URI of the gRPC service being called.
func (*PerRPCCredentials) RequireTransportSecurity ¶
func (c *PerRPCCredentials) RequireTransportSecurity() bool
RequireTransportSecurity indicates whether a secure transport (e.g., TLS) is required for the credentials. This implementation returns false, but should be updated if TLS is enabled for the gRPC connection.
type RBACEnforcer ¶
type RBACEnforcer struct {
}
RBACEnforcer handles Role-Based Access Control checks.
func NewRBACEnforcer ¶
func NewRBACEnforcer() *RBACEnforcer
NewRBACEnforcer creates a new RBACEnforcer.
func (*RBACEnforcer) HasAnyRole ¶
func (e *RBACEnforcer) HasAnyRole(user *configv1.User, roles []string) bool
HasAnyRole checks if the user has at least one of the specified roles.
func (*RBACEnforcer) HasRole ¶
func (e *RBACEnforcer) HasRole(user *configv1.User, role string) bool
HasRole checks if the given user has the specified role.
func (*RBACEnforcer) HasRoleInContext ¶
func (e *RBACEnforcer) HasRoleInContext(ctx context.Context, role string) bool
HasRoleInContext checks if the context contains the specified role.
type TrustedHeaderAuthenticator ¶
type TrustedHeaderAuthenticator struct {
HeaderName string
HeaderValue string // Optional: if empty, just checks presence
}
TrustedHeaderAuthenticator authenticates using a trusted header (e.g., from an auth proxy).
func NewTrustedHeaderAuthenticator ¶
func NewTrustedHeaderAuthenticator(config *configv1.TrustedHeaderAuth) *TrustedHeaderAuthenticator
NewTrustedHeaderAuthenticator creates a new TrustedHeaderAuthenticator.
func (*TrustedHeaderAuthenticator) Authenticate ¶
func (a *TrustedHeaderAuthenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, error)
Authenticate validates the trusted header.
type UpstreamAuthenticator ¶
type UpstreamAuthenticator interface {
// Authenticate modifies the given HTTP request to add authentication
// information, such as headers or basic auth credentials.
Authenticate(req *http.Request) error
}
UpstreamAuthenticator defines the interface for authentication methods used when communicating with upstream services. Each implementation is responsible for modifying the HTTP request to include the necessary authentication credentials.
func NewUpstreamAuthenticator ¶
func NewUpstreamAuthenticator(authConfig *configv1.Authentication) (UpstreamAuthenticator, error)
NewUpstreamAuthenticator creates an `UpstreamAuthenticator` based on the provided authentication configuration. It supports API key, bearer token, and basic authentication, as well as substitution of environment variables in the authentication parameters.
If the `authConfig` is `nil`, no authenticator is created, and the function returns `nil, nil`. If the configuration is invalid (e.g., missing required fields), an error is returned.
Parameters:
- authConfig: The configuration that specifies the authentication method and its parameters.
Returns:
- An `UpstreamAuthenticator` implementation, or nil if no auth is configured.
- An error if the configuration is invalid.
NewUpstreamAuthenticator creates an `UpstreamAuthenticator` based on the provided authentication configuration. It supports API key, bearer token, and basic authentication, as well as substitution of environment variables in the authentication parameters.
If the `authConfig` is `nil`, no authenticator is created, and the function returns `nil, nil`. If the configuration is invalid (e.g., missing required fields), an error is returned.
Parameters:
- authConfig: The configuration that specifies the authentication method and its parameters.
Returns:
- An `UpstreamAuthenticator` implementation, or nil if no auth is configured.
- An error if the configuration is invalid.