Skip to content

Commit

Permalink
Merge branch 'next/main' into chore/userpool-endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
jimblanc authored Oct 12, 2023
2 parents 5574b2e + e3c374e commit cfc4ea5
Show file tree
Hide file tree
Showing 54 changed files with 152 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { Cache, BrowserStorageCache } from '@aws-amplify/core';
import { isBrowser } from '@aws-amplify/core/internals/utils';
import { isBrowser, amplifyUuid } from '@aws-amplify/core/internals/utils';
import {
resolveCachedSession,
updateCachedSession,
Expand All @@ -11,11 +11,14 @@ import {
jest.mock('@aws-amplify/core');
jest.mock('@aws-amplify/core/internals/utils');

const mockAmplifyUuid = amplifyUuid as jest.Mock;

describe('Analytics service provider Personalize utils: cachedSession', () => {
const sessionIdCacheKey = '_awsct_sid.personalize';
const userIdCacheKey = '_awsct_uid.personalize';
const mockCache = Cache as jest.Mocked<typeof BrowserStorageCache>;
const mockIsBrowser = isBrowser as jest.Mock;
const mockUuid = 'b2bd676e-bc6b-40f4-bd86-1e31a07f7d10';

const mockSession = {
sessionId: 'sessionId0',
Expand All @@ -30,6 +33,7 @@ describe('Analytics service provider Personalize utils: cachedSession', () => {
beforeEach(() => {
mockCache.getItem.mockImplementation(key => mockCachedStorage[key]);
mockIsBrowser.mockReturnValue(false);
mockAmplifyUuid.mockReturnValue(mockUuid);
});

afterEach(() => {
Expand All @@ -47,7 +51,7 @@ describe('Analytics service provider Personalize utils: cachedSession', () => {
mockCache.getItem.mockImplementation(() => undefined);
const result = resolveCachedSession('trackingId0');
expect(result.sessionId).not.toBe(mockSession.sessionId);
expect(result.sessionId.length).toBeGreaterThan(0);
expect(result.sessionId).toEqual(mockUuid);
expect(result.userId).toBe(undefined);
});

Expand Down
2 changes: 0 additions & 2 deletions packages/analytics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@
],
"dependencies": {
"tslib": "^2.5.0",
"uuid": "^9.0.0",
"@aws-sdk/client-kinesis": "3.398.0",
"@aws-sdk/client-firehose": "3.398.0",
"@aws-sdk/client-personalize-events": "3.398.0",
Expand All @@ -105,7 +104,6 @@
"devDependencies": {
"@aws-amplify/core": "6.0.0",
"@aws-sdk/types": "3.398.0",
"@types/uuid": "^9.0.0",
"typescript": "5.0.2"
},
"jest": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

import { Cache } from '@aws-amplify/core';
import { isBrowser } from '@aws-amplify/core/internals/utils';
import { v4 as uuid } from 'uuid';
import { isBrowser, amplifyUuid } from '@aws-amplify/core/internals/utils';

const PERSONALIZE_CACHE_USERID = '_awsct_uid';
const PERSONALIZE_CACHE_SESSIONID = '_awsct_sid';
Expand All @@ -30,7 +29,7 @@ const setCache = (key: string, value: unknown) => {
export const resolveCachedSession = (trackingId: string) => {
let sessionId: string | undefined = getCache(PERSONALIZE_CACHE_SESSIONID);
if (!sessionId) {
sessionId = uuid();
sessionId = amplifyUuid();
setCache(PERSONALIZE_CACHE_SESSIONID, sessionId);
}

Expand Down Expand Up @@ -58,7 +57,7 @@ export const updateCachedSession = (
!!currentSessionId && !currentUserId && !!newUserId;

if (isRequireNewSession) {
const newSessionId = uuid();
const newSessionId = amplifyUuid();
setCache(PERSONALIZE_CACHE_SESSIONID, newSessionId);
setCache(PERSONALIZE_CACHE_USERID, newUserId);
} else if (isRequireUpdateSession) {
Expand Down
1 change: 0 additions & 1 deletion packages/api-graphql/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
"graphql": "15.8.0",
"tslib": "^1.8.0",
"url": "0.11.0",
"uuid": "^3.2.1",
"rxjs": "^7.8.1"
},
"size-limit": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { Observable, SubscriptionLike } from 'rxjs';
import { GraphQLError } from 'graphql';
import * as url from 'url';
import { v4 as uuid } from 'uuid';
import { Buffer } from 'buffer';
import { Hub, fetchAuthSession } from '@aws-amplify/core';
import { signRequest } from '@aws-amplify/core/internals/aws-client-utils';
Expand All @@ -17,6 +16,8 @@ import {
isNonRetryableError,
jitteredExponentialRetry,
DocumentType,
amplifyUuid,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';

import {
Expand Down Expand Up @@ -210,7 +211,7 @@ export class AWSAppSyncRealTimeProvider {
observer.complete();
} else {
let subscriptionStartActive = false;
const subscriptionId = uuid();
const subscriptionId = amplifyUuid();
const startSubscription = () => {
if (!subscriptionStartActive) {
subscriptionStartActive = true;
Expand Down Expand Up @@ -968,7 +969,7 @@ export class AWSAppSyncRealTimeProvider {
{
headers: request.headers,
method: request.method,
url: new URL(request.url),
url: new AmplifyUrl(request.url),
body: request.data,
},
{
Expand Down
3 changes: 2 additions & 1 deletion packages/api-graphql/src/internals/InternalGraphQLAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
CustomUserAgentDetails,
ConsoleLogger as Logger,
getAmplifyUserAgent,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';
import {
GraphQLAuthError,
Expand Down Expand Up @@ -304,7 +305,7 @@ export class InternalGraphQLAPIClass {
let response;
try {
const { body: responseBody } = await this._api.post({
url: new URL(endpoint),
url: new AmplifyUrl(endpoint),
options: {
headers,
body,
Expand Down
2 changes: 0 additions & 2 deletions packages/api-rest/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import './polyfills';

export { createCancellableOperation } from './createCancellableOperation';
export { resolveCredentials } from './resolveCredentials';
export { parseSigningInfo } from './parseSigningInfo';
Expand Down
10 changes: 7 additions & 3 deletions packages/api-rest/src/utils/resolveApiUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
// SPDX-License-Identifier: Apache-2.0

import { AmplifyClassV6 } from '@aws-amplify/core';
import {
AmplifyUrl,
AmplifyUrlSearchParams,
} from '@aws-amplify/core/internals/utils';
import {
RestApiError,
RestApiValidationErrorCode,
Expand All @@ -28,13 +32,13 @@ export const resolveApiUrl = (
const urlStr = amplify.getConfig()?.API?.REST?.[apiName]?.endpoint;
assertValidationError(!!urlStr, RestApiValidationErrorCode.InvalidApiName);
try {
const url = new URL(urlStr + path);
const url = new AmplifyUrl(urlStr + path);
if (queryParams) {
const mergedQueryParams = new URLSearchParams(url.searchParams);
const mergedQueryParams = new AmplifyUrlSearchParams(url.searchParams);
Object.entries(queryParams).forEach(([key, value]) => {
mergedQueryParams.set(key, value);
});
url.search = new URLSearchParams(mergedQueryParams).toString();
url.search = new AmplifyUrlSearchParams(mergedQueryParams).toString();
}
return url;
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
USER_AGENT_HEADER,
urlSafeDecode,
decodeJWT,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';
import { cacheCognitoTokens } from '../tokenProvider/cacheTokens';
import { CognitoUserPoolsTokenProvider } from '../tokenProvider';
Expand Down Expand Up @@ -148,7 +149,7 @@ async function handleCodeFlow({
}) {
/* Convert URL into an object with parameters as keys
{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */
const url = new URL(currentUrl);
const url = new AmplifyUrl(currentUrl);
let validatedState: string;
try {
validatedState = await validateStateFromURL(url);
Expand Down Expand Up @@ -242,7 +243,7 @@ async function handleImplicitFlow({
}) {
// hash is `null` if `#` doesn't exist on URL

const url = new URL(currentUrl);
const url = new AmplifyUrl(currentUrl);

const { idToken, accessToken, state, tokenType, expiresIn } = (
url.hash ?? '#'
Expand Down Expand Up @@ -330,7 +331,7 @@ async function handleAuthResponse({
preferPrivateSession?: boolean;
}) {
try {
const urlParams = new URL(currentUrl);
const urlParams = new AmplifyUrl(currentUrl);
const error = urlParams.searchParams.get('error');
const errorMessage = urlParams.searchParams.get('error_description');

Expand Down
2 changes: 0 additions & 2 deletions packages/auth/src/providers/cognito/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import './polyfills';

export { signUp } from './apis/signUp';
export { resetPassword } from './apis/resetPassword';
export { confirmResetPassword } from './apis/confirmResetPassword';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ import {
getRetryDecider,
jitteredBackoff,
} from '@aws-amplify/core/internals/aws-client-utils';
import { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';
import {
getAmplifyUserAgent,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';
import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers';

/**
Expand All @@ -29,12 +32,12 @@ const SERVICE_NAME = 'cognito-idp';
const endpointResolver = ({ region }: EndpointResolverOptions) => {
const authConfig = Amplify.getConfig().Auth?.Cognito;
const customURL = authConfig?.userPoolEndpoint;
const defaultURL = new URL(
const defaultURL = new AmplifyUrl(
`https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`
);

return {
url: customURL ? new URL(customURL) : defaultURL,
url: customURL ? new AmplifyUrl(customURL) : defaultURL,
};
};

Expand Down
9 changes: 7 additions & 2 deletions packages/auth/src/providers/cognito/utils/clients/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ import {
getRetryDecider,
jitteredBackoff,
} from '@aws-amplify/core/internals/aws-client-utils';
import { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';
import {
getAmplifyUserAgent,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';
import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers';

/**
Expand All @@ -26,7 +29,9 @@ const SERVICE_NAME = 'cognito-idp';
* The endpoint resolver function that returns the endpoint URL for a given region.
*/
const endpointResolver = ({ region }: EndpointResolverOptions) => ({
url: new URL(`https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`),
url: new AmplifyUrl(
`https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`
),
});

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/auth/src/providers/cognito/utils/signInHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
AuthAction,
assertTokenProviderConfig,
base64Encoder,
AmplifyUrl,
} from '@aws-amplify/core/internals/utils';
import { AuthenticationHelper } from './srp/AuthenticationHelper';
import { BigInteger } from './srp/BigInteger';
Expand Down Expand Up @@ -840,7 +841,7 @@ export function getTOTPSetupDetails(
accountName ?? username
}?secret=${secretCode}&issuer=${appName}`;

return new URL(totpUri);
return new AmplifyUrl(totpUri);
},
};
}
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/Signer/Signer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
signRequest,
TOKEN_QUERY_PARAM,
} from '../clients/middleware/signing/signer/signatureV4';
import { AmplifyUrl } from '../utils/amplifyUrl';

const IOT_SERVICE_NAME = 'iotdevicegateway';
// Best practice regex to parse the service and region from an AWS endpoint
Expand Down Expand Up @@ -75,7 +76,7 @@ export class Signer {
const requestToSign = {
...request,
body: request.data,
url: new URL(request.url),
url: new AmplifyUrl(request.url),
};

const options = getOptions(requestToSign, accessInfo, serviceInfo);
Expand Down Expand Up @@ -121,7 +122,7 @@ export class Signer {
const presignable = {
body,
method,
url: new URL(urlToSign),
url: new AmplifyUrl(urlToSign),
};

const options = getOptions(
Expand Down
5 changes: 4 additions & 1 deletion packages/core/src/awsClients/cognitoIdentity/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '../../clients/middleware/retry';
import { getAmplifyUserAgent } from '../../Platform';
import { observeFrameworkChanges } from '../../Platform/detectFramework';
import { AmplifyUrl } from '../../utils/amplifyUrl';

/**
* The service name used to sign requests if the API requires authentication.
Expand All @@ -29,7 +30,9 @@ const SERVICE_NAME = 'cognito-identity';
* The endpoint resolver function that returns the endpoint URL for a given region.
*/
const endpointResolver = ({ region }: EndpointResolverOptions) => ({
url: new URL(`https://cognito-identity.${region}.${getDnsSuffix(region)}`),
url: new AmplifyUrl(
`https://cognito-identity.${region}.${getDnsSuffix(region)}`
),
});

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/awsClients/pinpoint/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { parseJsonError } from '../../clients/serde/json';
import type { EndpointResolverOptions, Headers } from '../../clients/types';
import { getAmplifyUserAgent } from '../../Platform';
import { AmplifyUrl } from '../../utils/amplifyUrl';

/**
* The service name used to sign requests if the API requires authentication.
Expand All @@ -19,7 +20,7 @@ const SERVICE_NAME = 'mobiletargeting';
* The endpoint resolver function that returns the endpoint URL for a given region.
*/
const endpointResolver = ({ region }: EndpointResolverOptions) => ({
url: new URL(`https://pinpoint.${region}.${getDnsSuffix(region)}`),
url: new AmplifyUrl(`https://pinpoint.${region}.${getDnsSuffix(region)}`),
});

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/awsClients/pinpoint/getInAppMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
GetInAppMessagesCommandInput as GetInAppMessagesInput,
GetInAppMessagesCommandOutput as GetInAppMessagesOutput,
} from './types';
import { AmplifyUrl } from '../../utils/amplifyUrl';

export type { GetInAppMessagesInput, GetInAppMessagesOutput };

Expand All @@ -23,7 +24,7 @@ const getInAppMessagesSerializer = (
endpoint: Endpoint
): HttpRequest => {
const headers = getSharedHeaders();
const url = new URL(endpoint.url);
const url = new AmplifyUrl(endpoint.url);
url.pathname = `v1/apps/${extendedEncodeURIComponent(
ApplicationId
)}/endpoints/${extendedEncodeURIComponent(EndpointId)}/inappmessages`;
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/awsClients/pinpoint/putEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
PutEventsCommandInput as PutEventsInput,
PutEventsCommandOutput as PutEventsOutput,
} from './types';
import { AmplifyUrl } from '../../utils/amplifyUrl';

export type { PutEventsInput, PutEventsOutput };

Expand All @@ -25,7 +26,7 @@ const putEventsSerializer = (
): HttpRequest => {
assert(!!ApplicationId, PinpointValidationErrorCode.NoAppId);
const headers = getSharedHeaders();
const url = new URL(endpoint.url);
const url = new AmplifyUrl(endpoint.url);
url.pathname = `v1/apps/${extendedEncodeURIComponent(ApplicationId)}/events`;
const body = JSON.stringify(EventsRequest ?? {});
return { method: 'POST', headers, url, body };
Expand Down
Loading

0 comments on commit cfc4ea5

Please sign in to comment.