idptoken

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2024 License: MIT Imports: 32 Imported by: 0

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

View Source
const (
	DefaultIntrospectionClaimsCacheMaxEntries   = 1000
	DefaultIntrospectionClaimsCacheTTL          = 1 * time.Minute
	DefaultIntrospectionNegativeCacheMaxEntries = 1000
	DefaultIntrospectionNegativeCacheTTL        = 10 * time.Minute
)
View Source
const DefaultRequestTimeout = 30 * time.Second
View Source
const JWTTypeAccessToken = "at+jwt"
View Source
const TokenTypeBearer = "bearer"

Variables

View Source
var (
	// ErrSourceNotRegistered is returned if GetToken is requested for the unknown Source
	ErrSourceNotRegistered = errors.New("cannot issue token for unknown source")
)
View 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).

View Source
var ErrTokenIntrospectionUnauthenticated = errors.New("token introspection is unauthenticated")

ErrTokenIntrospectionUnauthenticated is returned when token introspection is unauthenticated.

View Source
var ErrTokenNotIntrospectable = errors.New("token is not introspectable")

ErrTokenNotIntrospectable is returned when token is not introspectable.

Functions

This section is empty.

Types

type CachingIntrospector

type CachingIntrospector struct {
	*Introspector
	ClaimsCache   IntrospectionClaimsCache
	NegativeCache IntrospectionNegativeCache
	// contains filtered or unexported fields
}

func NewCachingIntrospector

func NewCachingIntrospector(tokenProvider IntrospectionTokenProvider) (*CachingIntrospector, error)

func NewCachingIntrospectorWithOpts

func NewCachingIntrospectorWithOpts(
	tokenProvider IntrospectionTokenProvider, opts CachingIntrospectorOpts,
) (*CachingIntrospector, error)

func (*CachingIntrospector) IntrospectToken

func (i *CachingIntrospector) IntrospectToken(ctx context.Context, token string) (IntrospectionResult, error)

type CachingIntrospectorCacheOpts

type CachingIntrospectorCacheOpts struct {
	Enabled    bool
	MaxEntries int
	TTL        time.Duration
}

type CachingIntrospectorOpts

type CachingIntrospectorOpts struct {
	IntrospectorOpts
	ClaimsCache   CachingIntrospectorCacheOpts
	NegativeCache CachingIntrospectorCacheOpts
}

type Config

type Config struct {
	URL          string
	ClientID     string
	ClientSecret string
}

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

func (c *GRPCClient) IntrospectToken(
	ctx context.Context, token string, scopeFilter []IntrospectionScopeFilterAccessPolicy, accessToken string,
) (IntrospectionResult, error)

IntrospectToken introspects the token using the IDP token service.

type GRPCClientOpts

type GRPCClientOpts struct {
	// Logger is a logger for the client.
	Logger log.FieldLogger

	// RequestTimeout is a timeout for the gRPC requests.
	RequestTimeout time.Duration

	// 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 IntrospectionClaimsCache

type IntrospectionClaimsCache interface {
	Get(ctx context.Context, key [sha256.Size]byte) (IntrospectionClaimsCacheItem, bool)
	Add(ctx context.Context, key [sha256.Size]byte, value IntrospectionClaimsCacheItem)
	Purge(ctx context.Context)
	Len(ctx context.Context) int
}

type IntrospectionClaimsCacheItem

type IntrospectionClaimsCacheItem struct {
	Claims    *jwt.Claims
	TokenType string
	CreatedAt time.Time
}

type IntrospectionNegativeCache

type IntrospectionNegativeCache interface {
	Get(ctx context.Context, key [sha256.Size]byte) (IntrospectionNegativeCacheItem, bool)
	Add(ctx context.Context, key [sha256.Size]byte, value IntrospectionNegativeCacheItem)
	Purge(ctx context.Context)
	Len(ctx context.Context) int
}

type IntrospectionNegativeCacheItem

type IntrospectionNegativeCacheItem struct {
	CreatedAt time.Time
}

type IntrospectionResult

type IntrospectionResult struct {
	Active    bool   `json:"active"`
	TokenType string `json:"token_type,omitempty"`
	jwt.Claims
}

IntrospectionResult is a struct for introspection result.

type IntrospectionScopeFilterAccessPolicy

type IntrospectionScopeFilterAccessPolicy struct {
	ResourceNamespace string
}

IntrospectionScopeFilterAccessPolicy is an access policy for filtering scopes.

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 {
	// contains filtered or unexported fields
}

Introspector is a struct for introspecting tokens.

func NewIntrospector

func NewIntrospector(tokenProvider IntrospectionTokenProvider) *Introspector

NewIntrospector creates a new Introspector with the given token provider.

func NewIntrospectorWithOpts

func NewIntrospectorWithOpts(accessTokenProvider IntrospectionTokenProvider, opts IntrospectorOpts) *Introspector

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

	// StaticHTTPEndpoint 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.
	StaticHTTPEndpoint 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 list of access policies for filtering scopes during introspection.
	// If it is set, then only scopes that match at least one of the policies will be returned.
	ScopeFilter []IntrospectionScopeFilterAccessPolicy

	// Logger is a logger for logging errors and debug information.
	Logger 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
}

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(httpClient *http.Client) *MultiSourceProvider

NewMultiSourceProvider returns a new instance of MultiSourceProvider with default settings

func NewMultiSourceProviderWithOpts

func NewMultiSourceProviderWithOpts(
	httpClient *http.Client, opts ProviderOpts, sources ...Source,
) *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

func NewProvider(httpClient *http.Client, source Source) *Provider

NewProvider returns a new instance of Provider

func NewProviderWithOpts

func NewProviderWithOpts(httpClient *http.Client, opts ProviderOpts, source Source) *Provider

NewProviderWithOpts returns a new instance of Provider with custom options

func (*Provider) GetToken

func (mp *Provider) GetToken(
	ctx context.Context, scope ...string,
) (string, error)

GetToken returns raw token for `scope`

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

func (mp *Provider) RefreshTokensPeriodically(ctx context.Context)

RefreshTokensPeriodically starts a goroutine which refreshes tokens

type ProviderOpts

type ProviderOpts struct {
	// Logger is a logger for MultiSourceProvider.
	Logger log.FieldLogger

	// 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 Source

type Source struct {
	URL          string
	ClientID     string
	ClientSecret string
}

Source serves to provide auth source information to MultiSourceProvider and Provider

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 {
	Data     string
	ClientID string

	Scope   []string
	Expires time.Time
	// contains filtered or unexported fields
}

TokenData represents API-related token information

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

type UnexpectedIDPResponseError struct {
	HTTPCode int
	IssueURL string
}

UnexpectedIDPResponseError is an error representing an unexpected response

func (*UnexpectedIDPResponseError) Error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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