Documentation
¶
Overview ¶
Package mfa provides multi-factor authentication functionality.
Index ¶
- Variables
- type Algorithm
- type CredentialInfo
- type CredentialManager
- func (m *CredentialManager) AddCredential(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
- func (m *CredentialManager) DeleteCredential(ctx context.Context, userID uuid.UUID, credID string) error
- func (m *CredentialManager) GetCredential(ctx context.Context, userID uuid.UUID, credID string) (*CredentialInfo, error)
- func (m *CredentialManager) GetRawCredentials(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
- func (m *CredentialManager) ListCredentials(ctx context.Context, userID uuid.UUID) ([]CredentialInfo, error)
- func (m *CredentialManager) UpdateCredentialName(ctx context.Context, userID uuid.UUID, credID, name string) error
- func (m *CredentialManager) UpdateLastUsed(ctx context.Context, userID uuid.UUID, credID []byte) error
- type CredentialManagerConfig
- type CredentialStore
- type DeleteCredentialRequest
- type Digits
- type DisableRequest
- type Handler
- func (h *Handler) Disable(c echo.Context) error
- func (h *Handler) GetRecoveryCodes(c echo.Context) error
- func (h *Handler) RegenerateRecoveryCodes(c echo.Context) error
- func (h *Handler) RegisterRoutes(g *echo.Group)
- func (h *Handler) Setup(c echo.Context) error
- func (h *Handler) Status(c echo.Context) error
- func (h *Handler) ValidateMFA(c echo.Context) error
- func (h *Handler) Verify(c echo.Context) error
- func (h *Handler) WebAuthnDeleteCredential(c echo.Context) error
- func (h *Handler) WebAuthnRegisterBegin(c echo.Context) error
- func (h *Handler) WebAuthnRegisterFinish(c echo.Context) error
- func (h *Handler) WebAuthnStatus(c echo.Context) error
- type InMemoryCredentialStore
- func (s *InMemoryCredentialStore) Count(ctx context.Context, userID uuid.UUID) (int, error)
- func (s *InMemoryCredentialStore) Create(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
- func (s *InMemoryCredentialStore) Delete(ctx context.Context, userID uuid.UUID, credID []byte) error
- func (s *InMemoryCredentialStore) GetByID(ctx context.Context, userID uuid.UUID, credID []byte) (*WebAuthnCredential, error)
- func (s *InMemoryCredentialStore) GetByUser(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
- func (s *InMemoryCredentialStore) Update(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
- type Key
- type ListCredentialsResponse
- type LoginSession
- type Recovery
- func (r *Recovery) FormatCodesForDisplay(codes []string) []string
- func (r *Recovery) Generate() (*RecoveryCodes, error)
- func (r *Recovery) GetConfig() *RecoveryConfig
- func (r *Recovery) RemainingCodes(usedCodes []bool) int
- func (r *Recovery) Validate(code string, hashedCodes []string, usedCodes []bool) (int, error)
- func (r *Recovery) ValidateAndMark(code string, hashedCodes []string, usedCodes []bool) ([]bool, error)
- type RecoveryCodes
- type RecoveryCodesResponse
- type RecoveryConfig
- type RegistrationSession
- type SetupResponse
- type SetupResponseDTO
- type StatusResponse
- type TOTP
- func (t *TOTP) GenerateCode(secret string) (string, error)
- func (t *TOTP) GenerateKey(accountName string) (*Key, error)
- func (t *TOTP) GenerateSecret() (string, error)
- func (t *TOTP) GetConfig() *TOTPConfig
- func (t *TOTP) GetProvisioningURI(accountName, secret string) string
- func (t *TOTP) Setup(accountName string) (*SetupResponse, error)
- func (t *TOTP) Validate(code, secret string) bool
- func (t *TOTP) ValidateWithSkew(code, secret string) bool
- type TOTPConfig
- type UpdateCredentialRequest
- type ValidateMFARequest
- type VerifyRequest
- type VerifyResponse
- type WebAuthn
- func (w *WebAuthn) BeginDiscoverableLogin() (*protocol.CredentialAssertion, *LoginSession, error)
- func (w *WebAuthn) BeginLogin(user *WebAuthnUser) (*protocol.CredentialAssertion, *LoginSession, error)
- func (w *WebAuthn) BeginRegistration(user *WebAuthnUser) (*protocol.CredentialCreation, *RegistrationSession, error)
- func (w *WebAuthn) FinishLogin(user *WebAuthnUser, session *LoginSession, ...) (*WebAuthnCredential, error)
- func (w *WebAuthn) FinishRegistration(user *WebAuthnUser, session *RegistrationSession, ...) (*WebAuthnCredential, error)
- func (w *WebAuthn) GetConfig() *WebAuthnConfig
- type WebAuthnConfig
- type WebAuthnCredential
- type WebAuthnCredentialDTO
- type WebAuthnRegisterBeginRequest
- type WebAuthnStatusResponse
- type WebAuthnUser
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCredentialExists is returned when a credential with the same ID already exists. ErrCredentialExists = errors.New("credential already exists") // ErrMaxCredentialsReached is returned when the maximum number of credentials is reached. ErrMaxCredentialsReached = errors.New("maximum credentials reached") )
var ( // ErrInvalidRecoveryCode is returned when a recovery code is invalid. ErrInvalidRecoveryCode = errors.New("invalid recovery code") // ErrRecoveryCodeUsed is returned when a recovery code has already been used. ErrRecoveryCodeUsed = errors.New("recovery code already used") // ErrNoRecoveryCodesLeft is returned when all recovery codes have been used. ErrNoRecoveryCodesLeft = errors.New("no recovery codes left") )
var ( // ErrInvalidCode is returned when the TOTP code is invalid. ErrInvalidCode = errors.New("invalid TOTP code") // ErrSecretTooShort is returned when the secret is too short. ErrSecretTooShort = errors.New("secret is too short") )
var ( // ErrWebAuthnNotConfigured is returned when WebAuthn is not configured. ErrWebAuthnNotConfigured = errors.New("webauthn not configured") // ErrCredentialNotFound is returned when a credential is not found. ErrCredentialNotFound = errors.New("credential not found") // ErrInvalidChallenge is returned when the challenge is invalid. ErrInvalidChallenge = errors.New("invalid challenge") )
Functions ¶
This section is empty.
Types ¶
type Algorithm ¶
type Algorithm int
Algorithm represents the hashing function used for OTP generation.
type CredentialInfo ¶
type CredentialInfo struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt time.Time `json:"last_used_at"`
}
CredentialInfo represents public information about a credential.
type CredentialManager ¶
type CredentialManager struct {
// contains filtered or unexported fields
}
CredentialManager manages WebAuthn credentials.
func NewCredentialManager ¶
func NewCredentialManager(store CredentialStore, config *CredentialManagerConfig) *CredentialManager
NewCredentialManager creates a new credential manager.
func (*CredentialManager) AddCredential ¶
func (m *CredentialManager) AddCredential(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
AddCredential adds a new credential for a user.
func (*CredentialManager) DeleteCredential ¶
func (m *CredentialManager) DeleteCredential(ctx context.Context, userID uuid.UUID, credID string) error
DeleteCredential deletes a credential.
func (*CredentialManager) GetCredential ¶
func (m *CredentialManager) GetCredential(ctx context.Context, userID uuid.UUID, credID string) (*CredentialInfo, error)
GetCredential retrieves a credential by ID.
func (*CredentialManager) GetRawCredentials ¶
func (m *CredentialManager) GetRawCredentials(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
GetRawCredentials returns all raw WebAuthn credentials for a user. This is used internally for WebAuthn ceremonies.
func (*CredentialManager) ListCredentials ¶
func (m *CredentialManager) ListCredentials(ctx context.Context, userID uuid.UUID) ([]CredentialInfo, error)
ListCredentials returns all credentials for a user.
func (*CredentialManager) UpdateCredentialName ¶
func (m *CredentialManager) UpdateCredentialName(ctx context.Context, userID uuid.UUID, credID, name string) error
UpdateCredentialName updates the name of a credential.
func (*CredentialManager) UpdateLastUsed ¶
func (m *CredentialManager) UpdateLastUsed(ctx context.Context, userID uuid.UUID, credID []byte) error
UpdateLastUsed updates the last used time of a credential.
type CredentialManagerConfig ¶
type CredentialManagerConfig struct {
// MaxCredentialsPerUser is the maximum number of credentials per user.
MaxCredentialsPerUser int
}
CredentialManagerConfig holds configuration for the credential manager.
func DefaultCredentialManagerConfig ¶
func DefaultCredentialManagerConfig() *CredentialManagerConfig
DefaultCredentialManagerConfig returns the default configuration.
type CredentialStore ¶
type CredentialStore interface {
// Create creates a new credential.
Create(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
// GetByUser retrieves all credentials for a user.
GetByUser(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
// GetByID retrieves a credential by ID.
GetByID(ctx context.Context, userID uuid.UUID, credID []byte) (*WebAuthnCredential, error)
// Update updates a credential.
Update(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
// Delete deletes a credential.
Delete(ctx context.Context, userID uuid.UUID, credID []byte) error
// Count returns the number of credentials for a user.
Count(ctx context.Context, userID uuid.UUID) (int, error)
}
CredentialStore defines the interface for storing WebAuthn credentials.
type DeleteCredentialRequest ¶
type DeleteCredentialRequest struct {
Password string `json:"password" validate:"required"`
}
DeleteCredentialRequest represents a request to delete a credential.
type Digits ¶
type Digits int
Digits represents the number of digits in a TOTP code.
type DisableRequest ¶
type DisableRequest struct {
Code string `json:"code"`
Password string `json:"password" validate:"required"`
}
DisableRequest represents a request to disable MFA.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for MFA operations.
func NewHandler ¶
NewHandler creates a new MFA handler.
func NewHandlerWithWebAuthn ¶
func NewHandlerWithWebAuthn(totp *TOTP, recovery *Recovery, webauthnConfig *WebAuthnConfig, credStore CredentialStore) *Handler
NewHandlerWithWebAuthn creates a new MFA handler with custom WebAuthn configuration.
func (*Handler) GetRecoveryCodes ¶
GetRecoveryCodes handles getting recovery codes.
func (*Handler) RegenerateRecoveryCodes ¶
RegenerateRecoveryCodes handles regenerating recovery codes.
func (*Handler) RegisterRoutes ¶
RegisterRoutes registers the MFA routes.
func (*Handler) ValidateMFA ¶
ValidateMFA validates MFA code during login. This would be called after initial password authentication.
func (*Handler) WebAuthnDeleteCredential ¶
WebAuthnDeleteCredential deletes a WebAuthn credential.
func (*Handler) WebAuthnRegisterBegin ¶
WebAuthnRegisterBegin starts the WebAuthn registration ceremony.
func (*Handler) WebAuthnRegisterFinish ¶
WebAuthnRegisterFinish completes the WebAuthn registration ceremony.
type InMemoryCredentialStore ¶
type InMemoryCredentialStore struct {
// contains filtered or unexported fields
}
InMemoryCredentialStore is an in-memory implementation of CredentialStore.
func NewInMemoryCredentialStore ¶
func NewInMemoryCredentialStore() *InMemoryCredentialStore
NewInMemoryCredentialStore creates a new in-memory credential store.
func (*InMemoryCredentialStore) Create ¶
func (s *InMemoryCredentialStore) Create(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
Create creates a new credential.
func (*InMemoryCredentialStore) Delete ¶
func (s *InMemoryCredentialStore) Delete(ctx context.Context, userID uuid.UUID, credID []byte) error
Delete deletes a credential.
func (*InMemoryCredentialStore) GetByID ¶
func (s *InMemoryCredentialStore) GetByID(ctx context.Context, userID uuid.UUID, credID []byte) (*WebAuthnCredential, error)
GetByID retrieves a credential by ID.
func (*InMemoryCredentialStore) GetByUser ¶
func (s *InMemoryCredentialStore) GetByUser(ctx context.Context, userID uuid.UUID) ([]WebAuthnCredential, error)
GetByUser retrieves all credentials for a user.
func (*InMemoryCredentialStore) Update ¶
func (s *InMemoryCredentialStore) Update(ctx context.Context, userID uuid.UUID, cred *WebAuthnCredential) error
Update updates a credential.
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key contains the provisioning data for a TOTP account.
func (*Key) AccountName ¶
type ListCredentialsResponse ¶
type ListCredentialsResponse struct {
Credentials []CredentialInfo `json:"credentials"`
Count int `json:"count"`
MaxAllowed int `json:"max_allowed"`
}
ListCredentialsResponse represents the response for listing credentials.
type LoginSession ¶
type LoginSession struct {
UserID uuid.UUID `json:"user_id"`
Challenge string `json:"challenge"`
ExpiresAt time.Time `json:"expires_at"`
// SessionData is the serialized webauthn.SessionData
SessionData []byte `json:"session_data"`
}
LoginSession holds the state for a login ceremony.
type Recovery ¶
type Recovery struct {
// contains filtered or unexported fields
}
Recovery provides recovery code generation and validation.
func NewRecovery ¶
func NewRecovery(config *RecoveryConfig) *Recovery
NewRecovery creates a new Recovery instance.
func (*Recovery) FormatCodesForDisplay ¶
FormatCodesForDisplay formats recovery codes for display to the user. Groups codes in pairs for easier reading.
func (*Recovery) Generate ¶
func (r *Recovery) Generate() (*RecoveryCodes, error)
Generate generates a new set of recovery codes.
func (*Recovery) GetConfig ¶
func (r *Recovery) GetConfig() *RecoveryConfig
GetConfig returns the current recovery configuration.
func (*Recovery) RemainingCodes ¶
RemainingCodes returns the number of unused recovery codes.
type RecoveryCodes ¶
type RecoveryCodes struct {
// Codes are the plaintext recovery codes (only available at generation time).
Codes []string `json:"codes,omitempty"`
// HashedCodes are the hashed recovery codes for storage.
HashedCodes []string `json:"-"`
// UsedCodes tracks which codes have been used (by index).
UsedCodes []bool `json:"-"`
}
RecoveryCodes represents a set of recovery codes.
type RecoveryCodesResponse ¶
type RecoveryCodesResponse struct {
Codes []string `json:"codes"`
Remaining int `json:"remaining"`
}
RecoveryCodesResponse represents the recovery codes response.
type RecoveryConfig ¶
type RecoveryConfig struct {
// Count is the number of recovery codes to generate.
Count int
// Length is the length of each recovery code (in characters).
Length int
}
RecoveryConfig holds recovery code configuration.
func DefaultRecoveryConfig ¶
func DefaultRecoveryConfig() *RecoveryConfig
DefaultRecoveryConfig returns the default recovery code configuration.
type RegistrationSession ¶
type RegistrationSession struct {
UserID uuid.UUID `json:"user_id"`
Challenge string `json:"challenge"`
ExpiresAt time.Time `json:"expires_at"`
// SessionData is the serialized webauthn.SessionData
SessionData []byte `json:"session_data"`
}
RegistrationSession holds the state for a registration ceremony.
type SetupResponse ¶
type SetupResponse struct {
// Secret is the TOTP secret (base32 encoded).
Secret string `json:"secret"`
// URI is the provisioning URI for authenticator apps.
URI string `json:"uri"`
}
SetupResponse contains the data needed for MFA setup.
type SetupResponseDTO ¶
SetupResponseDTO represents the response for MFA setup.
type StatusResponse ¶
type StatusResponse struct {
Enabled bool `json:"enabled"`
RecoveryCount int `json:"recovery_codes_remaining"`
SetupRequired bool `json:"setup_required,omitempty"`
}
StatusResponse represents the MFA status response.
type TOTP ¶
type TOTP struct {
// contains filtered or unexported fields
}
TOTP provides TOTP generation and validation.
func (*TOTP) GenerateCode ¶
GenerateCode generates a TOTP code for the current time.
func (*TOTP) GenerateKey ¶
GenerateKey generates a new TOTP key for a user.
func (*TOTP) GenerateSecret ¶
GenerateSecret generates a new TOTP secret.
func (*TOTP) GetConfig ¶
func (t *TOTP) GetConfig() *TOTPConfig
GetConfig returns the current TOTP configuration.
func (*TOTP) GetProvisioningURI ¶
GetProvisioningURI returns the provisioning URI for authenticator apps.
func (*TOTP) Setup ¶
func (t *TOTP) Setup(accountName string) (*SetupResponse, error)
Setup generates the provisioning secret and URI for MFA setup.
func (*TOTP) ValidateWithSkew ¶
ValidateWithSkew validates a TOTP code with clock skew tolerance.
type TOTPConfig ¶
type TOTPConfig struct {
// Issuer is the name shown in authenticator apps.
Issuer string
// Algorithm is the hash algorithm (SHA1, SHA256, SHA512).
Algorithm Algorithm
// Digits is the number of digits in the code.
Digits Digits
// Period is the time step in seconds.
Period uint
// SecretSize is the size of the secret in bytes.
SecretSize uint
// Skew is the number of periods to allow for clock drift.
Skew uint
}
TOTPConfig holds TOTP configuration.
func DefaultTOTPConfig ¶
func DefaultTOTPConfig() *TOTPConfig
DefaultTOTPConfig returns the default TOTP configuration.
type UpdateCredentialRequest ¶
type UpdateCredentialRequest struct {
Name string `json:"name" validate:"required,min=1,max=100"`
}
UpdateCredentialRequest represents a request to update a credential.
type ValidateMFARequest ¶
type ValidateMFARequest struct {
MFAToken string `json:"mfa_token" validate:"required"`
Code string `json:"code"`
RecoveryCode string `json:"recovery_code"`
}
ValidateMFARequest represents a request to validate MFA during login.
type VerifyRequest ¶
type VerifyRequest struct {
Code string `json:"code" validate:"required"`
Secret string `json:"secret" validate:"required"`
}
VerifyRequest represents a request to verify MFA setup.
type VerifyResponse ¶
type VerifyResponse struct {
Enabled bool `json:"enabled"`
RecoveryCodes []string `json:"recovery_codes,omitempty"`
}
VerifyResponse represents the response for MFA verification.
type WebAuthn ¶
type WebAuthn struct {
// contains filtered or unexported fields
}
WebAuthn provides WebAuthn registration and authentication.
func NewWebAuthn ¶
func NewWebAuthn(config *WebAuthnConfig) (*WebAuthn, error)
NewWebAuthn creates a new WebAuthn instance.
func (*WebAuthn) BeginDiscoverableLogin ¶
func (w *WebAuthn) BeginDiscoverableLogin() (*protocol.CredentialAssertion, *LoginSession, error)
BeginDiscoverableLogin starts a discoverable (usernameless) login ceremony.
func (*WebAuthn) BeginLogin ¶
func (w *WebAuthn) BeginLogin(user *WebAuthnUser) (*protocol.CredentialAssertion, *LoginSession, error)
BeginLogin starts a WebAuthn login ceremony.
func (*WebAuthn) BeginRegistration ¶
func (w *WebAuthn) BeginRegistration(user *WebAuthnUser) (*protocol.CredentialCreation, *RegistrationSession, error)
BeginRegistration starts a WebAuthn registration ceremony.
func (*WebAuthn) FinishLogin ¶
func (w *WebAuthn) FinishLogin(user *WebAuthnUser, session *LoginSession, response *protocol.ParsedCredentialAssertionData) (*WebAuthnCredential, error)
FinishLogin completes a WebAuthn login ceremony.
func (*WebAuthn) FinishRegistration ¶
func (w *WebAuthn) FinishRegistration(user *WebAuthnUser, session *RegistrationSession, response *protocol.ParsedCredentialCreationData) (*WebAuthnCredential, error)
FinishRegistration completes a WebAuthn registration ceremony.
func (*WebAuthn) GetConfig ¶
func (w *WebAuthn) GetConfig() *WebAuthnConfig
GetConfig returns the current WebAuthn configuration.
type WebAuthnConfig ¶
type WebAuthnConfig struct {
// RPDisplayName is the display name of the relying party.
RPDisplayName string
// RPID is the relying party ID (usually the domain).
RPID string
// RPOrigins are the allowed origins.
RPOrigins []string
// Timeout is the timeout for ceremonies in milliseconds.
Timeout int
// AuthenticatorSelection specifies authenticator requirements.
AuthenticatorSelection *protocol.AuthenticatorSelection
// AttestationPreference specifies attestation conveyance preference.
AttestationPreference protocol.ConveyancePreference
}
WebAuthnConfig holds WebAuthn configuration.
func DefaultWebAuthnConfig ¶
func DefaultWebAuthnConfig() *WebAuthnConfig
DefaultWebAuthnConfig returns the default WebAuthn configuration.
type WebAuthnCredential ¶
type WebAuthnCredential struct {
ID []byte `json:"id"`
PublicKey []byte `json:"public_key"`
AttestationType string `json:"attestation_type"`
AAGUID []byte `json:"aaguid"`
SignCount uint32 `json:"sign_count"`
CloneWarning bool `json:"clone_warning"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
LastUsedAt time.Time `json:"last_used_at"`
}
WebAuthnCredential represents a stored WebAuthn credential.
func FromWebAuthnCredential ¶
func FromWebAuthnCredential(cred *webauthn.Credential, name string) *WebAuthnCredential
FromWebAuthnCredential creates a WebAuthnCredential from webauthn.Credential.
func (*WebAuthnCredential) ToWebAuthnCredential ¶
func (c *WebAuthnCredential) ToWebAuthnCredential() webauthn.Credential
ToWebAuthnCredential converts to webauthn.Credential.
type WebAuthnCredentialDTO ¶
type WebAuthnCredentialDTO struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"created_at"`
LastUsedAt string `json:"last_used_at"`
}
WebAuthnCredentialDTO represents a WebAuthn credential for API responses.
type WebAuthnRegisterBeginRequest ¶
type WebAuthnRegisterBeginRequest struct {
Name string `json:"name" validate:"required"`
}
WebAuthnRegisterBeginRequest represents a request to begin WebAuthn registration.
type WebAuthnStatusResponse ¶
type WebAuthnStatusResponse struct {
Enabled bool `json:"enabled"`
Credentials []WebAuthnCredentialDTO `json:"credentials"`
}
WebAuthnStatusResponse represents the WebAuthn status response.
type WebAuthnUser ¶
type WebAuthnUser struct {
ID uuid.UUID
Name string
DisplayName string
Credentials []WebAuthnCredential
}
WebAuthnUser represents a user for WebAuthn operations.
func (*WebAuthnUser) WebAuthnCredentials ¶
func (u *WebAuthnUser) WebAuthnCredentials() []webauthn.Credential
WebAuthnCredentials returns the user's credentials.
func (*WebAuthnUser) WebAuthnDisplayName ¶
func (u *WebAuthnUser) WebAuthnDisplayName() string
WebAuthnDisplayName returns the user's display name.
func (*WebAuthnUser) WebAuthnID ¶
func (u *WebAuthnUser) WebAuthnID() []byte
WebAuthnID returns the user's WebAuthn ID.
func (*WebAuthnUser) WebAuthnName ¶
func (u *WebAuthnUser) WebAuthnName() string
WebAuthnName returns the user's name.