Help us shape the future of Go! Take the 2026 Go Developer Survey

cognitoidentity

package
v1.8.3 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 28 Imported by: 0

README

Cognito Identity

Parity grade: A · SDK aws-sdk-go-v2/service/cognitoidentity@v1.36.4 · last audited 2026-10-12 (81a1aabf0)

Coverage

Metric Value
PARITY entries audited 23 (23 ok)
Feature families 1 (1 ok)
Known gaps 1
Deferred items 4
Resource leaks clean
Known gaps
  • Login tokens from providers other than emulator-hosted Cognito user pools (Google, Facebook, OIDC/SAML) are not signature-verified; opaque tokens are accepted.
Deferred
  • HTTP status code choice for NotAuthorizedException (403 here) vs AWS's actual per-exception status (SDK error-type resolution is body-driven, not status-code-driven, so this doesn't break aws-sdk-go-v2 clients; only relevant to tooling that inspects raw HTTP status).
  • ALREADY COVERED BY CHAOS (verified gopherstack-tqdj): ConcurrentModificationException (SetIdentityPoolRoles, UpdateIdentityPool per deserializers.go) is not emulated: there is no optimistic-concurrency/version token in this backend's resource model to make a genuine concurrent-write collision detectable, and fabricating one that never fires (or fires on arbitrary heuristics) would be worse than omitting it. Would need a real revision-counter field added to IdentityPool/IdentityRoles to do properly -- out of scope for an error-taxonomy pass. Concretely verified this pass: cognitoidentity.Handler implements ChaosServiceName() -> "cognito-identity" and ChaosOperations() -> h.GetSupportedOperations() (handler.go), and pkgs/chaos.Middleware is wired globally via registry.Use(chaos.Middleware(faultStore)) in internal/app/cli.go, matching purely on the request's SigV4 service name + X-Amz-Target operation + region and injecting an arbitrary caller-specified FaultError{Code, StatusCode} without touching backend state -- a fault rule such as {"service":"cognito-identity","operation":"UpdateIdentityPool","error":{"code":"ConcurrentModificationException","statusCode":400}} deterministically returns that exact typed error to a real client with zero backend code changes.
  • ALREADY COVERED BY CHAOS (verified gopherstack-tqdj): TooManyRequestsException (every op) and LimitExceededException (CreateIdentityPool/GetId/UpdateIdentityPool per deserializers.go) are throttling/account-quota conditions; this in-memory emulator has no request-rate tracking and AWS's actual per-account pool/identity quotas are account-specific soft limits, not fixed constants -- inventing an arbitrary hard-coded threshold would be a fabricated business rule, not a verified one. Left unimplemented, consistent with how other gopherstack services treat throttling. Same chaos mechanism as ConcurrentModificationException above makes both reachable on demand with zero backend code changes.
  • ALREADY COVERED BY CHAOS (verified gopherstack-tqdj): ExternalServiceException (GetCredentialsForIdentity, GetId, GetOpenIdToken, UnlinkIdentity per deserializers.go) is AWS's wrapper for a real external identity provider (Facebook/Google/a linked Cognito user pool) rejecting a token. This backend validates login tokens against its own stored state, not a real external IdP, so there is no authentic backend-state trigger condition for this exception here. Same chaos mechanism as above makes it reachable on demand with zero backend code changes.

More

Documentation

Overview

Package cognitoidentity provides a mock implementation of the AWS Cognito Federated Identities service.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrIdentityPoolNotFound is returned when the requested identity pool does not exist.
	ErrIdentityPoolNotFound = awserr.New("ResourceNotFoundException", awserr.ErrNotFound)

	// ErrIdentityPoolAlreadyExists is returned when an identity pool with the given name already exists.
	ErrIdentityPoolAlreadyExists = awserr.New("ResourceConflictException", awserr.ErrAlreadyExists)

	// ErrInvalidParameter is returned when an invalid or missing parameter is supplied.
	ErrInvalidParameter = awserr.New("InvalidParameterException", awserr.ErrInvalidParameter)

	// ErrNotAuthorized is returned when the caller lacks required permissions.
	ErrNotAuthorized = awserr.New("NotAuthorizedException", awserr.ErrInvalidParameter)

	// ErrResourceConflict is returned when a request's parameters conflict with
	// existing state (for example, LookupDeveloperIdentity supplying both an
	// IdentityId and a DeveloperUserIdentifier that do not resolve to the same
	// identity). Distinct from ErrIdentityPoolAlreadyExists (also wire-typed
	// ResourceConflictException) which is specifically about pool-name collisions.
	ErrResourceConflict = awserr.New("ResourceConflictException", awserr.ErrConflict)

	// ErrDeveloperUserAlreadyRegistered is returned by GetOpenIdTokenForDeveloperIdentity
	// when the developer user identifier supplied in Logins is already linked to a
	// different identity than the one requested.
	ErrDeveloperUserAlreadyRegistered = awserr.New(
		"DeveloperUserAlreadyRegisteredException",
		awserr.ErrConflict,
	)

	// ErrInvalidIdentityPoolConfiguration is returned by GetCredentialsForIdentity when
	// the identity pool has no IAM role configured for the identity's auth state
	// (authenticated vs. unauthenticated).
	ErrInvalidIdentityPoolConfiguration = awserr.New(
		"InvalidIdentityPoolConfigurationException",
		awserr.ErrInvalidParameter,
	)
)

