Go API Documentation

github.com/TykTechnologies/tyk/user

No package summary is available.

Package

Files: 3. Third party imports: 0. Imports from organisation: 2. Tests: 0. Benchmarks: 0.

Constants

const (
	HashPlainText	HashType	= ""
	HashBCrypt			= "bcrypt"
	HashSha256			= "sha256"
	HashMurmur32			= "murmur32"
	HashMurmur64			= "murmur64"
	HashMurmur128			= "murmur128"
)

Types

APILimit

APILimit stores quota and rate limit on ACL level (per API)

Field name Field type Comment

RateLimit

No comment on field.
ThrottleInterval

float64

No comment on field.
ThrottleRetryLimit

int

No comment on field.
MaxQueryDepth

int

No comment on field.
QuotaMax

int64

No comment on field.
QuotaRenews

int64

No comment on field.
QuotaRemaining

int64

No comment on field.
QuotaRenewalRate

int64

No comment on field.
SetBy

string

No comment on field.
type APILimit struct {
	RateLimit
	ThrottleInterval	float64	`json:"throttle_interval" msg:"throttle_interval"`
	ThrottleRetryLimit	int	`json:"throttle_retry_limit" msg:"throttle_retry_limit"`
	MaxQueryDepth		int	`json:"max_query_depth" msg:"max_query_depth"`
	QuotaMax		int64	`json:"quota_max" msg:"quota_max"`
	QuotaRenews		int64	`json:"quota_renews" msg:"quota_renews"`
	QuotaRemaining		int64	`json:"quota_remaining" msg:"quota_remaining"`
	QuotaRenewalRate	int64	`json:"quota_renewal_rate" msg:"quota_renewal_rate"`
	SetBy			string	`json:"-" msg:"-"`
}

AccessDefinition

AccessDefinition defines which versions of an API a key has access to NOTE: when adding new fields it is required to map them from DBAccessDefinition in the gateway/policy.go:19 TODO: is it possible to share fields?

Field name Field type Comment
APIName

string

No comment on field.
APIID

string

No comment on field.
Versions

[]string

No comment on field.
AllowedURLs

[]AccessSpec

No comment on field.
RestrictedTypes

[]graphql.Type

No comment on field.
AllowedTypes

[]graphql.Type

No comment on field.
Limit

APILimit

No comment on field.
FieldAccessRights

[]FieldAccessDefinition

No comment on field.
DisableIntrospection

bool

No comment on field.
AllowanceScope

string

No comment on field.
Endpoints

Endpoints

No comment on field.
type AccessDefinition struct {
	APIName			string			`json:"api_name" msg:"api_name"`
	APIID			string			`json:"api_id" msg:"api_id"`
	Versions		[]string		`json:"versions" msg:"versions"`
	AllowedURLs		[]AccessSpec		`bson:"allowed_urls" json:"allowed_urls" msg:"allowed_urls"`	// mapped string MUST be a valid regex
	RestrictedTypes		[]graphql.Type		`json:"restricted_types" msg:"restricted_types"`
	AllowedTypes		[]graphql.Type		`json:"allowed_types" msg:"allowed_types"`
	Limit			APILimit		`json:"limit" msg:"limit"`
	FieldAccessRights	[]FieldAccessDefinition	`json:"field_access_rights" msg:"field_access_rights"`
	DisableIntrospection	bool			`json:"disable_introspection" msg:"disable_introspection"`

	AllowanceScope	string	`json:"allowance_scope" msg:"allowance_scope"`

	Endpoints	Endpoints	`json:"endpoints,omitempty" msg:"endpoints,omitempty"`
}

AccessSpec

AccessSpecs define what URLS a user has access to an what methods are enabled

Field name Field type Comment
URL

string

No comment on field.
Methods

[]string

No comment on field.
type AccessSpec struct {
	URL	string		`json:"url" msg:"url"`
	Methods	[]string	`json:"methods" msg:"methods"`
}

BasicAuthData

This type doesn't have documentation.

Field name Field type Comment
Password

string

No comment on field.
Hash

HashType

No comment on field.
type BasicAuthData struct {
	Password	string		`json:"password" msg:"password"`
	Hash		HashType	`json:"hash_type" msg:"hash_type"`
}

Endpoint

Endpoint holds the configuration for endpoint rate limiting.

Field name Field type Comment
Path

string

No comment on field.
Methods

EndpointMethods

