@aws-amplify/auth
Version:
Auth category of aws-amplify
1 lines • 14.5 kB
Source Map (JSON)
{"version":3,"file":"credentialsProvider.mjs","sources":["../../../../../src/providers/cognito/credentialsProvider/credentialsProvider.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, createGetCredentialsForIdentityClient, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { assertIdTokenInAuthTokens } from '../utils/types';\nimport { createCognitoIdentityPoolEndpointResolver } from '../factories';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider';\nimport { formLoginsMap } from './utils';\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nexport class CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const getCredentialsForIdentity = createGetCredentialsForIdentityClient({\n endpointResolver: createCognitoIdentityPoolEndpointResolver({\n endpointOverride: authConfig.identityPoolEndpoint,\n }),\n });\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n let clientResult;\n try {\n clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n }\n catch (e) {\n assertServiceError(e);\n throw new AuthError(e);\n }\n if (clientResult?.Credentials?.AccessKeyId &&\n clientResult?.Credentials?.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const getCredentialsForIdentity = createGetCredentialsForIdentityClient({\n endpointResolver: createCognitoIdentityPoolEndpointResolver({\n endpointOverride: authConfig.identityPoolEndpoint,\n }),\n });\n let clientResult;\n try {\n clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n }\n catch (e) {\n assertServiceError(e);\n throw new AuthError(e);\n }\n if (clientResult?.Credentials?.AccessKeyId &&\n clientResult?.Credentials?.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n // note: the following call removes guest identityId from the persistent store (localStorage)\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'primary',\n });\n }\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;AACA;AAUA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,4BAA4B,CAAC;AAC9D,MAAM,eAAe,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAChC,MAAM,0CAA0C,CAAC;AACxD,IAAI,WAAW,CAAC,eAAe,EAAE;AACjC,QAAQ,IAAI,CAAC,uBAAuB,GAAG,CAAC;AACxC,QAAQ,IAAI,CAAC,gBAAgB,GAAG,eAAe;AAC/C;AACA,IAAI,MAAM,6BAA6B,GAAG;AAC1C,QAAQ,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC;AAC/D,QAAQ,IAAI,CAAC,yBAAyB,GAAG,SAAS;AAClD,QAAQ,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,EAAE;AACrD;AACA,IAAI,MAAM,gBAAgB,GAAG;AAC7B,QAAQ,MAAM,CAAC,KAAK,CAAC,oCAAoC,CAAC;AAC1D,QAAQ,IAAI,CAAC,yBAAyB,GAAG,SAAS;AAClD;AACA,IAAI,MAAM,2BAA2B,CAAC,qBAAqB,EAAE;AAC7D,QAAQ,MAAM,eAAe,GAAG,qBAAqB,CAAC,aAAa;AACnE,QAAQ,MAAM,EAAE,MAAM,EAAE,GAAG,qBAAqB;AAChD,QAAQ,MAAM,EAAE,UAAU,EAAE,GAAG,qBAAqB;AACpD,QAAQ,IAAI;AACZ,YAAY,0BAA0B,CAAC,UAAU,EAAE,OAAO,CAAC;AAC3D;AACA,QAAQ,MAAM;AACd;AACA,YAAY;AACZ;AACA,QAA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