warden

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

README

Warden SDK

📖 Multi-language Documentation: For documentation in other languages, please refer to docs directory

Warden SDK is a Go client library for interacting with the Warden API. It provides simple and easy-to-use interfaces for fetching user lists, querying individual user information, checking if users are in the allow list, and supports caching for improved performance.

Features

  • 🚀 Simple and Easy: Provides clean API interfaces
  • ⚡ High Performance: Built-in cache support (GetUsers), direct queries (GetUserByIdentifier) reduce API calls
  • 🔒 Secure: Supports API keys, HMAC and TLS client certificates; internal diagnostic errors are redacted (returned errors retain details; see SDK diagnostic logging)
  • 📦 Flexible: Configurable timeout, cache TTL, etc.
  • 🔌 Extensible: Supports custom logger implementations
  • 🎯 Smart Fallback: CheckUserInList supports automatic fallback to mail when phone is not found

Installation

go get github.com/soulteary/warden/pkg/warden

Quick Start

Basic Usage
package main

import (
    "context"
    "fmt"
    "time"
    
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    // Create client options
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithAPIKey("your-api-key").
        WithTimeout(10 * time.Second).
        WithCacheTTL(5 * time.Minute)
    
    // Create client
    client, err := warden.NewClient(opts)
    if err != nil {
        panic(err)
    }
    
    // Get user list
    ctx := context.Background()
    users, err := client.GetUsers(ctx)
    if err != nil {
        panic(err)
    }
    
    // Check if user is in the list (can provide phone, mail, or both)
    exists := client.CheckUserInList(ctx, "13800138000", "user@example.com")
    if exists {
        println("User is in the allow list and active")
    }
    
    // Can also use only phone or mail
    existsByPhone := client.CheckUserInList(ctx, "13800138000", "")
    existsByMail := client.CheckUserInList(ctx, "", "user@example.com")
    
    // Get user details
    user, err := client.GetUserByIdentifier(ctx, "13800138000", "", "")
    if err != nil {
        panic(err)
    }
    fmt.Printf("User: %s, Status: %s\n", user.UserID, user.Status)
}
Using Custom Logger

The SDK supports custom logger implementations. For example, using logrus:

import (
    "github.com/sirupsen/logrus"
    "github.com/soulteary/warden/pkg/warden"
)

func main() {
    logger := logrus.StandardLogger()
    
    opts := warden.DefaultOptions().
        WithBaseURL("http://localhost:8081").
        WithLogger(warden.NewLogrusAdapter(logger))
    
    client, err := warden.NewClient(opts)
    // ...
}
Paginated Query
// Get paginated user list
resp, err := client.GetUsersPaginated(ctx, 1, 10) // Page 1, 10 items per page
if err != nil {
    panic(err)
}

fmt.Printf("Total users: %d\n", resp.Pagination.Total)
fmt.Printf("Total pages: %d\n", resp.Pagination.TotalPages)
for _, user := range resp.Data {
    fmt.Printf("UserID: %s, Phone: %s, Mail: %s, Status: %s\n", 
        user.UserID, user.Phone, user.Mail, user.Status)
}
Get Single User Information
// Get user information by phone
user, err := client.GetUserByIdentifier(ctx, "13800138000", "", "")
if err != nil {
    if sdkErr, ok := err.(*warden.Error); ok && sdkErr.Code == warden.ErrCodeNotFound {
        println("User not found")
    } else {
        panic(err)
    }
} else {
    fmt.Printf("UserID: %s, Phone: %s, Mail: %s, Status: %s\n", 
        user.UserID, user.Phone, user.Mail, user.Status)
    if user.IsActive() {
        println("User is active")
    }
}

// Get user information by email
user, err = client.GetUserByIdentifier(ctx, "", "user@example.com", "")

// Get user information by user ID
user, err = client.GetUserByIdentifier(ctx, "", "", "user123")
Clear Cache
// Clear client cache manually
client.ClearCache()

// Or use the alias
client.InvalidateCache()
Custom HTTP Transport
import "net/http"

// Create custom transport
customTransport := &http.Transport{
    MaxIdleConns: 100,
    IdleConnTimeout: 90 * time.Second,
}

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithTransport(customTransport)

client, err := warden.NewClient(opts)
Retry Configuration
// Configure retry options
retryOpts := warden.DefaultRetryOptions()
retryOpts.MaxRetries = 3
retryOpts.RetryDelay = 100 * time.Millisecond
retryOpts.MaxRetryDelay = 5 * time.Second
retryOpts.BackoffMultiplier = 2.0

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithRetry(retryOpts)

client, err := warden.NewClient(opts)
Event-Driven Cache Invalidation
// Create channel for cache invalidation events
invalidationCh := make(chan struct{}, 1)

opts := warden.DefaultOptions().
    WithBaseURL("http://localhost:8081").
    WithCacheInvalidationChannel(invalidationCh)

