Documentation
¶
Overview ¶
Package basic provides HTTP Basic authentication middleware and utilities.
Index ¶
- Constants
- Variables
- func AddCredentials(req *http.Request) (added bool)
- func AddCredentialsWithProvider(req *http.Request, provider *NetrcProvider) (added bool)
- type AuthMap
- type BasicAuthPair
- type ClientAuth
- type ClientConfig
- type Handler
- type NetrcProvider
- type RoundTripper
- type ServerConfig
- type ThrottleConfig
- type ThrottledError
Constants ¶
const ( DefaultThrottleMaxFailures = 10 DefaultThrottleWindow = 5 * time.Minute DefaultThrottleLockout = 5 * time.Minute )
Defaults applied to ThrottleConfig fields left at their zero value.
Variables ¶
var ErrMalformedLine = errors.New("malformed basic auth line")
ErrMalformedLine is returned by LoadBasicAuthFromFile for a line that is not blank, not a "#" comment, and not of the form "user:hash" with both parts non-empty.
var ErrThrottled = errors.New("too many failed login attempts")
ErrThrottled is returned by Handler.AuthRequest when the client address has made too many failed login attempts. Use errors.As with *ThrottledError to obtain the retry delay.
Functions ¶
func AddCredentials ¶
AddCredentials fills in the user's credentials for req, if any. The return value reports whether any matching credentials were found. This function uses the default package-level NetrcProvider for backward compatibility.
func AddCredentialsWithProvider ¶
func AddCredentialsWithProvider(req *http.Request, provider *NetrcProvider) (added bool)
AddCredentialsWithProvider fills in the user's credentials for req using the specified provider. The return value reports whether any matching credentials were found.
Types ¶
type AuthMap ¶
type AuthMap map[string]BasicAuthPair
AuthMap is a user and password pair.
func LoadBasicAuthFromFile ¶
LoadBasicAuthFromFile reads an htpasswd-style file at filePath into an AuthMap. The file must be readable only by its owner (mode 0600 or 0400).
func LoadBasicAuthFromFileOrEmpty ¶ added in v0.9.0
LoadBasicAuthFromFileOrEmpty behaves like LoadBasicAuthFromFile, except a missing file returns an empty AuthMap and a nil error instead of the underlying os.Open error. Other errors (bad permissions, unreadable file) are returned unchanged. Useful for callers that treat "no credentials file yet" as a valid, empty starting state rather than a failure.
func LoadBasicAuthFromReader ¶
LoadBasicAuthFromReader reads htpasswd-style "user:hash" lines from reader into an AuthMap. Blank lines and "#" comments are ignored; malformed lines are skipped. Use LoadBasicAuthFromFile to have them reported instead.
func LoadBasicAuthFromScanner ¶
LoadBasicAuthFromScanner reads htpasswd-style "user:hash" lines from scanner into an AuthMap. Blank lines and "#" comments are ignored; malformed lines are skipped.
func (AuthMap) AddUserWithHashedPassword ¶
AddUserWithHashedPassword if user already exists it will over ride it.
func (AuthMap) AddUserWithPlainPassword ¶
AddUserWithPlainPassword if user already exists it will over ride it.
func (AuthMap) Authenticate ¶
Authenticate returns true if the user exists and the password is correct.
func (AuthMap) UserExists ¶
UserExists returns true if the user exists.
type BasicAuthPair ¶
BasicAuthPair holds a username and its bcrypt-hashed password.
func NewBasicAuthPairWithPlainPassword ¶
func NewBasicAuthPairWithPlainPassword(user, password string) (BasicAuthPair, error)
NewBasicAuthPairWithPlainPassword hashes password and returns a BasicAuthPair for user.
func (BasicAuthPair) VerifyPassword ¶
func (p BasicAuthPair) VerifyPassword(password string) (bool, error)
VerifyPassword reports whether password matches p's stored hash.
type ClientAuth ¶
type ClientAuth struct {
Config ClientConfig
// contains filtered or unexported fields
}
ClientAuth adds HTTP Basic credentials to outgoing requests, resolving them from Config or, failing that, a netrc file.
func (*ClientAuth) AddAuth ¶
func (a *ClientAuth) AddAuth(req *http.Request) error
AddAuth sets the Basic auth header on req, resolving credentials from a.Config.User/Password or, if unset, the matching netrc entry for req's host.
func (*ClientAuth) HTTPClient ¶
func (a *ClientAuth) HTTPClient() *http.Client
HTTPClient returns an *http.Client that authenticates every request with a's credentials.
type ClientConfig ¶
type ClientConfig struct {
// https://everything.curl.dev/usingcurl/netrc
//
// machine connect.lab.dioad.net
// login blah
// password blah
NetRCFile string `mapstructure:"netrc-file"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
}
ClientConfig configures HTTP Basic credentials for an outgoing client, either directly (User/Password) or via a netrc file.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler implements basic authentication for HTTP servers. The credential map can be replaced at any time via SetAuthMap, safely concurrent with in-flight AuthRequest calls - Handler does not need to be rebuilt to pick up new or changed credentials.
func NewHandler ¶
func NewHandler(cfg ServerConfig) (*Handler, error)
NewHandler creates a new Basic authentication handler from the provided configuration.
func NewHandlerWithMap ¶
func NewHandlerWithMap(cfg ServerConfig, authMap AuthMap) (*Handler, error)
NewHandlerWithMap creates a new Basic authentication handler using the provided AuthMap and configuration (for Realm, used in the WWW-Authenticate challenge header). Call h.SetAuthMap later to replace the credentials the returned Handler authenticates against, e.g. after a credentials file changes on disk.
func (*Handler) AuthMap ¶ added in v0.9.0
AuthMap returns the credentials Handler currently authenticates against. Safe to call concurrently with SetAuthMap and AuthRequest.
func (*Handler) AuthRequest ¶
AuthRequest authenticates an HTTP request using Basic authentication.
Unless disabled in ServerConfig.Throttle, a client address that exceeds the failed-login limit is rejected with a *ThrottledError (matching ErrThrottled) until its lockout expires, even if it then supplies the right password. A request without credentials counts as neither a failure nor a success.
func (*Handler) SetAuthMap ¶ added in v0.9.0
SetAuthMap atomically replaces the credentials Handler authenticates against. Safe to call concurrently with in-flight AuthRequest calls.
type NetrcProvider ¶
type NetrcProvider struct {
// contains filtered or unexported fields
}
NetrcProvider manages netrc credentials and their loading. It encapsulates the state for loading and parsing netrc files, allowing for multiple independent instances with different configurations. This resolves the global state issue that made testing difficult.
func NewNetrcProviderFromContent ¶
func NewNetrcProviderFromContent(content string) *NetrcProvider
NewNetrcProviderFromContent creates a NetrcProvider initialized with the given netrc content. This is useful for testing or when netrc data comes from a non-standard source.
type RoundTripper ¶
type RoundTripper struct {
Username string
Password string
Base http.RoundTripper
}
RoundTripper adds HTTP Basic credentials to every request before delegating to Base (or http.DefaultTransport if Base is nil).
type ServerConfig ¶
type ServerConfig struct {
AllowInsecureHTTP bool `mapstructure:"allow-insecure-http"`
HTPasswdFile string `mapstructure:"htpasswd-file"`
Users []string `mapstructure:"users"`
Realm string `mapstructure:"realm"`
// Throttle limits failed logins per client address. It is enabled by
// default; see ThrottleConfig for the limits.
Throttle ThrottleConfig `mapstructure:"throttle"`
}
ServerConfig configures HTTP Basic authentication for a server.
type ThrottleConfig ¶ added in v0.14.0
type ThrottleConfig struct {
// Disabled turns failed-login throttling off. By default throttling is on.
Disabled bool `mapstructure:"disabled"`
// MaxFailures is the number of rejected logins allowed within Window
// before the client address is locked out. Defaults to 10.
MaxFailures int `mapstructure:"max-failures"`
// Window is how long a failed login counts towards MaxFailures. Defaults
// to 5 minutes.
Window time.Duration `mapstructure:"window"`
// Lockout is how long a client address is rejected with 429 once
// MaxFailures is reached, even if it then supplies the right password.
// Defaults to 5 minutes.
Lockout time.Duration `mapstructure:"lockout"`
}
ThrottleConfig limits failed logins per client address to slow down password guessing. Throttling is enabled unless Disabled is set.
type ThrottledError ¶ added in v0.14.0
ThrottledError carries how long a locked-out client must wait to retry.
func (*ThrottledError) Error ¶ added in v0.14.0
func (e *ThrottledError) Error() string
Error implements error.
func (*ThrottledError) Is ¶ added in v0.14.0
func (e *ThrottledError) Is(target error) bool
Is reports whether target is ErrThrottled.