Sentinel errors for Cognito Identity Pool operations.

Functions

This section is empty.

Types

type Credentials

type Credentials struct {
	Expiration      time.Time
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	IdentityID      string
}

Credentials holds temporary AWS credentials returned by GetCredentialsForIdentity.

type DeveloperOpenIDToken

type DeveloperOpenIDToken struct {
	IdentityID string
	Token      string
}

DeveloperOpenIDToken is the result of GetOpenIDTokenForDeveloperIdentity.

type DeveloperTokenOptions

type DeveloperTokenOptions struct {
	PrincipalTags map[string]string
}

DeveloperTokenOptions carries the optional GetOpenIdTokenForDeveloperIdentity members.

type Handler

type Handler struct {
	Backend *InMemoryBackend
	// contains filtered or unexported fields
}

Handler is the Echo HTTP handler for Cognito Identity Pool operations.

func NewHandler

func NewHandler(backend *InMemoryBackend, region string) *Handler

NewHandler creates a new Cognito Identity handler.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns all operations that can be fault-injected.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns all regions this Cognito Identity instance handles.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns the lowercase AWS service name for fault rule matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the Cognito Identity action from the X-Amz-Target header.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource extracts the identity pool or identity resource from the request.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns the list of supported operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all backend state and rebuilds the dispatch table.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable by delegating to the backend.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher returns a function that matches Cognito Identity requests.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable by delegating to the backend.

type Identity

type Identity struct {
	CreatedAt        time.Time         `json:"createdAt"`
	LastModifiedDate time.Time         `json:"lastModifiedDate"`
	Logins           map[string]string `json:"logins,omitempty"`
	IdentityID       string            `json:"identityID"`
	IdentityPoolID   string            `json:"identityPoolID"`

	Enabled bool `json:"enabled"`
	// contains filtered or unexported fields
}

Identity represents a federated identity.

type IdentityDescription

type IdentityDescription struct {
	CreationDate     time.Time `json:"creationDate"`
	LastModifiedDate time.Time `json:"lastModifiedDate"`
	IdentityID       string    `json:"identityId"`
	Logins           []string  `json:"logins,omitempty"`
}

IdentityDescription describes a federated identity, including its login providers.

type IdentityPool

type IdentityPool struct {
	CreatedAt                 time.Time         `json:"createdAt"`
	SupportedLoginProviders   map[string]string `json:"supportedLoginProviders,omitempty"`
	Tags                      map[string]string `json:"tags,omitempty"`
	OpenIDConnectProviderARNs []string          `json:"openIdConnectProviderARNs,omitempty"`
	SamlProviderARNs          []string          `json:"samlProviderARNs,omitempty"`
	IdentityPoolID            string            `json:"identityPoolID"`
	IdentityPoolName          string            `json:"identityPoolName"`
	ARN                       string            `json:"arn"`
	DeveloperProviderName     string            `json:"developerProviderName,omitempty"`

	IdentityProviders              []IdentityProvider `json:"identityProviders,omitempty"`
	AllowUnauthenticatedIdentities bool               `json:"allowUnauthenticatedIdentities"`
	AllowClassicFlow               bool               `json:"allowClassicFlow"`
	// contains filtered or unexported fields
}

IdentityPool represents an Amazon Cognito Identity Pool.

type IdentityProvider

type IdentityProvider struct {
	ProviderName         string `json:"providerName"`
	ClientID             string `json:"clientID"`
	ServerSideTokenCheck bool   `json:"serverSideTokenCheck"`
}

IdentityProvider represents a linked Cognito User Pool provider.

type IdentityRoles