No comment on field.
type Endpoint struct {
	Path	string		`json:"path,omitempty" msg:"path"`
	Methods	EndpointMethods	`json:"methods,omitempty" msg:"methods"`
}

EndpointMethod

EndpointMethod holds the configuration on endpoint method level.

Field name Field type Comment
Name

string

No comment on field.
Limit

RateLimit

No comment on field.
type EndpointMethod struct {
	Name	string		`json:"name,omitempty" msg:"name,omitempty"`
	Limit	RateLimit	`json:"limit,omitempty" msg:"limit,omitempty"`
}

EndpointMethods

EndpointMethods is a collection of EndpointMethod.

Field name Field type Comment
type

[]EndpointMethod

No comment on field.
type EndpointMethods []EndpointMethod

EndpointRateLimitInfo

EndpointRateLimitInfo holds the information to process endpoint rate limits.

Field name Field type Comment
KeySuffix

string

KeySuffix is the suffix to use for the storage key.

Rate

float64

Rate is the allowance.

Per

float64

Per is the rate limiting interval.

type EndpointRateLimitInfo struct {
	// KeySuffix is the suffix to use for the storage key.
	KeySuffix	string
	// Rate is the allowance.
	Rate	float64
	// Per is the rate limiting interval.
	Per	float64
}

Endpoints

Endpoints is a collection of Endpoint.

Field name Field type Comment
type

[]Endpoint

No comment on field.
type Endpoints []Endpoint

EndpointsMap

EndpointsMap is the type to hold endpoint rate limit information as a map.

Field name Field type Comment
type

map[string]RateLimit

No comment on field.
type EndpointsMap map[string]RateLimit

FieldAccessDefinition

This type doesn't have documentation.

Field name Field type Comment
TypeName

string

No comment on field.
FieldName

string

No comment on field.
Limits

FieldLimits

No comment on field.
type FieldAccessDefinition struct {
	TypeName	string		`json:"type_name" msg:"type_name"`
	FieldName	string		`json:"field_name" msg:"field_name"`
	Limits		FieldLimits	`json:"limits" msg:"limits"`
}

FieldLimits

This type doesn't have documentation.

Field name Field type Comment
MaxQueryDepth

int

No comment on field.
type FieldLimits struct {
	MaxQueryDepth int `json:"max_query_depth" msg:"max_query_depth"`
}

GraphAccessDefinition

This type doesn't have documentation.

type GraphAccessDefinition struct {
}

HashType

This type doesn't have documentation.

Field name Field type Comment
type

string

No comment on field.
type HashType string

JWTData

This type doesn't have documentation.

Field name Field type Comment
Secret

string

No comment on field.
type JWTData struct {
	Secret string `json:"secret" msg:"secret"`
}

Monitor

This type doesn't have documentation.

Field name Field type Comment
TriggerLimits

[]float64

No comment on field.
type Monitor struct {
	TriggerLimits []float64 `json:"trigger_limits" msg:"trigger_limits"`
}

Policy

Policy represents a user policy swagger:model

Field name Field type Comment
MID

model.ObjectID

No comment on field.
ID

string

No comment on field.
Name

string

No comment on field.
OrgID

string

No comment on field.
Rate

float64

No comment on field.
Per

float64

No comment on field.
QuotaMax

int64

No comment on field.
QuotaRenewalRate

int64

No comment on field.
ThrottleInterval

float64

No comment on field.
ThrottleRetryLimit

int

No comment on field.
MaxQueryDepth

int

No comment on field.
AccessRights

map[string]AccessDefinition

No comment on field.
HMACEnabled

bool

No comment on field.
EnableHTTPSignatureValidation

bool

No comment on field.
Active

bool

No comment on field.
IsInactive

bool

No comment on field.
Tags

[]string

No comment on field.
KeyExpiresIn

int64

No comment on field.
Partitions

PolicyPartitions

No comment on field.
LastUpdated

string

No comment on field.
MetaData

map[string]any

No comment on field.
GraphQL

map[string]GraphAccessDefinition

No comment on field.
Smoothing

*apidef.RateLimitSmoothing

Smoothing contains rate limit smoothing settings.