client, err := warden.NewClient(opts)
if err != nil {
    panic(err)
}
defer client.Close() // Important: close to stop background listener

// Later, trigger cache invalidation from external event
invalidationCh <- struct{}{}

// Cache will be automatically cleared when signal is received

API Reference

Options

The Options struct is used to configure the client:

  • BaseURL: Warden service address (required)
  • APIKey: API Key (optional)
  • Timeout: HTTP request timeout (default 10 seconds)
  • CacheTTL: Cache TTL (default 5 minutes)
  • Logger: Logger interface (optional, defaults to NoOpLogger)
  • Transport: Custom HTTP transport (optional)
  • Retry: Retry configuration (optional, defaults to no retry)
  • CacheInvalidationChannel: Channel for event-driven cache invalidation (optional)
Client Methods
NewClient(opts *Options) (*Client, error)

Creates a new Warden client.

GetUsers(ctx context.Context) ([]AllowListUser, error)

Gets all user list. If cache is valid, returns cached data directly.

GetUsersPaginated(ctx context.Context, page, pageSize int) (*PaginatedResponse, error)

Gets paginated user list.

  • page: Page number (starts from 1)
  • pageSize: Page size

Returns PaginatedResponse, containing:

  • Data: User list
  • Pagination: Pagination information (page number, page size, total, total pages)

Note: This method does not use cache, each call fetches the latest data from the API.

GetUserByIdentifier(ctx context.Context, phone, mail, userID string) (*AllowListUser, error)

Gets a single user information by identifier.

  • phone: User phone number (optional, but must provide one of phone, mail, or userID)
  • mail: User email (optional)
  • userID: User unique identifier (optional)

Important: Must provide exactly one identifier among phone, mail, or userID.

Returns *AllowListUser and error. If user does not exist, returns ErrCodeNotFound error.

Note: This method does not use cache, each call fetches the latest data from the API.

CheckUserInList(ctx context.Context, phone, mail string) bool

Checks if a user is in the allow list.

  • phone: User phone number (optional)
  • mail: User email (optional)

Returns true if the user exists (matched by phone or email), false otherwise.

Behavior:

  • If both phone and mail are provided, phone takes priority
  • If phone lookup fails (returns NotFound error) and mail is not empty, automatically falls back to mail lookup
  • If phone lookup succeeds but user status is not active, does not fall back to mail (user already found)
  • If phone lookup fails and error is not NotFound (e.g., network error), does not fall back to mail
  • Input is automatically normalized: phone is trimmed, mail is trimmed and converted to lowercase
  • This method uses GetUserByIdentifier for lookup, more efficient than iterating through user list
  • Only users with status "active" will return true
ClearCache()

Clears the internal client cache.

InvalidateCache()

Alias for ClearCache() for consistency with event-driven invalidation.

Close()

Stops background goroutines (e.g., cache invalidation listener) and releases resources. Should be called when the client is no longer needed.

Type Definitions

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)
}

Methods:

  • IsActive() bool: Checks if user status is "active"
  • IsValid() bool: Checks if user status is valid (currently only supports "active")
PaginatedResponse
type PaginatedResponse struct {
    Data       []AllowListUser `json:"data"`
    Pagination PaginationInfo  `json:"pagination"`
}

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
}

Error Handling

The SDK uses custom error types with error codes and detailed information:

if err != nil {
    if sdkErr, ok := err.(*warden.Error); ok {
        switch sdkErr.Code {
        case warden.ErrCodeUnauthorized:
            // Handle authentication error
        case warden.ErrCodeRequestFailed:
            // Handle request failure
        // ...
        }
    }
}
Error Codes
  • ErrCodeInvalidConfig: Invalid configuration
  • ErrCodeRequestFailed: Request failed
  • ErrCodeInvalidResponse: Invalid response format
  • ErrCodeUnauthorized: Unauthorized
  • ErrCodeNotFound: Not found
  • ErrCodeServerError: Server error

RetryOptions

The RetryOptions struct configures retry behavior:

  • MaxRetries: Maximum number of retries (default 0, no retry)
  • RetryDelay: Initial delay between retries (default 100ms)
  • MaxRetryDelay: Maximum delay between retries (default 5s)
  • BackoffMultiplier: Multiplier for exponential backoff (default 2.0)
  • RetryableStatusCodes: HTTP status codes that trigger retry (default: 500, 502, 503, 504)

Note: Retries require MaxRetries > 0 and remain bounded by the request context. Transport errors are eligible for retry, except redirect-policy errors (ErrRedirect). Client errors (4xx) are never retried, even if listed in RetryableStatusCodes.