type IdentityRoles struct {
	RoleMappings           map[string]RoleMapping `json:"roleMappings,omitempty"`
	AuthenticatedRoleARN   string                 `json:"authenticatedRoleARN"`
	UnauthenticatedRoleARN string                 `json:"unauthenticatedRoleARN"`
	// contains filtered or unexported fields
}

IdentityRoles holds IAM role mappings for an identity pool.

type InMemoryBackend

type InMemoryBackend struct {
	// contains filtered or unexported fields
}

InMemoryBackend is the in-memory store for Cognito Identity Pool resources.

The four resource collections below were previously nested by region (outer key = region, e.g. map[string]map[string]*IdentityPool) so that same-named resources are isolated across regions. Each is now a flat *store.Table keyed by the composite "region|id" string (see regionKey), with companion *store.Index values replacing the old reverse-lookup maps (poolsByName, poolsByARN, identitiesByPool) and the prefix-scan used to purge a pool's principal-tag mappings. Callers must hold b.mu while accessing any table or index, exactly as they held it for the old maps -- store.Table and store.Index perform no locking of their own.

func NewInMemoryBackend

func NewInMemoryBackend(accountID, region string) *InMemoryBackend

NewInMemoryBackend creates a new InMemoryBackend.

func (*InMemoryBackend) AddIdentityInternal

func (b *InMemoryBackend) AddIdentityInternal(identity *Identity)

AddIdentityInternal seeds an identity directly into the backend for testing purposes. The region is derived from the identity's IdentityPoolID prefix (format: "region:uuid").

func (*InMemoryBackend) AddPoolInternal

func (b *InMemoryBackend) AddPoolInternal(pool *IdentityPool)

AddPoolInternal seeds an identity pool directly into the backend for testing purposes. It bypasses the normal CreateIdentityPool validation. The region is derived from the pool's ARN.

func (*InMemoryBackend) CreateIdentityPool

func (b *InMemoryBackend) CreateIdentityPool(
	ctx context.Context,
	name string,
	allowUnauthenticated bool,
	allowClassicFlow bool,
	developerProviderName string,
	providers []IdentityProvider,
	supportedLoginProviders map[string]string,
	tags map[string]string,
	opts ...*PoolExtendedConfig,
) (*IdentityPool, error)

CreateIdentityPool creates a new identity pool.

func (*InMemoryBackend) DeleteIdentities

func (b *InMemoryBackend) DeleteIdentities(
	ctx context.Context,
	identityIDs []string,
) ([]UnprocessedIdentityID, error)

DeleteIdentities deletes the given identity IDs from the backend. Identities that do not exist are silently skipped. Returns a (possibly empty) list of IDs that could not be processed.

func (*InMemoryBackend) DeleteIdentityPool

func (b *InMemoryBackend) DeleteIdentityPool(ctx context.Context, poolID string) error

DeleteIdentityPool removes an identity pool and all associated identities, roles, and principal-tag configurations.

func (*InMemoryBackend) DescribeIdentity

func (b *InMemoryBackend) DescribeIdentity(
	ctx context.Context,
	identityID string,
) (*IdentityDescription, error)

DescribeIdentity returns metadata about a specific federated identity.

func (*InMemoryBackend) DescribeIdentityPool

func (b *InMemoryBackend) DescribeIdentityPool(
	ctx context.Context,
	poolID string,
) (*IdentityPool, error)

DescribeIdentityPool returns the identity pool with the given ID.

func (*InMemoryBackend) GetCredentialsForIdentity

func (b *InMemoryBackend) GetCredentialsForIdentity(
	ctx context.Context,
	identityID string,
	logins map[string]string,
	customRoleARN string,
) (*Credentials, error)

GetCredentialsForIdentity returns temporary credentials for the role selected for an identity.

func (*InMemoryBackend) GetID

func (b *InMemoryBackend) GetID(
	ctx context.Context,
	poolID string,
	_ string,
	logins map[string]string,
) (*Identity, error)

GetID returns an existing identity or creates a new one for the given pool and logins.

func (*InMemoryBackend) GetIdentityPoolRoles

func (b *InMemoryBackend) GetIdentityPoolRoles(
	ctx context.Context,
	poolID string,
) (*IdentityRoles, error)

GetIdentityPoolRoles returns the IAM roles configured for an identity pool.

func (*InMemoryBackend) GetOpenIDToken

func (b *InMemoryBackend) GetOpenIDToken(
	ctx context.Context,
	identityID string,
	_ map[string]string,
) (*OpenIDToken, error)

GetOpenIDToken returns a synthetic OpenID Connect token for an identity.

func (*InMemoryBackend) GetOpenIDTokenForDeveloperIdentity

