Documentation ¶
Overview ¶
Package idptoken provides a robust way to request access tokens from IDP. Provider is to be used for a single token source. MultiSourceProvider to be used for multiple token sources.
Index ¶
- Constants
- Variables
- type Config
- type DefaultIntrospectionResult
- type GRPCClient
- type GRPCClientOpts
- type InMemoryTokenCache
- type IntrospectionCache
- type IntrospectionCacheItem
- type IntrospectionEndpointDiscoveryCache
- type IntrospectionEndpointDiscoveryCacheItem
- type IntrospectionLRUCache
- func (a *IntrospectionLRUCache[K, V]) Add(_ context.Context, key K, val V)
- func (a *IntrospectionLRUCache[K, V]) Get(_ context.Context, key K) (V, bool)
- func (a *IntrospectionLRUCache[K, V]) Len(ctx context.Context) int
- func (a *IntrospectionLRUCache[K, V]) Purge(ctx context.Context)
- func (a *IntrospectionLRUCache[K, V]) Remove(_ context.Context, key K) bool
- type IntrospectionResult
- type IntrospectionTokenProvider
- type Introspector
- type IntrospectorCacheOpts
- type IntrospectorOpts
- type MultiSourceProvider
- func (p *MultiSourceProvider) GetToken(ctx context.Context, clientID, sourceURL string, scope ...string) (string, error)
- func (p *MultiSourceProvider) GetTokenWithHeaders(ctx context.Context, clientID, sourceURL string, headers map[string]string, ...) (string, error)
- func (p *MultiSourceProvider) Invalidate()
- func (p *MultiSourceProvider) RefreshTokensPeriodically(ctx context.Context)
- func (p *MultiSourceProvider) RegisterSource(source Source)
- type Provider
- func (mp *Provider) GetToken(ctx context.Context, scope ...string) (string, error)
- func (mp *Provider) GetTokenWithHeaders(ctx context.Context, headers map[string]string, scope ...string) (string, error)
- func (mp *Provider) Invalidate()
- func (mp *Provider) RefreshTokensPeriodically(ctx context.Context)
- type ProviderOpts
- type Source
- type TokenCache
- type TokenData
- type TokenDetails
- type TrustedIssNotFoundFallback
- type UnexpectedIDPResponseError
Constants ¶
const ( // DefaultIntrospectionClaimsCacheMaxEntries is a default maximum number of entries in the claims cache. // Claims cache is used for storing introspected active tokens. DefaultIntrospectionClaimsCacheMaxEntries = 1000 // DefaultIntrospectionClaimsCacheTTL is a default time-to-live for the claims cache. DefaultIntrospectionClaimsCacheTTL = 1 * time.Minute // DefaultIntrospectionNegativeCacheMaxEntries is a default maximum number of entries in the negative cache. // Negative cache is used for storing tokens that are not active. DefaultIntrospectionNegativeCacheMaxEntries = 1000 // DefaultIntrospectionNegativeCacheTTL is a default time-to-live for the negative cache. DefaultIntrospectionNegativeCacheTTL = 1 * time.Hour // DefaultIntrospectionEndpointDiscoveryCacheMaxEntries is a default maximum number of entries in the endpoint discovery cache. DefaultIntrospectionEndpointDiscoveryCacheMaxEntries = 1000 // DefaultIntrospectionEndpointDiscoveryCacheTTL is a default time-to-live for the endpoint discovery cache. DefaultIntrospectionEndpointDiscoveryCacheTTL = 1 * time.Hour )
const DefaultGRPCClientRequestTimeout = time.Second * 30
DefaultGRPCClientRequestTimeout is a default timeout for the gRPC requests.
Variables ¶
var ErrSourceNotRegistered = errors.New("cannot issue token for unknown source")
ErrSourceNotRegistered is returned if GetToken is requested for the unknown Source
var ErrTokenIntrospectionNotNeeded = errors.New("token introspection is not needed")
ErrTokenIntrospectionNotNeeded is returned when token introspection is unnecessary (i.e., it already contains all necessary information).
var ErrTokenNotIntrospectable = errors.New("token is not introspectable")
ErrTokenNotIntrospectable is returned when token is not introspectable.
var ErrUnauthenticated = errors.New("request is unauthenticated")
ErrUnauthenticated is returned when a request is unauthenticated.
Functions ¶
This section is empty.
Types ¶
type Config ¶
Config is a configuration for IDP token source.
func NewConfig ¶
func NewConfig() *Config
NewConfig creates a new configuration for IDP token source.
func (*Config) Set ¶
func (c *Config) Set(dp config.DataProvider) (err error)
Set sets the configuration from the given data provider.
func (*Config) SetProviderDefaults ¶
func (c *Config) SetProviderDefaults(_ config.DataProvider)
SetProviderDefaults sets the default values for the configuration.
type DefaultIntrospectionResult ¶ added in v0.10.0
type DefaultIntrospectionResult struct { Active bool `json:"active"` TokenType string `json:"token_type,omitempty"` jwt.DefaultClaims }
DefaultIntrospectionResult is a default implementation of IntrospectionResult.
func (*DefaultIntrospectionResult) Clone ¶ added in v0.10.0
func (ir *DefaultIntrospectionResult) Clone() IntrospectionResult
Clone returns a deep copy of the introspection result.
func (*DefaultIntrospectionResult) GetClaims ¶ added in v0.10.0
func (ir *DefaultIntrospectionResult) GetClaims() jwt.Claims
GetClaims returns the claims of the token.
func (*DefaultIntrospectionResult) GetTokenType ¶ added in v0.10.0
func (ir *DefaultIntrospectionResult) GetTokenType() string
GetTokenType returns the token type.
func (*DefaultIntrospectionResult) IsActive ¶ added in v0.10.0
func (ir *DefaultIntrospectionResult) IsActive() bool
IsActive returns true if the token is active.
type GRPCClient ¶
type GRPCClient struct {
// contains filtered or unexported fields
}
GRPCClient is a client for the IDP token service that uses gRPC.
func NewGRPCClient ¶
func NewGRPCClient( target string, transportCreds credentials.TransportCredentials, ) (*GRPCClient, error)
NewGRPCClient creates a new GRPCClient instance that communicates with the IDP token service.
func NewGRPCClientWithOpts ¶
func NewGRPCClientWithOpts( target string, transportCreds credentials.TransportCredentials, opts GRPCClientOpts, ) (*GRPCClient, error)
NewGRPCClientWithOpts creates a new GRPCClient instance that communicates with the IDP token service with the specified options.
func (*GRPCClient) Close ¶
func (c *GRPCClient) Close() error
Close closes the client gRPC connection.
func (*GRPCClient) ExchangeToken ¶ added in v0.5.0
func (c *GRPCClient) ExchangeToken(ctx context.Context, token string, tokenVersion uint32) (TokenData, error)
ExchangeToken exchanges the token requesting a new token with the specified version.
func (*GRPCClient) IntrospectToken ¶
func (c *GRPCClient) IntrospectToken( ctx context.Context, token string, scopeFilter jwt.ScopeFilter, accessToken string, ) (IntrospectionResult, error)
IntrospectToken introspects the token using the IDP token service.
type GRPCClientOpts ¶
type GRPCClientOpts struct { // LoggerProvider is a function that provides a logger for the client. LoggerProvider func(ctx context.Context) log.FieldLogger // RequestTimeout is a timeout for the gRPC requests. RequestTimeout time.Duration // UserAgent is a user agent string for the client. UserAgent string // PrometheusLibInstanceLabel is a label for Prometheus metrics. // It allows distinguishing metrics from different instances of the same library. PrometheusLibInstanceLabel string }
GRPCClientOpts contains options for the GRPCClient.
type InMemoryTokenCache ¶
type InMemoryTokenCache struct {
// contains filtered or unexported fields
}
func NewInMemoryTokenCache ¶
func NewInMemoryTokenCache() *InMemoryTokenCache
func (*InMemoryTokenCache) ClearAll ¶
func (c *InMemoryTokenCache) ClearAll()
func (*InMemoryTokenCache) Delete ¶
func (c *InMemoryTokenCache) Delete(key string)
func (*InMemoryTokenCache) Get ¶
func (c *InMemoryTokenCache) Get(key string) *TokenDetails
func (*InMemoryTokenCache) Keys ¶
func (c *InMemoryTokenCache) Keys() []string
func (*InMemoryTokenCache) Put ¶
func (c *InMemoryTokenCache) Put(key string, val *TokenDetails)
type IntrospectionCache ¶ added in v0.10.0
type IntrospectionCache interface { Get(ctx context.Context, key [sha256.Size]byte) (IntrospectionCacheItem, bool) Add(ctx context.Context, key [sha256.Size]byte, value IntrospectionCacheItem) Remove(ctx context.Context, key [sha256.Size]byte) bool Purge(ctx context.Context) Len(ctx context.Context) int }
IntrospectionCache is an interface that must be implemented by used cache implementations. The cache is used for storing results of access token introspection.
type IntrospectionCacheItem ¶ added in v0.10.0
type IntrospectionCacheItem struct { IntrospectionResult IntrospectionResult CreatedAt time.Time }
type IntrospectionEndpointDiscoveryCache ¶ added in v0.8.0
type IntrospectionEndpointDiscoveryCache interface { Get(ctx context.Context, key [sha256.Size]byte) (IntrospectionEndpointDiscoveryCacheItem, bool) Add(ctx context.Context, key [sha256.Size]byte, value IntrospectionEndpointDiscoveryCacheItem) Purge(ctx context.Context) Len(ctx context.Context) int }
IntrospectionEndpointDiscoveryCache is an interface that must be implemented by used endpoint discovery cache implementations.
type IntrospectionEndpointDiscoveryCacheItem ¶ added in v0.8.0
type IntrospectionEndpointDiscoveryCacheItem struct { // IntrospectionEndpoint is an introspection endpoint URL. IntrospectionEndpoint string // CreatedAt is a time when the item was created in the cache. CreatedAt time.Time }
IntrospectionEndpointDiscoveryCacheItem is an item in the introspection endpoint discovery cache.
type IntrospectionLRUCache ¶ added in v0.5.0
type IntrospectionLRUCache[K comparable, V any] struct { // contains filtered or unexported fields }
func (*IntrospectionLRUCache[K, V]) Add ¶ added in v0.5.0
func (a *IntrospectionLRUCache[K, V]) Add(_ context.Context, key K, val V)
func (*IntrospectionLRUCache[K, V]) Get ¶ added in v0.5.0
func (a *IntrospectionLRUCache[K, V]) Get(_ context.Context, key K) (V, bool)
func (*IntrospectionLRUCache[K, V]) Len ¶ added in v0.5.0
func (a *IntrospectionLRUCache[K, V]) Len(ctx context.Context) int
func (*IntrospectionLRUCache[K, V]) Purge ¶ added in v0.5.0
func (a *IntrospectionLRUCache[K, V]) Purge(ctx context.Context)
type IntrospectionResult ¶
type IntrospectionResult interface { IsActive() bool GetTokenType() string GetClaims() jwt.Claims Clone() IntrospectionResult }
IntrospectionResult is an interface that must be implemented by introspection result implementations. By default, DefaultIntrospectionResult is used.
type IntrospectionTokenProvider ¶
type IntrospectionTokenProvider interface { GetToken(ctx context.Context, scope ...string) (string, error) Invalidate() }
IntrospectionTokenProvider is an interface for getting access token for doing introspection. The token should have introspection permission.
type Introspector ¶
type Introspector struct { // GRPCClient is a client for doing gRPC requests. // If it is set, then introspection will be done via gRPC. // Otherwise, introspection will be done via HTTP. GRPCClient *GRPCClient // HTTPClient is an HTTP client for doing requests. HTTPClient *http.Client // ClaimsCache is a cache for storing claims of introspected active tokens. ClaimsCache IntrospectionCache // NegativeCache is a cache for storing info about tokens that are not active. NegativeCache IntrospectionCache // EndpointDiscoveryCache is a cache for storing OpenID configuration. EndpointDiscoveryCache IntrospectionEndpointDiscoveryCache // contains filtered or unexported fields }
Introspector is a struct for introspecting tokens.
func NewIntrospector ¶
func NewIntrospector(tokenProvider IntrospectionTokenProvider) (*Introspector, error)
NewIntrospector creates a new Introspector with the given token provider.
func NewIntrospectorWithOpts ¶
func NewIntrospectorWithOpts(accessTokenProvider IntrospectionTokenProvider, opts IntrospectorOpts) (*Introspector, error)
NewIntrospectorWithOpts creates a new Introspector with the given token provider and options. See IntrospectorOpts for more details.
func (*Introspector) AddTrustedIssuer ¶
func (i *Introspector) AddTrustedIssuer(issName, issURL string)
AddTrustedIssuer adds trusted issuer with specified name and URL.
func (*Introspector) AddTrustedIssuerURL ¶
func (i *Introspector) AddTrustedIssuerURL(issURL string) error
AddTrustedIssuerURL adds trusted issuer URL.
func (*Introspector) IntrospectToken ¶
func (i *Introspector) IntrospectToken(ctx context.Context, token string) (IntrospectionResult, error)
IntrospectToken introspects the given token.
type IntrospectorCacheOpts ¶ added in v0.5.0
IntrospectorCacheOpts is a configuration of how cache will be used.
type IntrospectorOpts ¶
type IntrospectorOpts struct { // GRPCClient is a gRPC client for doing introspection. // If it is set, then introspection will be done using this client. // Otherwise, introspection will be done via HTTP. GRPCClient *GRPCClient // HTTPEndpoint is a static URL for introspection. // If it is set, then introspection will be done using this endpoint. // Otherwise, introspection will be done using issuer URL (/.well-known/openid-configuration response). // In this case, issuer URL should be present in JWT header or payload. HTTPEndpoint string // HTTPClient is an HTTP client for doing requests to /.well-known/openid-configuration and introspection endpoints. HTTPClient *http.Client // AccessTokenScope is a scope for getting access token for doing introspection. // The token should have introspection permission. AccessTokenScope []string // ScopeFilter is a filter for scope during introspection. // If it's set, then only access policies in scope that match at least one of the filtering policies will be returned. ScopeFilter jwt.ScopeFilter // LoggerProvider is a function that provides a logger for the Introspector. LoggerProvider func(ctx context.Context) log.FieldLogger // TrustedIssuerNotFoundFallback is a function called // when given issuer from JWT is not found in the list of trusted ones. TrustedIssuerNotFoundFallback TrustedIssNotFoundFallback // PrometheusLibInstanceLabel is a label for Prometheus metrics. // It allows distinguishing metrics from different instances of the same library. PrometheusLibInstanceLabel string // ClaimsCache is a configuration of how claims cache will be used. ClaimsCache IntrospectorCacheOpts // NegativeCache is a configuration of how negative cache will be used. NegativeCache IntrospectorCacheOpts // EndpointDiscoveryCache is a configuration of how endpoint discovery cache will be used. EndpointDiscoveryCache IntrospectorCacheOpts // ResultTemplate is a custom introspection result // that will be used instead of DefaultIntrospectionResult for unmarshalling introspection response. // It must implement IntrospectionResult interface. ResultTemplate IntrospectionResult }
IntrospectorOpts is a set of options for creating Introspector.
type MultiSourceProvider ¶
type MultiSourceProvider struct {
// contains filtered or unexported fields
}
MultiSourceProvider is a caching token provider for multiple datacenters and clients
func NewMultiSourceProvider ¶
func NewMultiSourceProvider(sources []Source) *MultiSourceProvider
NewMultiSourceProvider returns a new instance of MultiSourceProvider with default settings
func NewMultiSourceProviderWithOpts ¶
func NewMultiSourceProviderWithOpts(sources []Source, opts ProviderOpts) *MultiSourceProvider
NewMultiSourceProviderWithOpts returns a new instance of MultiSourceProvider with custom settings
func (*MultiSourceProvider) GetToken ¶
func (p *MultiSourceProvider) GetToken( ctx context.Context, clientID, sourceURL string, scope ...string, ) (string, error)
GetToken returns raw token for `clientID`, `sourceURL` and `scope`
func (*MultiSourceProvider) GetTokenWithHeaders ¶
func (p *MultiSourceProvider) GetTokenWithHeaders( ctx context.Context, clientID, sourceURL string, headers map[string]string, scope ...string, ) (string, error)
GetTokenWithHeaders returns raw token for `clientID`, `sourceURL` and `scope` while using `headers`
func (*MultiSourceProvider) Invalidate ¶
func (p *MultiSourceProvider) Invalidate()
Invalidate fully invalidates all tokens cache
func (*MultiSourceProvider) RefreshTokensPeriodically ¶
func (p *MultiSourceProvider) RefreshTokensPeriodically(ctx context.Context)
RefreshTokensPeriodically starts a goroutine which refreshes tokens
func (*MultiSourceProvider) RegisterSource ¶
func (p *MultiSourceProvider) RegisterSource(source Source)
RegisterSource allows registering a new Source into MultiSourceProvider
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider is a caching token provider for a single credentials set
func NewProvider ¶
NewProvider returns a new instance of Provider
func NewProviderWithOpts ¶
func NewProviderWithOpts(source Source, opts ProviderOpts) *Provider
NewProviderWithOpts returns a new instance of Provider with custom options
func (*Provider) GetTokenWithHeaders ¶
func (mp *Provider) GetTokenWithHeaders( ctx context.Context, headers map[string]string, scope ...string, ) (string, error)
GetTokenWithHeaders returns raw token for `scope` while using `headers`
func (*Provider) Invalidate ¶
func (mp *Provider) Invalidate()
func (*Provider) RefreshTokensPeriodically ¶
RefreshTokensPeriodically starts a goroutine which refreshes tokens
type ProviderOpts ¶
type ProviderOpts struct { // Logger is a logger for MultiSourceProvider. Logger log.FieldLogger // HTTPClient is an HTTP client for MultiSourceProvider. HTTPClient *http.Client // MinRefreshPeriod is a minimal possible refresh interval for MultiSourceProvider's token cache. MinRefreshPeriod time.Duration // CustomHeaders is a map of custom headers to be used in all HTTP requests. CustomHeaders map[string]string // CustomCacheInstance is a custom token cache instance to be used in MultiSourceProvider. CustomCacheInstance TokenCache // PrometheusLibInstanceLabel is a label for Prometheus metrics. // It allows distinguishing metrics from different instances of the same service. PrometheusLibInstanceLabel string }
ProviderOpts represents options for creating a new MultiSourceProvider
type TokenCache ¶
type TokenCache interface { // Get returns a value from the cache by key. Get(key string) *TokenDetails // Put sets a new value to the cache by key. Put(key string, val *TokenDetails) // Delete removes a value from the cache by key. Delete(key string) // ClearAll removes all values from the cache. ClearAll() // Keys returns all keys from the cache. Keys() []string }
TokenCache is a cache entry used to store TokenDetails based on a string key
type TokenData ¶
type TokenData struct { // AccessToken is the issued access token. AccessToken string // TokenType is the type of the issued access token. TokenType string // ExpiresIn is the duration of the access token validity. ExpiresIn time.Duration }
TokenData contains the data of the token issuing response from the IDP service.
type TokenDetails ¶
type TokenDetails struct {
// contains filtered or unexported fields
}
TokenDetails represents the data to be stored in TokenCache
type TrustedIssNotFoundFallback ¶
type TrustedIssNotFoundFallback func(ctx context.Context, i *Introspector, iss string) (issURL string, issFound bool)
TrustedIssNotFoundFallback is a function called when given issuer is not found in the list of trusted ones. For example, it could be analyzed and then added to the list by calling AddTrustedIssuerURL method.
type UnexpectedIDPResponseError ¶
UnexpectedIDPResponseError is an error representing an unexpected response
func (*UnexpectedIDPResponseError) Error ¶
func (e *UnexpectedIDPResponseError) Error() string