auth

package
v0.0.0-...-9e5e0b2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAPIKeyNotFound  = errors.New("api key not found")
	ErrAPIKeyExpired   = errors.New("api key has expired")
	ErrAPIKeyRevoked   = errors.New("api key has been revoked")
	ErrUnauthorized    = errors.New("unauthorized")
	ErrRotationPending = errors.New("rotation already pending")
)
View Source
var (
	ErrInvalidCiphertext = errors.New("invalid ciphertext")
	ErrKeyNotConfigured  = errors.New("encryption key not configured")
)
View Source
var (
	ErrInvalidToken     = errors.New("invalid token")
	ErrExpiredToken     = errors.New("token has expired")
	ErrRevokedToken     = errors.New("token has been revoked")
	ErrInvalidTokenType = errors.New("invalid token type")
	ErrWeakSecret       = errors.New("JWT secret is too weak or uses default value")
)
View Source
var ErrInvalidDuration = echo.NewHTTPError(http.StatusBadRequest, "invalid duration format")

ErrInvalidDuration is returned when a duration string is invalid.

Functions

func GenerateKey

func GenerateKey() ([]byte, error)

GenerateKey generates a new random 32-byte encryption key.

func GenerateKeyBase64

func GenerateKeyBase64() (string, error)

GenerateKeyBase64 generates a new random encryption key and returns it as base64.

func GenerateSecureSecret

func GenerateSecureSecret() (string, error)

GenerateSecureSecret generates a cryptographically secure random secret. Security: Use this to generate a secure JWT secret if none is configured.

func ValidateJWTSecret

func ValidateJWTSecret(secret string) error

ValidateJWTSecret checks if the JWT secret is secure enough. Security: Returns an error if the secret is weak or uses a known default value.

Types

type APIKeyHandler

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

APIKeyHandler handles HTTP requests for API key management.

func NewAPIKeyHandler

func NewAPIKeyHandler(service *APIKeyService) *APIKeyHandler

NewAPIKeyHandler creates a new API key handler.

func (*APIKeyHandler) CreateKey

func (h *APIKeyHandler) CreateKey(c echo.Context) error

CreateKey creates a new API key.

func (*APIKeyHandler) DeleteKey

func (h *APIKeyHandler) DeleteKey(c echo.Context) error

DeleteKey deletes an API key.

func (*APIKeyHandler) ListKeys

func (h *APIKeyHandler) ListKeys(c echo.Context) error

ListKeys returns all API keys for the current user.

func (*APIKeyHandler) RegisterRoutes