Best Practices

  1. Reuse Client: Create the client once and reuse it throughout the application lifecycle
  2. Set Cache TTL Appropriately: Set appropriate cache time based on data update frequency
  3. Use Context: Pass context to support cancellation and timeout control
  4. Error Handling: Always check and handle errors
  5. Logging: Use appropriate logger implementation in production environments
  6. Close Client: Call Close() when the client is no longer needed to stop background goroutines
  7. Configure Retry: Enable retry for production environments to handle transient failures
  8. Custom Transport: Use custom transport for advanced scenarios (TLS, proxy, connection pooling, etc.)

Examples

For complete examples, please refer to the example directory.

License

Apache License 2.0

List cache invalidation during a request

ClearCache, InvalidateCache and invalidation-channel events fence list requests that started before the invalidation. Such a response is neither cached nor returned by GetUsers; the call returns REQUEST_FAILED wrapping ErrCacheInvalidated (detectable with errors.Is). The caller may start a new request. There is no automatic additional fetch. Cache TTL, optional source freshness and the normal request retry policy are unchanged.

Concurrent list responses

Within one client and invalidation epoch, a later-started request that successfully commits prevents earlier requests from publishing or returning their responses. Those calls return REQUEST_FAILED wrapping ErrCacheSuperseded. Starting a later request, or receiving an invalid or expired response, does not suppress an earlier valid response. Empty lists participate in the same ordering.

This is local request ordering, not a global source-version guarantee. Snapshot hashes and Redis revision tokens are not ordered, and sequential requests routed to different replicas may still observe different accepted datasets. No extra fetch, retry or change to default freshness settings is introduced.

Source errors from an enforcing server

With WithSourceFreshness enabled, a metadata-v1 server can classify a source refusal on HTTP 503. errors.Is(err, ErrSourceStale) identifies expiry; ErrSourceUnknown identifies unavailable age evidence, and ErrSourceFuture identifies future source time. These errors use SOURCE_FRESHNESS and retain the original server error in their chain. Plain or unrecognized 503 responses keep SERVER_ERROR. Default clients keep their existing mapping and cache behavior. The existing retry policy runs before classification, including configured 503 retries. See the configuration guide for paired server and SDK enablement.

Cache and source freshness contracts

Redirect policy

The SDK rejects HTTP redirects with ErrRedirect. This applies to all SDK calls and all credentials, including API keys, HMAC signing and client certificates. A redirect policy error is not retried. Set BaseURL to the final service URL; redirect response bodies are not returned or cached.

Credential selection

When HMAC signing is configured, the SDK sends only HMAC authentication headers. A simultaneously configured API key is omitted from both X-API-Key and Authorization. API-key-only clients continue to send both headers. This avoids exposing an additional reusable credential on signed requests; it does not change server authentication policies or TLS client certificate configuration.

SDK diagnostic logging

The SDK uses NoOpLogger by default. With a custom logger, internal request failure messages report SDK error categories and HTTP status codes without raw transport error text, response bodies or retry URLs. This prevents those error paths from exposing lookup identifiers or upstream response data in SDK logs. Returned errors retain their existing details and wrapping for caller compatibility; applications must apply their own logging policy to those errors. The Logger interface and adapter do not sanitize messages supplied by callers.

Documentation

Overview

Package warden provides a client SDK for interacting with Warden API.

Index

Constants

View Source
const (
	ErrCodeInvalidConfig   = "INVALID_CONFIG"
	ErrCodeRequestFailed   = "REQUEST_FAILED"
	ErrCodeInvalidResponse = "INVALID_RESPONSE"
	ErrCodeUnauthorized    = "UNAUTHORIZED"
	ErrCodeNotFound        = "NOT_FOUND"
	ErrCodeServerError     = "SERVER_ERROR"
	ErrCodeSourceFreshness = "SOURCE_FRESHNESS"
)

Predefined error codes

View Source
const (
	// HeaderSourceError classifies negotiated source refusals on HTTP 503 only.
	HeaderSourceError        = "Warden-Source-Error"
	HeaderSnapshotMetadata   = "Warden-Snapshot-Metadata"
	HeaderSnapshotVersion    = "Warden-Snapshot-Version"
	HeaderSourceSucceededAt  = "Warden-Source-Succeeded-At"
	HeaderSnapshotValidUntil = "Warden-Snapshot-Valid-Until"
)

Negotiated response metadata is separate from the compatibility JSON schema.

View Source
const DefaultMaxResponseBytes int64 = 8 << 20

DefaultMaxResponseBytes is the default cap on response body size (8 MiB).

Variables

View Source
var (
	ErrSourceUnknown = errors.New("warden: source freshness evidence unavailable or invalid")
	ErrSourceStale   = errors.New("warden: source freshness deadline reached")
	ErrSourceFuture  = errors.New("warden: source timestamp exceeds clock allowance")
)

Source freshness errors never include raw response headers or user records.

View Source
var ErrCacheInvalidated = errors.New("warden: cache invalidated during request")