type Policy struct {
	MID				model.ObjectID				`bson:"_id,omitempty" json:"_id" gorm:"primaryKey;column:_id"`
	ID				string					`bson:"id,omitempty" json:"id"`
	Name				string					`bson:"name" json:"name"`
	OrgID				string					`bson:"org_id" json:"org_id"`
	Rate				float64					`bson:"rate" json:"rate"`
	Per				float64					`bson:"per" json:"per"`
	QuotaMax			int64					`bson:"quota_max" json:"quota_max"`
	QuotaRenewalRate		int64					`bson:"quota_renewal_rate" json:"quota_renewal_rate"`
	ThrottleInterval		float64					`bson:"throttle_interval" json:"throttle_interval"`
	ThrottleRetryLimit		int					`bson:"throttle_retry_limit" json:"throttle_retry_limit"`
	MaxQueryDepth			int					`bson:"max_query_depth" json:"max_query_depth"`
	AccessRights			map[string]AccessDefinition		`bson:"access_rights" json:"access_rights"`
	HMACEnabled			bool					`bson:"hmac_enabled" json:"hmac_enabled"`
	EnableHTTPSignatureValidation	bool					`json:"enable_http_signature_validation" msg:"enable_http_signature_validation"`
	Active				bool					`bson:"active" json:"active"`
	IsInactive			bool					`bson:"is_inactive" json:"is_inactive"`
	Tags				[]string				`bson:"tags" json:"tags"`
	KeyExpiresIn			int64					`bson:"key_expires_in" json:"key_expires_in"`
	Partitions			PolicyPartitions			`bson:"partitions" json:"partitions"`
	LastUpdated			string					`bson:"last_updated" json:"last_updated"`
	MetaData			map[string]interface{}			`bson:"meta_data" json:"meta_data"`
	GraphQL				map[string]GraphAccessDefinition	`bson:"graphql_access_rights" json:"graphql_access_rights"`

	// Smoothing contains rate limit smoothing settings.
	Smoothing	*apidef.RateLimitSmoothing	`json:"smoothing" bson:"smoothing"`
}

PolicyPartitions

This type doesn't have documentation.

Field name Field type Comment
Quota

bool

No comment on field.
RateLimit

bool

No comment on field.
Complexity

bool

No comment on field.
Acl

bool

No comment on field.
PerAPI

bool

No comment on field.
type PolicyPartitions struct {
	Quota		bool	`bson:"quota" json:"quota"`
	RateLimit	bool	`bson:"rate_limit" json:"rate_limit"`
	Complexity	bool	`bson:"complexity" json:"complexity"`
	Acl		bool	`bson:"acl" json:"acl"`
	PerAPI		bool	`bson:"per_api" json:"per_api"`
}

RateLimit

RateLimit holds rate limit configuration.

Field name Field type Comment
Rate

float64

Rate is the allowed number of requests per interval.

Per

float64

Per is the interval at which rate limit is enforced.

Smoothing

*apidef.RateLimitSmoothing

Smoothing contains rate limit smoothing settings.

type RateLimit struct {
	// Rate is the allowed number of requests per interval.
	Rate	float64	`json:"rate" msg:"rate"`
	// Per is the interval at which rate limit is enforced.
	Per	float64	`json:"per" msg:"per"`

	// Smoothing contains rate limit smoothing settings.
	Smoothing	*apidef.RateLimitSmoothing	`json:"smoothing,omitempty" bson:"smoothing,omitempty"`
}

SessionState

SessionState objects represent a current API session, mainly used for rate limiting. There's a data structure that's based on this and it's used for Protocol Buffer support, make sure to update "coprocess/proto/coprocess_session_state.proto" and generate the bindings using: cd coprocess/proto && ./update_bindings.sh

swagger:model

Field name Field type Comment
LastCheck

int64

No comment on field.
Allowance

float64

No comment on field.
Rate

float64

No comment on field.
Per

float64

No comment on field.
ThrottleInterval

float64

No comment on field.
ThrottleRetryLimit

int

No comment on field.
MaxQueryDepth

int

No comment on field.
DateCreated

time.Time

No comment on field.
Expires

int64

No comment on field.
QuotaMax

int64

No comment on field.
QuotaRenews

int64

No comment on field.
QuotaRemaining

int64

No comment on field.
QuotaRenewalRate

int64

No comment on field.
AccessRights

map[string]AccessDefinition

No comment on field.
OrgID

string

No comment on field.
OauthClientID

string

No comment on field.
OauthKeys

map[string]string

No comment on field.
Certificate

string

No comment on field.
BasicAuthData

BasicAuthData

No comment on field.
JWTData

JWTData

No comment on field.
HMACEnabled