func (h *APIKeyHandler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the API key routes.

func (*APIKeyHandler) RotateKey

func (h *APIKeyHandler) RotateKey(c echo.Context) error

RotateKey rotates an API key.

type APIKeyInfo

type APIKeyInfo struct {
	ID          string     `json:"id"`
	UserID      string     `json:"user_id"`
	Name        string     `json:"name"`
	Prefix      string     `json:"prefix"`
	Key         string     `json:"key,omitempty"`
	Scopes      []string   `json:"scopes"`
	CreatedAt   time.Time  `json:"created_at"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	LastUsed    *time.Time `json:"last_used,omitempty"`
	Revoked     bool       `json:"revoked"`
	RotatedFrom *string    `json:"rotated_from,omitempty"`
	RotatedTo   *string    `json:"rotated_to,omitempty"`
	RotatedAt   *time.Time `json:"rotated_at,omitempty"`
	GracePeriod *time.Time `json:"grace_period,omitempty"`
}

APIKeyInfo represents the information about an API key

func GetAPIKeyFromContext

func GetAPIKeyFromContext(c echo.Context) *APIKeyInfo

GetAPIKeyFromContext retrieves API key info from the echo context

func (*APIKeyInfo) HasScope

func (k *APIKeyInfo) HasScope(scope string) bool

HasScope checks if the API key has the specified scope

type APIKeyResponseDTO

type APIKeyResponseDTO struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	KeyPrefix  string     `json:"key_prefix"`
	Scopes     []string   `json:"scopes"`
	CreatedAt  time.Time  `json:"created_at"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
}

APIKeyResponseDTO represents an API key in responses.

type APIKeyService

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

APIKeyService handles API key operations

func NewAPIKeyService

func NewAPIKeyService(dbPath string, opts ...APIKeyServiceOption) (*APIKeyService, error)

NewAPIKeyService creates a new API key service with its own SQLite database.

func NewAPIKeyServiceWithDB

func NewAPIKeyServiceWithDB(db *sql.DB, opts ...APIKeyServiceOption) (*APIKeyService, error)

NewAPIKeyServiceWithDB creates an API key service using an existing shared database connection.

func NewAPIKeyServiceWithReadDB

func NewAPIKeyServiceWithReadDB(writeDB, readDB *sql.DB, opts ...APIKeyServiceOption) (*APIKeyService, error)

NewAPIKeyServiceWithReadDB creates an API key service using existing shared write/read database connections.

func (*APIKeyService) CleanupExpiredRotations

func (s *APIKeyService) CleanupExpiredRotations(ctx context.Context) (int64, error)

CleanupExpiredRotations revokes old keys that have passed their grace period

func (*APIKeyService) Close

func (s *APIKeyService) Close() error

Close closes the database connection if this service owns it.

func (*APIKeyService) CompleteRotation

func (s *APIKeyService) CompleteRotation(ctx context.Context, oldKeyID, userID string) error

CompleteRotation completes a rotation by revoking the old key

func (*APIKeyService) CreateKey

func (s *APIKeyService) CreateKey(ctx context.Context, req *CreateKeyRequest) (*APIKeyInfo, error)

CreateKey creates a new API key

func (*APIKeyService) GetDecryptedKey

func (s *APIKeyService) GetDecryptedKey(ctx context.Context, keyID, userID string) (string, error)

GetDecryptedKey retrieves and decrypts an API key by its ID.

func (*APIKeyService) GetRotationHistory

func (s *APIKeyService) GetRotationHistory(ctx context.Context, keyID, userID string) ([]*APIKeyInfo, error)

GetRotationHistory returns the rotation history for a key

func (*APIKeyService) ListKeys

func (s *APIKeyService) ListKeys(ctx context.Context, userID string) ([]*APIKeyInfo, error)

ListKeys lists all API keys for a user

func (*APIKeyService) ReEncryptAllKeys

func (s *APIKeyService) ReEncryptAllKeys(ctx context.Context, oldEnc, newEnc *Encryptor) (int64, error)

ReEncryptAllKeys re-encrypts all API keys with a new encryptor.

func (*APIKeyService) RevokeKey

func (s *APIKeyService) RevokeKey(ctx context.Context, id, userID string) error

RevokeKey revokes an API key

func (*APIKeyService) RotateKey

func (s *APIKeyService) RotateKey(ctx context.Context, req *RotateKeyRequest) (*RotateKeyResult, error)

RotateKey rotates an API key

func (*APIKeyService) ValidateKey

func (s *APIKeyService) ValidateKey(ctx context.Context, key string) (*APIKeyInfo, error)

ValidateKey validates an API key and returns its information

type APIKeyServiceOption

type APIKeyServiceOption func(*APIKeyService)

APIKeyServiceOption is a functional option for APIKeyService.

func WithEncryption

func WithEncryption(enc *Encryptor) APIKeyServiceOption

WithEncryption enables encryption for API key storage.

type AuthMiddleware

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

AuthMiddleware handles authentication for HTTP requests

func NewAuthMiddleware

func NewAuthMiddleware(jwtSvc *JWTService, apiKeySvc *APIKeyService) *AuthMiddleware

NewAuthMiddleware creates a new auth middleware

func (*AuthMiddleware) Authenticate

func (m *AuthMiddleware) Authenticate() echo.MiddlewareFunc

Authenticate returns a middleware that requires authentication

func (*AuthMiddleware) OptionalAuthenticate

func (m *AuthMiddleware) OptionalAuthenticate() echo.MiddlewareFunc

OptionalAuthenticate returns a middleware that optionally authenticates

func (*AuthMiddleware) RequireScope

func (m *AuthMiddleware) RequireScope(scope string) echo.MiddlewareFunc

RequireScope returns a middleware that requires a specific scope

func (*AuthMiddleware) SetPreviewModeChecker

func (m *AuthMiddleware) SetPreviewModeChecker(checker interface {
	IsPreviewMode(context.Context) (bool, error)
})

SetPreviewModeChecker configures preview mode verification for preview JWTs. When set, tokens for the synthetic preview user are rejected once preview mode is off.

type Claims

type Claims struct {
	jwt.RegisteredClaims
	UserClaims
	TokenType TokenType `json:"token_type"`
}

Claims represents the full JWT claims

type ContextKey

type ContextKey string

ContextKey is the type for context keys

const (
	// UserContextKey is the key for storing user claims in context
	UserContextKey ContextKey = "user"
	// APIKeyContextKey is the key for storing API key info in context
	APIKeyContextKey ContextKey = "apikey"
)

type CreateKeyRequest

type CreateKeyRequest struct {
	UserID    string
	Name      string
	Scopes    []string
	ExpiresAt time.Time
}

CreateKeyRequest represents a request to create an API key

type CreateKeyRequestDTO

type CreateKeyRequestDTO struct {
	Name      string   `json:"name" validate:"required"`
	Scopes    []string `json:"scopes" validate:"required"`
	ExpiresIn string   `json:"expires_in,omitempty"` // e.g., "7d", "30d", "90d", "365d", ""
}

CreateKeyRequest represents a request to create an API key.

type CreateKeyResponseDTO

type CreateKeyResponseDTO struct {
	APIKey *APIKeyResponseDTO `json:"api_key"`
	Key    string             `json:"key"` // Full key, only shown once
}

CreateKeyResponse represents the response after creating an API key.

type EncryptionConfig

type EncryptionConfig struct {
	// Key is the master encryption key (32 bytes for AES-256).
	// Can be set directly or derived from a passphrase.
	Key []byte

	// KeyPath is the path to a file containing the encryption key.
	KeyPath string

	// Passphrase is used to derive the encryption key using PBKDF2.
	Passphrase string

	// Salt is used with the passphrase for key derivation.
	// If not provided, a default salt is used (not recommended for production).
	Salt []byte
}

EncryptionConfig holds configuration for API key encryption.

type Encryptor

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

Encryptor handles encryption and decryption of sensitive data.

func NewEncryptor

func NewEncryptor(cfg *EncryptionConfig) (*Encryptor, error)

NewEncryptor creates a new Encryptor with the given configuration.

func (*Encryptor) Decrypt

func (e *Encryptor) Decrypt(ciphertext string) ([]byte, error)

Decrypt decrypts ciphertext that was encrypted with Encrypt.

func (*Encryptor) DecryptString

func (e *Encryptor) DecryptString(ciphertext string) (string, error)

DecryptString decrypts a string that was encrypted with EncryptString.

func (*Encryptor) Encrypt

func (e *Encryptor) Encrypt(plaintext []byte) (string, error)

Encrypt encrypts plaintext using AES-256-GCM.

func (*Encryptor) EncryptString

func (e *Encryptor) EncryptString(plaintext string) (string, error)

EncryptString encrypts a string and returns the encrypted string.

func (*Encryptor) RotateKey

func (e *Encryptor) RotateKey(newKey []byte) error

RotateKey rotates the encryption key. This should be called when re-encrypting data.

type JWTConfig

type JWTConfig struct {
	Secret            string        `yaml:"secret"`
	Expiration        time.Duration `yaml:"expiration"`
	RefreshExpiration time.Duration `yaml:"refresh_expiration"`
	Issuer            string        `yaml:"issuer"`
}

JWTConfig holds JWT configuration

type JWTService

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

JWTService handles JWT operations

func NewJWTService

func NewJWTService(cfg *JWTConfig) *JWTService

NewJWTService creates a new JWT service. Security: This will log a warning if the secret appears weak.

func NewJWTServiceSecure

func NewJWTServiceSecure(cfg *JWTConfig) (*JWTService, error)

NewJWTServiceSecure creates a new JWT service with security validation. Security: Returns an error if the secret is weak or uses a known default value. Use this in production to ensure secure configuration.

func (*JWTService) GenerateAccessToken

func (s *JWTService) GenerateAccessToken(userClaims *UserClaims) (string, error)

GenerateAccessToken generates a new access token

func (*JWTService) GenerateRefreshToken

func (s *JWTService) GenerateRefreshToken(userClaims *UserClaims) (string, error)

GenerateRefreshToken generates a new refresh token

func (*JWTService) IsSecretSecure

func (s *JWTService) IsSecretSecure() bool

IsSecretSecure checks if the current secret is secure.

func (*JWTService) RefreshTokens

func (s *JWTService) RefreshTokens(refreshToken string) (string, string, error)

RefreshTokens validates a refresh token and generates new access and refresh tokens

func (*JWTService) RevokeToken

func (s *JWTService) RevokeToken(tokenString string) error

RevokeToken adds a token to the blacklist

func (*JWTService) ValidateToken

func (s *JWTService) ValidateToken(tokenString string) (*Claims, error)

ValidateToken validates a JWT token and returns the claims

type RotateKeyRequest

type RotateKeyRequest struct {
	KeyID       string
	UserID      string
	GracePeriod time.Duration
}

RotateKeyRequest represents a request to rotate an API key

type RotateKeyResult

type RotateKeyResult struct {
	OldKey *APIKeyInfo `json:"old_key"`
	NewKey *APIKeyInfo `json:"new_key"`
}

RotateKeyResult contains the result of a key rotation

type TokenType

type TokenType string

TokenType represents the type of JWT token

const (
	TokenTypeAccess  TokenType = "access"
	TokenTypeRefresh TokenType = "refresh"
)

type UserClaims

type UserClaims struct {
	UserID   string `json:"user_id"`
	Username string `json:"username"`
	Role     string `json:"role"`
}

UserClaims represents the custom claims in JWT

func GetUserFromContext

func GetUserFromContext(c echo.Context) *UserClaims

GetUserFromContext retrieves user claims from the echo context

Jump to

Keyboard shortcuts

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