ErrCacheInvalidated indicates that a list response crossed a cache invalidation. The response is neither returned nor cached; callers may issue a new request.

View Source
var ErrCacheSuperseded = errors.New("warden: list response superseded by a newer request")

ErrCacheSuperseded indicates a later-started list request already committed. The older response is neither returned nor cached.

View Source
var ErrRedirect = errors.New("warden: redirects are disabled")

ErrRedirect indicates a rejected service redirect. SDK credentials are bound to the configured service and are never forwarded to a redirect target.

View Source
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 NewCache

func NewCache(ttl time.Duration) *Cache

NewCache creates a new cache instance with the specified TTL.

func (*Cache) Clear

func (c *Cache) Clear()

Clear clears the cache for subsequent lookups. A hit captured before Clear may still finish copying and return its detached rows.

func (*Cache) Get

func (c *Cache) Get() []AllowListUser

Get returns the cached user list if it is valid when the view is captured. The returned rows and Scope slices belong to the caller.

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 NewClient

func NewClient(opts *Options) (*Client, error)

NewClient creates a new Warden API client with the provided options.

func (*Client) CheckUserInList

func (c *Client) CheckUserInList(ctx context.Context, phone, mail string) bool

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) ClearCache

func (c *Client) ClearCache()

ClearCache clears the internal cache.

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

type Clock interface {
	Now() time.Time
}

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.

func NewError

func NewError(code, message string, err error) *Error

NewError creates a new SDK error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

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) Debug

func (n *NoOpLogger) Debug(msg string)

Debug discards debug messages.

func (*NoOpLogger) Debugf

func (n *NoOpLogger) Debugf(format string, args ...interface{})

Debugf discards formatted debug messages.

func (*NoOpLogger) Error

func (n *NoOpLogger) Error(msg string)

Error discards error messages.

func (*NoOpLogger) Errorf

func (n *NoOpLogger) Errorf(format string, args ...interface{})

Errorf discards formatted error messages.

func (*NoOpLogger) Info

func (n *NoOpLogger) Info(msg string)

Info discards info messages.

func (*NoOpLogger) Infof

func (n *NoOpLogger) Infof(format string, args ...interface{})

Infof discards formatted info messages.

func (*NoOpLogger) Warn

func (n *NoOpLogger) Warn(msg string)

Warn discards warning 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 and enabled source freshness (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
	// SourceMaxAge enables negotiated source freshness when positive; zero keeps compatibility.
	SourceMaxAge time.Duration
	// SourceClockSkew is subtracted from the source deadline and bounds future timestamps.
	SourceClockSkew time.Duration
}

Options contains configuration options for the Warden SDK client.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default options with sensible defaults.

func (*Options) Validate

func (o *Options) Validate() error

Validate validates the options and returns an error if invalid.

func (*Options) WithAPIKey

func (o *Options) WithAPIKey(key string) *Options

WithAPIKey sets the API key for authentication.

func (*Options) WithBaseURL

func (o *Options) WithBaseURL(url string) *Options

WithBaseURL sets the base URL for the Warden service.

func (*Options) WithCacheInvalidationChannel added in v0.4.0

func (o *Options) WithCacheInvalidationChannel(ch <-chan struct{}) *Options

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

func (o *Options) WithCacheTTL(ttl time.Duration) *Options

WithCacheTTL sets the cache TTL.

func (*Options) WithClock added in v0.14.0

func (o *Options) WithClock(clock Clock) *Options

WithClock overrides the time source used for signature timestamps and enabled source freshness. Primarily useful for deterministic tests.

func (*Options) WithHMAC added in v0.14.0

func (o *Options) WithHMAC(keyID, secret string) *Options

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

func (o *Options) WithLogger(logger Logger) *Options

WithLogger sets the logger implementation.

func (*Options) WithMaxResponseBytes added in v0.14.0

func (o *Options) WithMaxResponseBytes(n int64) *Options

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) WithSourceFreshness added in v1.5.0

func (o *Options) WithSourceFreshness(maxAge, clockSkew time.Duration) *Options

WithSourceFreshness enables source-bounded reads and caching. Zero maxAge disables the constraint; clockSkew is a conservative allowance, not extra age.

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

func (o *Options) WithTLSConfig(cfg *tls.Config) *Options

WithTLSConfig sets a custom *tls.Config (e.g. client certificates, root CAs) that will be applied to the HTTP transport.

func (*Options) WithTimeout

func (o *Options) WithTimeout(timeout time.Duration) *Options

WithTimeout sets the HTTP request timeout.

func (*Options) WithTransport added in v0.4.0

func (o *Options) WithTransport(transport *http.Transport) *Options

WithTransport sets a custom HTTP transport.

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 eligible for retry, excluding 4xx (default: 500, 502, 503, 504)
	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.

Jump to

Keyboard shortcuts

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