bool

No comment on field.
EnableHTTPSignatureValidation

bool

No comment on field.
HmacSecret

string

No comment on field.
RSACertificateId

string

No comment on field.
IsInactive

bool

No comment on field.
ApplyPolicyID

string

No comment on field.
ApplyPolicies

[]string

No comment on field.
DataExpires

int64

No comment on field.
Monitor

Monitor

No comment on field.
EnableDetailRecording

bool

Deprecated: EnableDetailRecording is deprecated. Use EnableDetailedRecording going forward instead

EnableDetailedRecording

bool

No comment on field.
MetaData

map[string]any

No comment on field.
Tags

[]string

No comment on field.
Alias

string

No comment on field.
LastUpdated

string

No comment on field.
IdExtractorDeadline

int64

No comment on field.
SessionLifetime

int64

No comment on field.
keyHash

string

Used to store token hash

KeyID

string

No comment on field.
Smoothing

*apidef.RateLimitSmoothing

Smoothing contains rate limit smoothing settings.

modified

bool

modified holds the hint if a session has been modified for update. use Touch() to set it, and IsModified() to get it.

type SessionState struct {
	LastCheck			int64				`json:"last_check" msg:"last_check"`
	Allowance			float64				`json:"allowance" msg:"allowance"`
	Rate				float64				`json:"rate" msg:"rate"`
	Per				float64				`json:"per" msg:"per"`
	ThrottleInterval		float64				`json:"throttle_interval" msg:"throttle_interval"`
	ThrottleRetryLimit		int				`json:"throttle_retry_limit" msg:"throttle_retry_limit"`
	MaxQueryDepth			int				`json:"max_query_depth" msg:"max_query_depth"`
	DateCreated			time.Time			`json:"date_created" msg:"date_created"`
	Expires				int64				`json:"expires" msg:"expires"`
	QuotaMax			int64				`json:"quota_max" msg:"quota_max"`
	QuotaRenews			int64				`json:"quota_renews" msg:"quota_renews"`
	QuotaRemaining			int64				`json:"quota_remaining" msg:"quota_remaining"`
	QuotaRenewalRate		int64				`json:"quota_renewal_rate" msg:"quota_renewal_rate"`
	AccessRights			map[string]AccessDefinition	`json:"access_rights" msg:"access_rights"`
	OrgID				string				`json:"org_id" msg:"org_id"`
	OauthClientID			string				`json:"oauth_client_id" msg:"oauth_client_id"`
	OauthKeys			map[string]string		`json:"oauth_keys" msg:"oauth_keys"`
	Certificate			string				`json:"certificate" msg:"certificate"`
	BasicAuthData			BasicAuthData			`json:"basic_auth_data" msg:"basic_auth_data"`
	JWTData				JWTData				`json:"jwt_data" msg:"jwt_data"`
	HMACEnabled			bool				`json:"hmac_enabled" msg:"hmac_enabled"`
	EnableHTTPSignatureValidation	bool				`json:"enable_http_signature_validation" msg:"enable_http_signature_validation"`
	HmacSecret			string				`json:"hmac_string" msg:"hmac_string"`
	RSACertificateId		string				`json:"rsa_certificate_id" msg:"rsa_certificate_id"`
	IsInactive			bool				`json:"is_inactive" msg:"is_inactive"`
	ApplyPolicyID			string				`json:"apply_policy_id" msg:"apply_policy_id"`
	ApplyPolicies			[]string			`json:"apply_policies" msg:"apply_policies"`
	DataExpires			int64				`json:"data_expires" msg:"data_expires"`
	Monitor				Monitor				`json:"monitor" msg:"monitor"`
	// Deprecated: EnableDetailRecording is deprecated. Use EnableDetailedRecording
	// going forward instead
	EnableDetailRecording	bool			`json:"enable_detail_recording" msg:"enable_detail_recording"`
	EnableDetailedRecording	bool			`json:"enable_detailed_recording" msg:"enable_detailed_recording"`
	MetaData		map[string]interface{}	`json:"meta_data" msg:"meta_data"`
	Tags			[]string		`json:"tags" msg:"tags"`
	Alias			string			`json:"alias" msg:"alias"`
	LastUpdated		string			`json:"last_updated" msg:"last_updated"`
	IdExtractorDeadline	int64			`json:"id_extractor_deadline" msg:"id_extractor_deadline"`
	SessionLifetime		int64			`bson:"session_lifetime" json:"session_lifetime"`

	// Used to store token hash
	keyHash	string
	KeyID	string	`json:"-"`

	// Smoothing contains rate limit smoothing settings.
	Smoothing	*apidef.RateLimitSmoothing	`json:"smoothing" bson:"smoothing"`

	// modified holds the hint if a session has been modified for update.
	// use Touch() to set it, and IsModified() to get it.
	modified	bool
}

