Skip to content

Commit

Permalink
feat(amplify-category-api): prompt api key creation on amplify push (a…
Browse files Browse the repository at this point in the history
…ws-amplify#8124)

* feat(amplify-category-api): prompt api key create when invalid with sandbox mode

* test(amplify-category-api): add unit tests for provider utils

* test(amplify-category-api): fix test for adding api key prompt

* refactor(cli): refactor api key prompt

* refactor(amplify-category-api): add api key with gql compiled
  • Loading branch information
danielleadams authored and SwaySway committed Sep 24, 2021
1 parent 28d2748 commit e682189
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jest.mock('../../../provider-utils/awscloudformation/utils/amplify-meta-utils',

jest.mock('amplify-cli-core');

const fs_mock = (fs as unknown) as jest.Mocked<typeof fs>;
const fs_mock = fs as unknown as jest.Mocked<typeof fs>;
const writeTransformerConfiguration_mock = writeTransformerConfiguration as jest.MockedFunction<typeof writeTransformerConfiguration>;
const getAppSyncResourceName_mock = getAppSyncResourceName as jest.MockedFunction<typeof getAppSyncResourceName>;
const getAppSyncAuthConfig_mock = getAppSyncAuthConfig as jest.MockedFunction<typeof getAppSyncAuthConfig>;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { $TSContext } from 'amplify-cli-core';
import * as prompts from 'amplify-prompts';
import { promptToAddApiKey } from '../../../provider-utils/awscloudformation/prompt-to-add-api-key';
import * as walkthrough from '../../../provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough';
import * as cfnApiArtifactHandler from '../../../provider-utils/awscloudformation/cfn-api-artifact-handler';

jest.mock('../../../provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough', () => ({
askApiKeyQuestions: jest.fn(),
}));

jest.mock('../../../provider-utils/awscloudformation/cfn-api-artifact-handler', () => ({
getCfnApiArtifactHandler: jest.fn(() => {
return { updateArtifacts: jest.fn() };
}),
}));

jest.mock('amplify-prompts', () => ({
prompter: {
confirmContinue: jest.fn().mockImplementation(() => true),
},
}));

describe('prompt to add Api Key', () => {
it('runs through expected user flow: print info, update files', async () => {
const envName = 'envone';
const ctx = {
amplify: {
getEnvInfo() {
return { envName };
},
},
} as unknown as $TSContext;

jest.spyOn(prompts.prompter, 'confirmContinue');
jest.spyOn(walkthrough, 'askApiKeyQuestions');
jest.spyOn(cfnApiArtifactHandler, 'getCfnApiArtifactHandler');

await promptToAddApiKey(ctx);

expect(prompts.prompter.confirmContinue).toHaveBeenCalledWith('Would you like to create an API Key?');
expect(walkthrough.askApiKeyQuestions).toHaveBeenCalledTimes(1);
expect(cfnApiArtifactHandler.getCfnApiArtifactHandler).toHaveBeenCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
askAdditionalAuthQuestions,
} from '../../../../provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough';
import { authConfigHasApiKey, getAppSyncAuthConfig } from '../../../../provider-utils/awscloudformation/utils/amplify-meta-utils';
import { FeatureFlags, CLIEnvironmentProvider, FeatureFlagRegistration } from 'amplify-cli-core';
import { FeatureFlags } from 'amplify-cli-core';
jest.mock('../../../../provider-utils/awscloudformation/utils/amplify-meta-utils', () => ({
getAppSyncAuthConfig: jest.fn(),
authConfigHasApiKey: jest.fn(),
Expand Down
1 change: 1 addition & 0 deletions packages/amplify-category-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export {
processDockerConfig,
} from './provider-utils/awscloudformation/utils/containers-artifacts';
export { getContainers } from './provider-utils/awscloudformation/docker-compose';
export { promptToAddApiKey } from './provider-utils/awscloudformation/prompt-to-add-api-key';

const category = 'api';

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { $TSContext } from 'amplify-cli-core';
import { askApiKeyQuestions } from './service-walkthroughs/appSync-walkthrough';
import { authConfigToAppSyncAuthType } from './utils/auth-config-to-app-sync-auth-type-bi-di-mapper';
import { getCfnApiArtifactHandler } from './cfn-api-artifact-handler';
import { prompter } from 'amplify-prompts';

export async function promptToAddApiKey(context: $TSContext): Promise<void> {
if (await prompter.confirmContinue('Would you like to create an API Key?')) {
const apiKeyConfig = await askApiKeyQuestions();
const authConfig = [apiKeyConfig];

await getCfnApiArtifactHandler(context).updateArtifacts({
version: 1,
serviceModification: {
serviceName: 'AppSync',
additionalAuthTypes: authConfig.map(authConfigToAppSyncAuthType),
},
});
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export function defineGlobalSandboxMode(context: any): string {
import { $TSContext } from 'amplify-cli-core';

export function defineGlobalSandboxMode(context: $TSContext): string {
const envName = context.amplify.getEnvInfo().envName;

return `# This allows public create, read, update, and delete access for a limited time to all models via API Key.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import chalk from 'chalk';
import { $TSContext } from 'amplify-cli-core';
import { promptToAddApiKey } from 'amplify-category-api';
import { globalSandboxModeEnabled, showGlobalSandboxModeWarning } from './show-global-sandbox-mode-warning';
import { apiKeyIsActive, hasApiKey } from './get-api-key-config';

export async function promptSandboxModeApiKey(context: $TSContext): Promise<void> {
if (globalSandboxModeEnabled(context)) {
if (!apiKeyIsActive() || !hasApiKey()) {
context.print.info(`
⚠️ WARNING: Global Sandbox Mode has been enabled, which requires a valid API key. If
you'd like to disable, remove ${chalk.green('"type AMPLIFY_GLOBAL @allow_public_data_access_with_api_key"')}
from your GraphQL schema and run 'amplify push' again. If you'd like to proceed with
sandbox mode disabled in '${context.amplify.getEnvInfo().envName}', do not create an API Key.
`);
await promptToAddApiKey(context);
} else showGlobalSandboxModeWarning(context);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { initializeEnv } from '../../initialize-env';
import { getProviderPlugins } from './get-provider-plugins';
import { getEnvInfo } from './get-env-info';
import { EnvironmentDoesNotExistError, exitOnNextTick, stateManager, $TSAny, $TSContext } from 'amplify-cli-core';
import { promptSandboxModeApiKey } from './prompt-sandbox-mode-api-key';

export async function pushResources(
context: $TSContext,
Expand Down Expand Up @@ -67,6 +68,8 @@ export async function pushResources(
continueToPush = await context.amplify.confirmPrompt('Are you sure you want to continue?');
}

await promptSandboxModeApiKey(context);

if (continueToPush) {
try {
// Get current-cloud-backend's amplify-meta
Expand Down

0 comments on commit e682189

Please sign in to comment.