func (b *InMemoryBackend) GetOpenIDTokenForDeveloperIdentity(
	ctx context.Context,
	poolID string,
	identityID string,
	logins map[string]string,
	tokenDuration int64,
	opts ...DeveloperTokenOptions,
) (*DeveloperOpenIDToken, error)

GetOpenIDTokenForDeveloperIdentity registers or retrieves an identity for a developer authenticated user, then returns a synthetic OpenID token.

func (*InMemoryBackend) GetPrincipalTagAttributeMap

func (b *InMemoryBackend) GetPrincipalTagAttributeMap(
	ctx context.Context,
	poolID, providerName string,
) (*PrincipalTagMapping, error)

GetPrincipalTagAttributeMap returns the principal tag attribute map for a pool and provider.

func (*InMemoryBackend) ListIdentities

func (b *InMemoryBackend) ListIdentities(
	ctx context.Context,
	poolID string,
	maxResults int,
	hideDisabled bool,
	nextToken string,
) (*ListIdentitiesResult, error)

ListIdentities returns identities associated with an identity pool, sorted by IdentityId. nextToken is an opaque cursor encoding the last-returned IdentityId for pagination.

func (*InMemoryBackend) ListIdentityPools

func (b *InMemoryBackend) ListIdentityPools(
	ctx context.Context,
	maxResults int,
	nextToken string,
) ([]*IdentityPool, string)

ListIdentityPools returns all identity pools sorted by name, up to maxResults (0 = all). nextToken is an opaque cursor that encodes the last-returned pool name for pagination.

func (*InMemoryBackend) ListTagsForResource

func (b *InMemoryBackend) ListTagsForResource(
	ctx context.Context,
	resourceARN string,
) (map[string]string, error)

ListTagsForResource returns the tags for an identity pool resource by its ARN.

func (*InMemoryBackend) LookupDeveloperIdentity

func (b *InMemoryBackend) LookupDeveloperIdentity(
	ctx context.Context,
	poolID string,
	identityID string,
	developerUserIdentifier string,
	developerProviderName string,
) (*LookupDeveloperIdentityResult, error)

LookupDeveloperIdentity retrieves the identity associated with a developer user identifier or the list of developer user identifiers associated with an identity. Per AWS semantics, if you supply only one of IdentityId/DeveloperUserIdentifier, the other is looked up and returned; if you supply both, DeveloperUserIdentifier is verified against IdentityId and a ResourceConflictException is returned when they do not match.

func (*InMemoryBackend) MergeDeveloperIdentities

func (b *InMemoryBackend) MergeDeveloperIdentities(
	ctx context.Context,
	sourceUserID string,
	destUserID string,
	developerProviderName string,
	poolID string,
) (*Identity, error)

MergeDeveloperIdentities merges the source identity into the destination identity.

func (*InMemoryBackend) Region

func (b *InMemoryBackend) Region() string

Region returns the region this backend is configured for.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all identity pool, identity and role state.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot. It implements persistence.Persistable.

func (*InMemoryBackend) SetIdentityPoolRoles

func (b *InMemoryBackend) SetIdentityPoolRoles(
	ctx context.Context,
	poolID, authenticatedARN, unauthenticatedARN string,
	roleMappings map[string]RoleMapping,
) error

SetIdentityPoolRoles configures IAM roles for an identity pool. Only the roles that are present (non-empty) in the provided map are updated; existing roles for omitted keys are preserved.

func (*InMemoryBackend) SetPrincipalTagAttributeMap

func (b *InMemoryBackend) SetPrincipalTagAttributeMap(
	ctx context.Context,
	poolID string,
	providerName string,
	useDefaults bool,
	principalTags map[string]string,
) (*PrincipalTagMapping, error)

SetPrincipalTagAttributeMap configures principal tag attribute mappings for a pool and provider.

func (*InMemoryBackend) SetRoleAssumer

func (b *InMemoryBackend) SetRoleAssumer(a RoleAssumer)

SetRoleAssumer wires the STS seam used by GetCredentialsForIdentity.

func (*InMemoryBackend) SetTokenKeyResolver

func (b *InMemoryBackend) SetTokenKeyResolver(r TokenKeyResolver)

SetTokenKeyResolver wires signature verification for user-pool login tokens.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON. It implements persistence.Persistable.

func (*InMemoryBackend) TagResource

func (b *InMemoryBackend) TagResource(
	ctx context.Context,
	resourceARN string,
	tags map[string]string,
) error

TagResource adds or updates tags on an identity pool resource by ARN.

func (*InMemoryBackend) UnlinkDeveloperIdentity

