auth

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

framework/auth/apikey.go

framework/auth/auth.go

framework/auth/base_provider.go

framework/auth/database.go

framework/auth/errors.go

framework/auth/manager.go

auth/oauth2_provider.go

auth/token_store.go

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidCredentials indicates credentials are invalid
	ErrInvalidCredentials = errors.New("invalid credentials")

	// ErrResourceNotFound indicates the requested resource doesn't exist
	ErrResourceNotFound = errors.New("resource not found")

	// ErrProviderNotFound indicates the auth provider doesn't exist
	ErrProviderNotFound = errors.New("auth provider not found")

	// ErrTokenExpired indicates the auth token has expired
	ErrTokenExpired = errors.New("token expired")

	// ErrRefreshFailed indicates credential refresh failed
	ErrRefreshFailed = errors.New("credential refresh failed")

	// ErrValidationFailed indicates credential validation failed
	ErrValidationFailed = errors.New("validation failed")
)

Functions

func GenerateKey

func GenerateKey() (string, error)

GenerateKey generates a random encryption key

func GetDefaultScopes

func GetDefaultScopes(providerName string) []string

GetDefaultScopes returns default scopes for a provider

func NewAuthError

func NewAuthError(provider, resource, op string, err error) error

NewAuthError creates a new AuthError

Types

type APIKeyConfig

type APIKeyConfig struct {
	APIKey string `yaml:"api_key" json:"api_key"`
	Header string `yaml:"header" json:"header"` // Optional custom header name
}

APIKeyConfig holds API key provider configuration

type APIKeyProvider

type APIKeyProvider struct {
	*BaseProvider
	// contains filtered or unexported fields
}

APIKeyProvider authenticates using API keys

func NewAPIKeyProvider

func NewAPIKeyProvider(name string, config APIKeyConfig) *APIKeyProvider

NewAPIKeyProvider creates a new API key provider

func (*APIKeyProvider) GetResource

func (p *APIKeyProvider) GetResource(ctx context.Context, resourceID string) (Resource, error)

GetResource returns an authenticated HTTP client

func (*APIKeyProvider) Validate

func (p *APIKeyProvider) Validate(ctx context.Context) error

Validate checks if the API key is set

type APIKeyResource

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

APIKeyResource wraps an HTTP client

func (*APIKeyResource) BaseURL

func (r *APIKeyResource) BaseURL() string

BaseURL returns the base URL for the API

func (*APIKeyResource) Client

func (r *APIKeyResource) Client() *http.Client

Client returns the HTTP client for making requests

func (*APIKeyResource) Close

func (r *APIKeyResource) Close() error

func (*APIKeyResource) Type

func (r *APIKeyResource) Type() string

type AuthError

type AuthError struct {
	Provider string
	Resource string
	Op       string // Operation that failed
	Err      error  // Underlying error
}

AuthError wraps errors with additional context

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type AuthProvider

type AuthProvider interface {
	// GetResource returns an authenticated resource
	// resourceID identifies which resource to access (e.g., "main-db", "payment-api")
	GetResource(ctx context.Context, resourceID string) (Resource, error)

	// Validate checks if credentials are valid without fetching a resource
	Validate(ctx context.Context) error

	// Refresh refreshes credentials (useful for tokens that expire)
	Refresh(ctx context.Context) error

	// Close cleans up any resources held by the provider
	Close() error

	// Name returns the provider name for logging/debugging
	Name() string
}

AuthProvider manages authentication to external resources Each provider handles a specific auth method (API key, OAuth, DB, etc.)

type BaseProvider

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

BaseProvider provides common functionality for auth providers

func NewBaseProvider

func NewBaseProvider(name string) *BaseProvider

NewBaseProvider creates a new base provider

func (*BaseProvider) Close

func (p *BaseProvider) Close() error

Close is a no-op base implementation

func (*BaseProvider) GetResourceConfig

func (p *BaseProvider) GetResourceConfig(resourceID string) (ResourceConfig, error)

GetResourceConfig retrieves a resource configuration

func (*BaseProvider) ListResources

func (p *BaseProvider) ListResources() []string

ListResources returns all registered resource IDs

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

Name returns the provider name

func (*BaseProvider) Refresh

func (p *BaseProvider) Refresh(ctx context.Context) error

Refresh is a no-op base implementation

func (*BaseProvider) RegisterResource

func (p *BaseProvider) RegisterResource(config ResourceConfig)

RegisterResource registers a resource configuration

func (*BaseProvider) Validate

func (p *BaseProvider) Validate(ctx context.Context) error

Validate is a no-op base implementation

type CredentialStore