Functions

func IsHashType

func IsHashType(t string) bool {
	switch HashType(t) {
	case HashBCrypt, HashSha256, HashMurmur32, HashMurmur64, HashMurmur128:
		return true
	}
	return false
}

Cognitive complexity: 3, Cyclomatic complexity: 3

func NewSessionState

func NewSessionState() *SessionState {
	return &SessionState{}
}

Cognitive complexity: 1, Cyclomatic complexity: 1

func (*Policy) APILimit

func (p *Policy) APILimit() APILimit {
	return APILimit{
		QuotaMax:		p.QuotaMax,
		QuotaRenewalRate:	p.QuotaRenewalRate,
		ThrottleInterval:	p.ThrottleInterval,
		ThrottleRetryLimit:	p.ThrottleRetryLimit,
		MaxQueryDepth:		p.MaxQueryDepth,
		RateLimit: RateLimit{
			Rate:		p.Rate,
			Per:		p.Per,
			Smoothing:	p.Smoothing,
		},
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 1

func (*SessionState) APILimit

APILimit returns an user.APILimit from the session data.

func (s *SessionState) APILimit() APILimit {
	return APILimit{
		RateLimit: RateLimit{
			Rate:		s.Rate,
			Per:		s.Per,
			Smoothing:	s.Smoothing,
		},
		QuotaMax:		s.QuotaMax,
		QuotaRenewalRate:	s.QuotaRenewalRate,
		QuotaRenews:		s.QuotaRenews,
		ThrottleInterval:	s.ThrottleInterval,
		ThrottleRetryLimit:	s.ThrottleRetryLimit,
		MaxQueryDepth:		s.MaxQueryDepth,
	}
}

Cognitive complexity: 2, Cyclomatic complexity: 1

func (*SessionState) CustomPolicies

CustomPolicies returns a map of custom policies on the session. To preserve policy order, use GetCustomPolicies instead.

func (s *SessionState) CustomPolicies() (map[string]Policy, error) {
	customPolicies, err := s.GetCustomPolicies()
	if err != nil {
		return nil, err
	}

	result := make(map[string]Policy, len(customPolicies))
	for i := 0; i < len(customPolicies); i++ {
		result[customPolicies[i].ID] = customPolicies[i]
	}

	return result, nil
}

Cognitive complexity: 4, Cyclomatic complexity: 3

func (*SessionState) GetCustomPolicies

GetCustomPolicies is like CustomPolicies but returns the list, preserving order.

func (s *SessionState) GetCustomPolicies() ([]Policy, error) {
	var (
		customPolicies []Policy
	)

	metadataPolicies, found := s.MetaData["policies"].([]interface{})
	if !found {
		return nil, errors.New("policies not found in metadata")
	}

	polJSON, err := json.Marshal(metadataPolicies)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal metadata policies: %w", err)
	}

	if err := json.Unmarshal(polJSON, &customPolicies); err != nil {
		return nil, fmt.Errorf("failed to unmarshal metadata policies: %w", err)
	}

	return customPolicies, err
}

Cognitive complexity: 7, Cyclomatic complexity: 4

Uses: errors.New, fmt.Errorf, json.Marshal, json.Unmarshal.

func (*SessionState) GetQuotaLimitByAPIID

GetQuotaLimitByAPIID return quota max, quota remaining, quota renewal rate and quota renews for the given session

func (s *SessionState) GetQuotaLimitByAPIID(apiID string) (int64, int64, int64, int64) {
	if access, ok := s.AccessRights[apiID]; ok && !access.Limit.IsEmpty() {
		return access.Limit.QuotaMax,
			access.Limit.QuotaRemaining,
			access.Limit.QuotaRenewalRate,
			access.Limit.QuotaRenews
	}

	return s.QuotaMax, s.QuotaRemaining, s.QuotaRenewalRate, s.QuotaRenews
}

Cognitive complexity: 2, Cyclomatic complexity: 3

func (*SessionState) IsBasicAuth

IsBasicAuth returns whether the key is basic auth or not.

func (s *SessionState) IsBasicAuth() bool {
	return s.BasicAuthData.Password != ""
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) IsModified

IsModified will return true if session has been modified to trigger an update.

func (s *SessionState) IsModified() bool {
	return s.modified
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) KeyHash

func (s *SessionState) KeyHash() string {
	if s.keyHash == "" {
		panic("KeyHash cache not found. You should call `SetKeyHash` before.")
	}

	return s.keyHash
}

Cognitive complexity: 2, Cyclomatic complexity: 2

func (*SessionState) KeyHashEmpty

func (s *SessionState) KeyHashEmpty() bool {
	return s.keyHash == ""
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) Lifetime

Lifetime returns the lifetime of a session. Global session lifetime has always precedence. Then, the session lifetime value in the key level takes precedence. However, if key respectKeyExpiration is true, when the key expiration has longer than the session lifetime, the key expiration is returned. It means even if the session lifetime finishes, it waits for the key expiration for physical removal.

func (s *SessionState) Lifetime(respectKeyExpiration bool, fallback int64, forceGlobalSessionLifetime bool, globalSessionLifetime int64) int64 {
	if forceGlobalSessionLifetime {
		return globalSessionLifetime
	}

	if s.SessionLifetime > 0 {
		return calculateLifetime(respectKeyExpiration, s.Expires, s.SessionLifetime)
	}

	if fallback > 0 {
		return calculateLifetime(respectKeyExpiration, s.Expires, fallback)
	}

	return 0
}

Cognitive complexity: 6, Cyclomatic complexity: 4

func (*SessionState) MD5Hash

func (s *SessionState) MD5Hash() string {
	return fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%+v", s))))
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: fmt.Sprintf, md5.Sum.

func (*SessionState) PoliciesEqualTo

PoliciesEqualTo compares and returns true if passed slice if IDs contains only current ApplyPolicies

func (s *SessionState) PoliciesEqualTo(ids []string) bool {
	if len(s.ApplyPolicies) != len(ids) {
		return false
	}

	polIDMap := make(map[string]bool, len(ids))
	for _, id := range ids {
		polIDMap[id] = true
	}

	for _, curID := range s.ApplyPolicies {
		if !polIDMap[curID] {
			return false
		}
	}

	return true
}

Cognitive complexity: 10, Cyclomatic complexity: 5

func (*SessionState) PolicyIDs

PolicyIDs returns the IDs of all the policies applied to this session. For backwards compatibility reasons, this falls back to ApplyPolicyID if ApplyPolicies is empty.

func (s *SessionState) PolicyIDs() []string {
	if len(s.ApplyPolicies) > 0 {
		return s.ApplyPolicies
	}
	if s.ApplyPolicyID != "" {
		return []string{s.ApplyPolicyID}
	}
	return nil
}

Cognitive complexity: 5, Cyclomatic complexity: 3

func (*SessionState) Reset

Reset marks the session as not modified, skipping related updates.

func (s *SessionState) Reset() {
	s.modified = false
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) SetCustomPolicies

SetCustomPolicies sets custom policies into session metadata.

func (s *SessionState) SetCustomPolicies(list []Policy) {
	if s.MetaData == nil {
		s.MetaData = make(map[string]interface{})
	}

	policies := []interface{}{}
	for pol := range list {
		policies = append(policies, list[pol])
	}
	s.MetaData["policies"] = policies
}

Cognitive complexity: 8, Cyclomatic complexity: 3

func (*SessionState) SetKeyHash

func (s *SessionState) SetKeyHash(hash string) {
	s.keyHash = hash
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) SetPolicies

func (s *SessionState) SetPolicies(ids ...string) {
	s.ApplyPolicyID = ""
	s.ApplyPolicies = ids
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (*SessionState) TagsFromMetadata

TagsFromMetadata updates the session state with the tags from the metadata.

func (s *SessionState) TagsFromMetadata(data map[string]interface{}) (updateSession bool) {
	developerID, keyFound := data["tyk_developer_id"].(string)
	if keyFound {
		s.MetaData["tyk_developer_id"] = developerID
		updateSession = true
	}

	limitPattern, keyFound := data["rate_limit_pattern"].(string)
	if keyFound {
		s.MetaData["rate_limit_pattern"] = limitPattern
		updateSession = true
	}

	// pteam-<id>, porg-<id>
	clientTags, ok := data["tags"].([]interface{})
	if ok {
		for _, tag := range clientTags {
			strTag, ok := tag.(string)
			if !ok {
				continue
			}
			s.Tags = append(s.Tags, strTag)
		}
		updateSession = true
	}

	policies, ok := data["policies"].([]interface{})
	if ok {
		s.MetaData["policies"] = policies
		updateSession = true
	}

	return
}

Cognitive complexity: 16, Cyclomatic complexity: 7

func (*SessionState) Touch

Touch marks the session as modified, indicating that it should be updated.

func (s *SessionState) Touch() {
	s.modified = true
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (APILimit) Clone

Clone does a deepcopy of APILimit.

func (a APILimit) Clone() *APILimit {
	var smoothingRef *apidef.RateLimitSmoothing
	if a.Smoothing != nil {
		smoothing := *a.Smoothing
		smoothingRef = &smoothing
	}

	return &APILimit{
		RateLimit: RateLimit{
			Rate:		a.Rate,
			Per:		a.Per,
			Smoothing:	smoothingRef,
		},
		ThrottleInterval:	a.ThrottleInterval,
		ThrottleRetryLimit:	a.ThrottleRetryLimit,
		MaxQueryDepth:		a.MaxQueryDepth,
		QuotaMax:		a.QuotaMax,
		QuotaRenews:		a.QuotaRenews,
		QuotaRemaining:		a.QuotaRemaining,
		QuotaRenewalRate:	a.QuotaRenewalRate,
		SetBy:			a.SetBy,
	}
}

Cognitive complexity: 4, Cyclomatic complexity: 2

Uses: apidef.RateLimitSmoothing.

func (APILimit) IsEmpty

IsEmpty checks if APILimit is empty.

func (a APILimit) IsEmpty() bool {
	if a.Rate != 0 {
		return false
	}

	if a.Per != 0 {
		return false
	}

	if a.ThrottleInterval != 0 {
		return false
	}

	if a.ThrottleRetryLimit != 0 {
		return false
	}

	if a.MaxQueryDepth != 0 {
		return false
	}

	if a.QuotaMax != 0 {
		return false
	}

	if a.QuotaRenews != 0 {
		return false
	}

	if a.QuotaRemaining != 0 {
		return false
	}

	if a.QuotaRenewalRate != 0 {
		return false
	}

	if a.SetBy != "" {
		return false
	}

	return true
}

Cognitive complexity: 20, Cyclomatic complexity: 11

func (EndpointMethods) Contains

Contains is used to assert if a method exists in EndpointMethods.

func (em EndpointMethods) Contains(method string) bool {
	for _, v := range em {
		if strings.EqualFold(v.Name, method) {
			return true
		}
	}
	return false
}

Cognitive complexity: 5, Cyclomatic complexity: 3

Uses: strings.EqualFold.

func (EndpointMethods) Len

Len is used to implement sort interface.

func (em EndpointMethods) Len() int {
	return len(em)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (EndpointMethods) Less

Less is used to implement sort interface.

func (em EndpointMethods) Less(i, j int) bool {
	return strings.ToUpper(em[i].Name) < strings.ToUpper(em[j].Name)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Uses: strings.ToUpper.

func (EndpointMethods) Swap

Swap is used to implement sort interface.

func (em EndpointMethods) Swap(i, j int) {
	em[i], em[j] = em[j], em[i]
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (Endpoints) Len

Len is used to implement sort interface.

func (es Endpoints) Len() int {
	return len(es)
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (Endpoints) Less

Less is used to implement sort interface.

func (es Endpoints) Less(i, j int) bool {
	return es[i].Path < es[j].Path
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (Endpoints) Map

Map returns EndpointsMap of Endpoints using the key format [method:path]. If duplicate entries are found, it would get overwritten with latest entries Endpoints.

func (es Endpoints) Map() EndpointsMap {
	if len(es) == 0 {
		return nil
	}

	out := make(EndpointsMap)
	for _, e := range es {
		for _, method := range e.Methods {
			key := fmt.Sprintf("%s:%s", method.Name, e.Path)
			out[key] = method.Limit
		}
	}

	return out
}

Cognitive complexity: 8, Cyclomatic complexity: 4

Uses: fmt.Sprintf.

func (Endpoints) Swap

Swap is used to implement sort interface.

func (es Endpoints) Swap(i, j int) {
	es[i], es[j] = es[j], es[i]
}

Cognitive complexity: 0, Cyclomatic complexity: 1

func (EndpointsMap) Endpoints

Endpoints coverts EndpointsMap to Endpoints.

func (em EndpointsMap) Endpoints() Endpoints {
	if len(em) == 0 {
		return nil
	}

	var perPathMethods = make(map[string]EndpointMethods)
	for key, rateLimit := range em {
		keyParts := strings.Split(key, ":")
		if len(keyParts) != 2 {
			continue
		}

		method, path := keyParts[0], keyParts[1]
		epMethod := EndpointMethod{
			Name:	method,
			Limit:	rateLimit,
		}
		if methods, ok := perPathMethods[path]; ok {
			perPathMethods[path] = append(methods, epMethod)
			continue
		}

		perPathMethods[path] = EndpointMethods{
			epMethod,
		}
	}

	var endpoints Endpoints
	for path, methods := range perPathMethods {
		sort.Sort(methods)
		endpoints = append(endpoints, Endpoint{
			Path:		path,
			Methods:	methods,
		})
	}

	sort.Sort(endpoints)

	return endpoints
}

Cognitive complexity: 15, Cyclomatic complexity: 6

Uses: sort.Sort, strings.Split.

func (PolicyPartitions) Enabled

Enabled reports if partitioning is enabled.

func (p PolicyPartitions) Enabled() bool {
	return p.Quota || p.RateLimit || p.Acl || p.Complexity
}

Cognitive complexity: 0, Cyclomatic complexity: 4

func (RateLimit) Duration

Duration returns the time between two allowed requests at the defined rate. It's used to decide which rate limit has a bigger allowance.

func (r RateLimit) Duration() time.Duration {
	if r.Per <= 0 || r.Rate <= 0 {
		return 0
	}
	return time.Duration(float64(time.Second) * r.Per / r.Rate)
}

Cognitive complexity: 2, Cyclomatic complexity: 3

Uses: time.Duration, time.Second.

func (SessionState) Clone

Clone returns a fresh copy of s

func (s SessionState) Clone() SessionState {
	// Simple vales are cloned by value
	newSession := s
	newSession.AccessRights = cloneAccess(s.AccessRights)
	newSession.OauthKeys = cloneKeys(s.OauthKeys)
	newSession.ApplyPolicies = cloneSlice(s.ApplyPolicies)
	newSession.MetaData = cloneMetadata(s.MetaData)
	newSession.Tags = cloneSlice(s.Tags)

	return newSession
}

Cognitive complexity: 0, Cyclomatic complexity: 1

Private functions

func calculateLifetime

calculateLifetime calculates the lifetime of a session. It also sets the value to the key expiration in case of the key expiration value is respected and lifetime < expiration.

calculateLifetime (respectExpiration bool, expiration,lifetime int64) int64
References: time.Duration, time.Now, time.Second.

func cloneAccess

cloneAccess (m map[string]AccessDefinition) map[string]AccessDefinition

func cloneKeys

cloneKeys (m map[string]string) map[string]string

func cloneMetadata

cloneMetadata (m map[string]interface{}) map[string]interface{}

func cloneSlice

cloneSlice (s []string) []string


Tests

Files: 3. Third party imports: 1. Imports from organisation: 0. Tests: 12. Benchmarks: 0.

Test functions

TestAPILimit_Clone

References: apidef.RateLimitSmoothing, assert.NotEqual, reflect.DeepEqual, testing.T.

TestAPILimit_Duration

References: assert.Equal, testing.T, time.Duration, time.Second.

TestAPILimit_IsEmpty

References: assert.Equal, testing.T.

TestEndpointsMap_Endpoints

References: assert.Equal, testing.T.

TestEndpoints_Map

References: assert.Equal, testing.T.

TestIsHashType

References: assert.False, assert.True.

TestSessionState_CustomPolicies

References: reflect.DeepEqual, testing.T.

TestSessionState_Lifetime

References: assert.Equal, testing.T, time.Now, time.Second.

TestSessionState_SetCustomPolicies

References: assert.NoError, assert.True, testing.T.

TestSessionState_TagsFromMetadata

References: testing.T.

TestSessionState_Touch_and_IsModified

References: assert.Equal, assert.False, assert.NoError, assert.True, json.Marshal, json.Unmarshal.

Test_calculateLifetime

References: assert.Equal, testing.T, time.Duration, time.Now, time.Second.