Documentation
¶
Overview ¶
Package warden provides a client SDK for interacting with Warden API.
Index ¶
- Constants
- Variables
- type AllowListUser
- type Cache
- type Client
- func (c *Client) CheckUserInList(ctx context.Context, phone, mail string) bool
- func (c *Client) ClearCache()
- func (c *Client) Close()
- func (c *Client) GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)
- func (c *Client) GetUsers(ctx context.Context) ([]AllowListUser, error)
- func (c *Client) GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)
- func (c *Client) InvalidateCache()
- type Clock
- type Error
- type Logger
- type LoggerKitAdapter
- func (l *LoggerKitAdapter) Debug(msg string)
- func (l *LoggerKitAdapter) Debugf(format string, args ...interface{})
- func (l *LoggerKitAdapter) Error(msg string)
- func (l *LoggerKitAdapter) Errorf(format string, args ...interface{})
- func (l *LoggerKitAdapter) Info(msg string)
- func (l *LoggerKitAdapter) Infof(format string, args ...interface{})
- func (l *LoggerKitAdapter) Warn(msg string)
- func (l *LoggerKitAdapter) Warnf(format string, args ...interface{})
- type NoOpLogger
- func (n *NoOpLogger) Debug(msg string)
- func (n *NoOpLogger) Debugf(format string, args ...interface{})
- func (n *NoOpLogger) Error(msg string)
- func (n *NoOpLogger) Errorf(format string, args ...interface{})
- func (n *NoOpLogger) Info(msg string)
- func (n *NoOpLogger) Infof(format string, args ...interface{})
- func (n *NoOpLogger) Warn(msg string)
- func (n *NoOpLogger) Warnf(format string, args ...interface{})
- type Options
- func (o *Options) Validate() error
- func (o *Options) WithAPIKey(key string) *Options
- func (o *Options) WithBaseURL(url string) *Options
- func (o *Options) WithCacheInvalidationChannel(ch <-chan struct{}) *Options
- func (o *Options) WithCacheTTL(ttl time.Duration) *Options
- func (o *Options) WithClock(clock Clock) *Options
- func (o *Options) WithHMAC(keyID, secret string) *Options
- func (o *Options) WithLogger(logger Logger) *Options
- func (o *Options) WithMaxResponseBytes(n int64) *Options
- func (o *Options) WithRetry(retry *RetryOptions) *Options
- func (o *Options) WithTLSClientCert(cert tls.Certificate) *Options
- func (o *Options) WithTLSConfig(cfg *tls.Config) *Options
- func (o *Options) WithTimeout(timeout time.Duration) *Options
- func (o *Options) WithTransport(transport *http.Transport) *Options
- type PaginatedResponse
- type PaginationInfo
- type RetryOptions
Constants ¶
const ( ErrCodeInvalidConfig = "INVALID_CONFIG" ErrCodeRequestFailed = "REQUEST_FAILED" ErrCodeInvalidResponse = "INVALID_RESPONSE" ErrCodeNotFound = "NOT_FOUND" ErrCodeServerError = "SERVER_ERROR" )
Predefined error codes
const DefaultMaxResponseBytes int64 = 8 << 20
DefaultMaxResponseBytes is the default cap on response body size (8 MiB).
Variables ¶
var ErrResponseTooLarge = errors.New("warden: response exceeds size limit")
ErrResponseTooLarge is returned when a response exceeds MaxResponseBytes.
Functions ¶
This section is empty.
Types ¶
type AllowListUser ¶
type AllowListUser struct {
Phone string `json:"phone"` // User phone number
Mail string `json:"mail"` // User email address
UserID string `json:"user_id"` // User unique identifier (optional, auto-generated if not provided)
Status string `json:"status"` // User status (e.g., "active", "inactive", "suspended")
Scope []string `json:"scope"` // User permission scope (optional)
Role string `json:"role"` // User role (optional)
Name string `json:"name,omitempty"` // User display name (optional)
DingtalkUserID string `json:"dingtalk_userid,omitempty"` // DingTalk user ID for work notification (optional)
}
AllowListUser represents a user in the allow list.
func (*AllowListUser) IsActive ¶ added in v0.3.0
func (u *AllowListUser) IsActive() bool
IsActive checks if the user status is active.
Returns true if the user status is "active", false otherwise. This method is used to verify if a user is allowed to access the system.
func (*AllowListUser) IsValid ¶ added in v0.3.0
func (u *AllowListUser) IsValid() bool
IsValid checks if the user has a valid status for authentication.
Returns true if the user status is one of the valid statuses (currently only "active"). This method can be extended in the future to support other valid statuses if needed.
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides thread-safe caching for user list.
func (*Cache) Get ¶
func (c *Cache) Get() []AllowListUser
Get returns the cached user list if it's still valid, nil otherwise.
func (*Cache) Set ¶
func (c *Cache) Set(users []AllowListUser)
Set stores the user list in cache with expiration.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the Warden API client.
func (*Client) CheckUserInList ¶
CheckUserInList checks if a user (by phone or mail) is in the allow list and has active status. Returns false if the user is not found, has inactive/suspended status, or if there's an error. This method uses GetUserByIdentifier for better performance and includes status validation. If both phone and mail are provided, phone takes priority. If phone lookup fails with NotFound error, it will fall back to mail lookup.
func (*Client) Close ¶ added in v0.4.0
func (c *Client) Close()
Close stops the cache invalidation listener and releases resources. This should be called when the client is no longer needed.
func (*Client) GetUserByIdentifier ¶
func (c *Client) GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)
GetUserByIdentifier fetches a single user by phone, mail, or user_id. Only one identifier should be provided.
func (*Client) GetUsers ¶
func (c *Client) GetUsers(ctx context.Context) ([]AllowListUser, error)
GetUsers fetches the user list from Warden API. If pagination parameters are not provided, returns all users.
func (*Client) GetUsersPaginated ¶
func (c *Client) GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)
GetUsersPaginated fetches a paginated user list from Warden API.
func (*Client) InvalidateCache ¶ added in v0.4.0
func (c *Client) InvalidateCache()
InvalidateCache is an alias for ClearCache for consistency with event-driven invalidation.
type Clock ¶ added in v0.14.0
Clock abstracts time for deterministic testing of signature timestamps.
type Error ¶
type Error struct {
Code string // Error code
Message string // Error message
Err error // Original error (if any)
}
Error represents an error that occurred in the SDK.
type Logger ¶
type Logger interface {
Debug(msg string)
Debugf(format string, args ...interface{})
Info(msg string)
Infof(format string, args ...interface{})
Warn(msg string)
Warnf(format string, args ...interface{})
Error(msg string)
Errorf(format string, args ...interface{})
}
Logger defines the interface for logging operations. This allows the SDK to work with different logging libraries (e.g., logger-kit, zerolog, standard log). Use NewLoggerKitAdapter for logger-kit.
type LoggerKitAdapter ¶ added in v0.9.0
type LoggerKitAdapter struct {
// contains filtered or unexported fields
}
LoggerKitAdapter adapts logger-kit Logger to the SDK Logger interface.
func NewLoggerKitAdapter ¶ added in v0.9.0
func NewLoggerKitAdapter(l *loggerkit.Logger) *LoggerKitAdapter
NewLoggerKitAdapter creates a new LoggerKitAdapter.
func (*LoggerKitAdapter) Debug ¶ added in v0.9.0
func (l *LoggerKitAdapter) Debug(msg string)
Debug logs a debug message using logger-kit.
func (*LoggerKitAdapter) Debugf ¶ added in v0.9.0
func (l *LoggerKitAdapter) Debugf(format string, args ...interface{})
Debugf logs a formatted debug message using logger-kit.
func (*LoggerKitAdapter) Error ¶ added in v0.9.0
func (l *LoggerKitAdapter) Error(msg string)
Error logs an error message using logger-kit.
func (*LoggerKitAdapter) Errorf ¶ added in v0.9.0
func (l *LoggerKitAdapter) Errorf(format string, args ...interface{})
Errorf logs a formatted error message using logger-kit.
func (*LoggerKitAdapter) Info ¶ added in v0.9.0
func (l *LoggerKitAdapter) Info(msg string)
Info logs an info message using logger-kit.
func (*LoggerKitAdapter) Infof ¶ added in v0.9.0
func (l *LoggerKitAdapter) Infof(format string, args ...interface{})
Infof logs a formatted info message using logger-kit.
func (*LoggerKitAdapter) Warn ¶ added in v0.9.0
func (l *LoggerKitAdapter) Warn(msg string)
Warn logs a warning message using logger-kit.
func (*LoggerKitAdapter) Warnf ¶ added in v0.9.0
func (l *LoggerKitAdapter) Warnf(format string, args ...interface{})
Warnf logs a formatted warning message using logger-kit.
type NoOpLogger ¶
type NoOpLogger struct{}
NoOpLogger is a no-op implementation of Logger that discards all log messages. This is used as the default logger when no logger is provided.
func (*NoOpLogger) Debugf ¶
func (n *NoOpLogger) Debugf(format string, args ...interface{})
Debugf discards formatted debug messages.
func (*NoOpLogger) Errorf ¶
func (n *NoOpLogger) Errorf(format string, args ...interface{})
Errorf discards formatted error messages.
func (*NoOpLogger) Infof ¶
func (n *NoOpLogger) Infof(format string, args ...interface{})
Infof discards formatted info messages.
func (*NoOpLogger) Warnf ¶
func (n *NoOpLogger) Warnf(format string, args ...interface{})
Warnf discards formatted warning messages.
type Options ¶
type Options struct {
BaseURL string // Warden service address (required)
APIKey string // API Key (optional)
Timeout time.Duration // HTTP request timeout (default 10s)
CacheTTL time.Duration // Cache TTL (default 5 minutes)
Logger Logger // Logger interface (optional, defaults to NoOpLogger)
Transport *http.Transport // Custom HTTP transport (optional)
Retry *RetryOptions // Retry configuration (optional)
CacheInvalidationChannel <-chan struct{} // Channel for event-driven cache invalidation (optional)
// HMACKeyID and HMACSecret enable request signing (HMAC v2). When both are set,
// every request is signed. The secret is never logged.
HMACKeyID string
HMACSecret string
// Clock overrides the time source used for signature timestamps (testing).
Clock Clock
// TLSConfig, when set, is applied to the HTTP transport (e.g. client certs, root
// CAs). It takes precedence over Transport's own TLSClientConfig.
TLSConfig *tls.Config
// MaxResponseBytes bounds the response body read to defend against unbounded
// payloads. Zero means use DefaultMaxResponseBytes; a negative value disables it.
MaxResponseBytes int64
}
Options contains configuration options for the Warden SDK client.
func DefaultOptions ¶
func DefaultOptions() *Options
DefaultOptions returns default options with sensible defaults.
func (*Options) WithAPIKey ¶
WithAPIKey sets the API key for authentication.
func (*Options) WithBaseURL ¶
WithBaseURL sets the base URL for the Warden service.
func (*Options) WithCacheInvalidationChannel ¶ added in v0.4.0
WithCacheInvalidationChannel sets a channel for event-driven cache invalidation. When a signal is received on this channel, the cache will be automatically cleared.
func (*Options) WithCacheTTL ¶
WithCacheTTL sets the cache TTL.
func (*Options) WithClock ¶ added in v0.14.0
WithClock overrides the time source used for signature timestamps. Primarily useful for deterministic tests.
func (*Options) WithHMAC ¶ added in v0.14.0
WithHMAC enables HMAC v2 request signing with the given key id and secret. The secret is never logged. Passing two empty values disables signing; a partial key-id/secret pair is rejected by Validate.
func (*Options) WithLogger ¶
WithLogger sets the logger implementation.
func (*Options) WithMaxResponseBytes ¶ added in v0.14.0
WithMaxResponseBytes bounds how many bytes of a response body will be read. Zero uses DefaultMaxResponseBytes; a negative value disables the limit.
func (*Options) WithRetry ¶ added in v0.4.0
func (o *Options) WithRetry(retry *RetryOptions) *Options
WithRetry sets the retry configuration.
func (*Options) WithTLSClientCert ¶ added in v0.14.0
func (o *Options) WithTLSClientCert(cert tls.Certificate) *Options
WithTLSClientCert configures mutual TLS by presenting the given client certificate. It preserves any existing TLSConfig fields.
func (*Options) WithTLSConfig ¶ added in v0.14.0
WithTLSConfig sets a custom *tls.Config (e.g. client certificates, root CAs) that will be applied to the HTTP transport.
func (*Options) WithTimeout ¶
WithTimeout sets the HTTP request timeout.
type PaginatedResponse ¶
type PaginatedResponse struct {
Data []AllowListUser `json:"data"`
Pagination PaginationInfo `json:"pagination"`
}
PaginatedResponse represents a paginated response from the Warden API.
type PaginationInfo ¶
type PaginationInfo struct {
Page int `json:"page"` // Current page number (starts from 1)
PageSize int `json:"page_size"` // Page size
Total int `json:"total"` // Total number of records
TotalPages int `json:"total_pages"` // Total number of pages
}
PaginationInfo contains pagination metadata.
type RetryOptions ¶ added in v0.4.0
type RetryOptions struct {
RetryableStatusCodes []int // HTTP status codes that should trigger retry (default: 5xx)
MaxRetries int // Maximum number of retries (default 0, no retry)
RetryDelay time.Duration // Initial delay between retries (default 100ms)
MaxRetryDelay time.Duration // Maximum delay between retries (default 5s)
BackoffMultiplier float64 // Multiplier for exponential backoff (default 2.0)
}
RetryOptions contains configuration for request retry behavior.
func DefaultRetryOptions ¶ added in v0.4.0
func DefaultRetryOptions() *RetryOptions
DefaultRetryOptions returns default retry options with sensible defaults.