func (b *InMemoryBackend) UnlinkDeveloperIdentity(
	ctx context.Context,
	identityID string,
	poolID string,
	developerProviderName string,
	developerUserIdentifier string,
) error

UnlinkDeveloperIdentity removes a developer-provider association from an identity.

func (*InMemoryBackend) UnlinkIdentity

func (b *InMemoryBackend) UnlinkIdentity(
	ctx context.Context,
	identityID string,
	logins map[string]string,
	loginsToRemove []string,
) error

UnlinkIdentity removes login providers from an identity after validating the supplied login tokens.

func (*InMemoryBackend) UntagResource

func (b *InMemoryBackend) UntagResource(
	ctx context.Context,
	resourceARN string,
	tagKeys []string,
) error

UntagResource removes the given tag keys from an identity pool resource by ARN.

func (*InMemoryBackend) UpdateIdentityPool

func (b *InMemoryBackend) UpdateIdentityPool(
	ctx context.Context,
	poolID string,
	name string,
	allowUnauthenticated bool,
	allowClassicFlow bool,
	developerProviderName string,
	providers []IdentityProvider,
	supportedLoginProviders map[string]string,
	tags map[string]string,
	opts ...*PoolExtendedConfig,
) (*IdentityPool, error)

UpdateIdentityPool updates the settings of an existing identity pool.

type ListIdentitiesResult

type ListIdentitiesResult struct {
	IdentityPoolID string                `json:"identityPoolId"`
	NextToken      string                `json:"nextToken,omitempty"`
	Identities     []IdentityDescription `json:"identities"`
}

ListIdentitiesResult holds the output for ListIdentities.

type LookupDeveloperIdentityResult

type LookupDeveloperIdentityResult struct {
	IdentityID                  string
	DeveloperUserIdentifierList []string
}

LookupDeveloperIdentityResult holds the output of LookupDeveloperIdentity.

type MappingRule

type MappingRule struct {
	Claim     string `json:"claim"`
	MatchType string `json:"matchType"`
	Value     string `json:"value"`
	RoleARN   string `json:"roleARN"`
}

MappingRule defines a single claim-based role assignment rule.

type OpenIDToken

type OpenIDToken struct {
	IdentityID string
	Token      string
}

OpenIDToken holds the result of GetOpenIdToken.

type PoolExtendedConfig

type PoolExtendedConfig struct {
	OpenIDConnectProviderARNs []string
	SamlProviderARNs          []string
}

PoolExtendedConfig carries optional fields added in later API versions that would otherwise require touching every existing CreateIdentityPool/UpdateIdentityPool call site. Pass as a trailing variadic arg; callers that omit it get zero values.

type PrincipalTagMapping

type PrincipalTagMapping struct {
	PrincipalTags map[string]string `json:"principalTags,omitempty"`

	UseDefaults bool `json:"useDefaults"`
	// contains filtered or unexported fields
}

PrincipalTagMapping stores the principal tag attribute map for a pool and provider.

type Provider

type Provider struct{}

Provider implements service.Provider for Amazon Cognito Federated Identities.

func (*Provider) Init

Init initializes the Cognito Identity service backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name.

type RoleAssumer

type RoleAssumer interface {
	AssumeRoleWithWebIdentity(roleARN, sessionName, webIdentityToken string) (*Credentials, error)
}

RoleAssumer mints credentials for a role from a Cognito OpenID token (STS AssumeRoleWithWebIdentity).

type RoleMapping

type RoleMapping struct {
	RulesConfiguration      *RulesConfiguration `json:"rulesConfiguration,omitempty"`
	Type                    string              `json:"type"`
	AmbiguousRoleResolution string              `json:"ambiguousRoleResolution,omitempty"`
}

RoleMapping configures how an identity pool assigns IAM roles for a provider.

type RulesConfiguration

type RulesConfiguration struct {
	Rules []MappingRule `json:"rules"`
}

RulesConfiguration holds an ordered list of claim-based mapping rules.

type TokenKeyResolver

type TokenKeyResolver interface {
	ResolveTokenKey(issuer, kid string) (key *rsa.PublicKey, hosted bool, err error)
}

TokenKeyResolver looks up the signing key of a login token issued by an emulator-hosted user pool. hosted is false when the issuer is not hosted by this emulator.

type UnprocessedIdentityID

type UnprocessedIdentityID struct {
	ErrorCode  string `json:"errorCode"`
	IdentityID string `json:"identityId"`
}

UnprocessedIdentityID represents a Cognito identity that could not be deleted.

Jump to

Keyboard shortcuts

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