type CredentialStore interface {
	// Store saves credentials securely
	Store(ctx context.Context, key string, creds *Credentials) error

	// Retrieve gets credentials
	Retrieve(ctx context.Context, key string) (*Credentials, error)

	// Delete removes credentials
	Delete(ctx context.Context, key string) error

	// Close cleans up the store
	Close() error
}

CredentialStore securely stores and retrieves credentials

type Credentials

type Credentials struct {
	// Username or API key
	Username string

	// Password or secret
	Password string

	// Token for token-based auth
	Token string

	// Token expiry time
	ExpiresAt time.Time

	// Additional metadata
	Metadata map[string]string
}

Credentials holds authentication credentials IMPORTANT: This should never be logged or serialized to disk in plaintext

type DatabaseConfig

type DatabaseConfig struct {
	Driver   string `yaml:"driver" json:"driver"` // postgres, mysql, sqlite
	Host     string `yaml:"host" json:"host"`
	Port     int    `yaml:"port" json:"port"`
	Database string `yaml:"database" json:"database"`
	Username string `yaml:"username" json:"username"`
	Password string `yaml:"password" json:"password"`

	// Connection pool settings
	MaxOpenConns    int           `yaml:"max_open_conns" json:"max_open_conns"`
	MaxIdleConns    int           `yaml:"max_idle_conns" json:"max_idle_conns"`
	ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" json:"conn_max_lifetime"`
}

DatabaseConfig holds database provider configuration

type DatabaseProvider

type DatabaseProvider struct {
	*BaseProvider
	// contains filtered or unexported fields
}

DatabaseProvider authenticates to databases

func NewDatabaseProvider

func NewDatabaseProvider(name string) *DatabaseProvider

NewDatabaseProvider creates a new database provider

func (*DatabaseProvider) Close

func (p *DatabaseProvider) Close() error

Close closes all database connections

func (*DatabaseProvider) GetResource

func (p *DatabaseProvider) GetResource(ctx context.Context, resourceID string) (Resource, error)

GetResource returns a database connection

func (*DatabaseProvider) Validate

func (p *DatabaseProvider) Validate(ctx context.Context) error

Validate checks if we can connect to the database

type DatabaseResource

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

DatabaseResource wraps a database connection

func (*DatabaseResource) Close

func (r *DatabaseResource) Close() error

func (*DatabaseResource) DB

func (r *DatabaseResource) DB() *sql.DB

DB returns the sql.DB instance

func (*DatabaseResource) Type

func (r *DatabaseResource) Type() string

type FileTokenStore

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

FileTokenStore stores tokens in encrypted files

func NewFileTokenStore

func NewFileTokenStore(baseDir, encryptionKey string) (*FileTokenStore, error)

NewFileTokenStore creates a new file-based token store

func (*FileTokenStore) Close

func (s *FileTokenStore) Close() error

Close closes the token store

func (*FileTokenStore) Delete

func (s *FileTokenStore) Delete(ctx context.Context, providerName string) error

Delete deletes a token

func (*FileTokenStore) Load

func (s *FileTokenStore) Load(ctx context.Context, providerName string) (*OAuth2Token, error)

Load loads a token from disk (decrypted)

func (*FileTokenStore) Save

func (s *FileTokenStore) Save(ctx context.Context, providerName string, token *OAuth2Token) error

Save saves a token to disk (encrypted)

type Manager

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

Manager manages multiple auth providers

func NewManager

func NewManager() *Manager

NewManager creates a new auth manager

func (*Manager) Close

func (m *Manager) Close() error

Close closes all providers

func (*Manager) Get

func (m *Manager) Get(name string) (AuthProvider, error)

Get retrieves a registered provider by name

func (*Manager) GetResource

func (m *Manager) GetResource(ctx context.Context, providerName, resourceID string) (Resource, error)

GetResource gets a resource from a specific provider

func (*Manager) List

func (m *Manager) List() []string

List returns names of all registered providers

func (*Manager) Register

func (m *Manager) Register(name string, provider AuthProvider) error

Register registers an auth provider with a unique name

func (*Manager) ValidateAll

func (m *Manager) ValidateAll(ctx context.Context) error

ValidateAll validates all registered providers

type MemoryTokenStore

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

MemoryTokenStore stores tokens in memory (for testing)

func NewMemoryTokenStore

func NewMemoryTokenStore() *MemoryTokenStore

NewMemoryTokenStore creates a new memory token store

func (*MemoryTokenStore) Close

func (s *MemoryTokenStore) Close() error

func (*MemoryTokenStore) Delete

func (s *MemoryTokenStore) Delete(ctx context.Context, providerName string) error

func (*MemoryTokenStore) Load

func (s *MemoryTokenStore) Load(ctx context.Context, providerName string) (*OAuth2Token, error)

func (*MemoryTokenStore) Save

func (s *MemoryTokenStore) Save(ctx context.Context, providerName string, token *OAuth2Token) error

type OAuth2Config

type OAuth2Config struct {
	ClientID     string   `yaml:"client_id" json:"client_id"`
	ClientSecret string   `yaml:"client_secret" json:"client_secret"`
	RedirectURL  string   `yaml:"redirect_url" json:"redirect_url"`
	Scopes       []string `yaml:"scopes" json:"scopes"`
	AuthURL      string   `yaml:"auth_url" json:"auth_url"`
	TokenURL     string   `yaml:"token_url" json:"token_url"`
}

OAuth2Config holds OAuth2 provider configuration

type OAuth2Provider

type OAuth2Provider struct {
	*BaseProvider
	// contains filtered or unexported fields
}

OAuth2Provider manages OAuth2 authentication

func NewOAuth2Provider

func NewOAuth2Provider(name string, config OAuth2Config, tokenStore TokenStore) *OAuth2Provider

NewOAuth2Provider creates a new OAuth2 provider

func (*OAuth2Provider) Close

func (p *OAuth2Provider) Close() error

Close closes the provider

func (*OAuth2Provider) Exchange

func (p *OAuth2Provider) Exchange(ctx context.Context, code string) error

Exchange exchanges an authorization code for a token

func (*OAuth2Provider) GetAuthURL

func (p *OAuth2Provider) GetAuthURL(state string) string

GetAuthURL returns the OAuth2 authorization URL

func (*OAuth2Provider) GetResource

func (p *OAuth2Provider) GetResource(ctx context.Context, resourceID string) (Resource, error)

GetResource returns an authenticated HTTP client

func (*OAuth2Provider) Refresh

func (p *OAuth2Provider) Refresh(ctx context.Context) error

Refresh refreshes the OAuth2 token

func (*OAuth2Provider) SetToken

func (p *OAuth2Provider) SetToken(ctx context.Context, token *OAuth2Token) error

SetToken sets the OAuth2 token

func (*OAuth2Provider) Validate

func (p *OAuth2Provider) Validate(ctx context.Context) error

Validate checks if we have valid credentials

type OAuth2Resource

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

OAuth2Resource wraps an OAuth2 HTTP client

func (*OAuth2Resource) BaseURL

func (r *OAuth2Resource) BaseURL() string

BaseURL returns the base URL

func (*OAuth2Resource) Client

func (r *OAuth2Resource) Client() *http.Client

Client returns the HTTP client

func (*OAuth2Resource) Close

func (r *OAuth2Resource) Close() error

func (*OAuth2Resource) Type

func (r *OAuth2Resource) Type() string

type OAuth2Token

type OAuth2Token struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	TokenType    string    `json:"token_type"`
	ExpiresAt    time.Time `json:"expires_at"`
}

OAuth2Token represents an OAuth2 token

type ProviderConfig

type ProviderConfig struct {
	// Provider type (e.g., "database", "api-key", "oauth2")
	Type string `yaml:"type" json:"type"`

	// Configuration specific to the provider type
	Config map[string]interface{} `yaml:"config" json:"config"`

	// Resources managed by this provider
	Resources map[string]ResourceConfig `yaml:"resources" json:"resources"`
}

ProviderConfig holds configuration for an auth provider

type ProviderFactory

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

ProviderFactory creates OAuth2 providers for popular services

func NewProviderFactory

func NewProviderFactory(tokenStore TokenStore) *ProviderFactory

NewProviderFactory creates a new provider factory

func (*ProviderFactory) Create

func (f *ProviderFactory) Create(providerName, clientID, clientSecret, redirectURL string, scopes []string) (*OAuth2Provider, error)

Create creates an OAuth2 provider for a service

type Resource

type Resource interface {
	// Close releases the resource
	Close() error

	// Type returns the resource type (e.g., "database", "api", "file")
	Type() string
}

Resource represents an authenticated connection to a resource This could be a database connection, HTTP client, file handle, etc.

type ResourceConfig

type ResourceConfig struct {
	// Resource identifier
	ID string `yaml:"id" json:"id"`

	// Resource type (database, api, file, etc.)
	Type string `yaml:"type" json:"type"`

	// Resource-specific configuration
	Config map[string]interface{} `yaml:"config" json:"config"`
}

ResourceConfig describes a single resource

type TokenStore

type TokenStore interface {
	Save(ctx context.Context, providerName string, token *OAuth2Token) error
	Load(ctx context.Context, providerName string) (*OAuth2Token, error)
	Delete(ctx context.Context, providerName string) error
	Close() error
}

TokenStore manages OAuth2 tokens

Jump to

Keyboard shortcuts

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