/
index.ts
319 lines (289 loc) · 12.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import {
$TSContext,
$TSObject,
AmplifyCategories,
AmplifySupportedService,
buildOverrideDir,
exitOnNextTick,
pathManager,
stateManager,
} from 'amplify-cli-core';
import { printer } from 'amplify-prompts';
import { validateAddApiRequest, validateUpdateApiRequest } from 'amplify-util-headless-input';
import * as fs from 'fs-extra';
import * as path from 'path';
import { run } from './commands/api/console';
import { getAppSyncAuthConfig, getAppSyncResourceName } from './provider-utils/awscloudformation//utils/amplify-meta-utils';
import { provider } from './provider-utils/awscloudformation/aws-constants';
import { ApigwStackTransform } from './provider-utils/awscloudformation/cdk-stack-builder';
import { getCfnApiArtifactHandler } from './provider-utils/awscloudformation/cfn-api-artifact-handler';
import { askAuthQuestions } from './provider-utils/awscloudformation/service-walkthroughs/appSync-walkthrough';
import { authConfigToAppSyncAuthType } from './provider-utils/awscloudformation/utils/auth-config-to-app-sync-auth-type-bi-di-mapper';
import { checkAppsyncApiResourceMigration } from './provider-utils/awscloudformation/utils/check-appsync-api-migration';
import { getAppSyncApiResourceName } from './provider-utils/awscloudformation/utils/getAppSyncApiName';
export { NETWORK_STACK_LOGICAL_ID } from './category-constants';
export { addAdminQueriesApi, updateAdminQueriesApi } from './provider-utils/awscloudformation/';
export { DEPLOYMENT_MECHANISM } from './provider-utils/awscloudformation/base-api-stack';
export { convertDeperecatedRestApiPaths } from './provider-utils/awscloudformation/convert-deprecated-apigw-paths';
export { getContainers } from './provider-utils/awscloudformation/docker-compose';
export { EcsAlbStack } from './provider-utils/awscloudformation/ecs-alb-stack';
export { EcsStack } from './provider-utils/awscloudformation/ecs-apigw-stack';
export { promptToAddApiKey } from './provider-utils/awscloudformation/prompt-to-add-api-key';
export {
ApiResource,
generateContainersArtifacts,
processDockerConfig,
} from './provider-utils/awscloudformation/utils/containers-artifacts';
export { getAuthConfig } from './provider-utils/awscloudformation/utils/get-appsync-auth-config';
export { getResolverConfig } from './provider-utils/awscloudformation/utils/get-appsync-resolver-config';
export { getGitHubOwnerRepoFromPath } from './provider-utils/awscloudformation/utils/github';
const category = AmplifyCategories.API;
const categories = 'categories';
export async function console(context: $TSContext) {
await run(context);
}
export async function migrate(context: $TSContext, serviceName?: string) {
const { projectPath } = context?.migrationInfo ?? { projectPath: pathManager.findProjectRoot() };
const amplifyMeta = stateManager.getMeta(projectPath);
const migrateResourcePromises = [];
for (const categoryName of Object.keys(amplifyMeta)) {
if (categoryName === category) {
for (const resourceName of Object.keys(amplifyMeta[category])) {
try {
if (amplifyMeta[category][resourceName].providerPlugin) {
const providerController = await import(
path.join(__dirname, 'provider-utils', amplifyMeta[category][resourceName].providerPlugin, 'index')
);
if (providerController) {
if (!serviceName || serviceName === amplifyMeta[category][resourceName].service) {
migrateResourcePromises.push(
providerController.migrateResource(context, projectPath, amplifyMeta[category][resourceName].service, resourceName),
);
}
}
} else {
printer.error(`Provider not configured for ${category}: ${resourceName}`);
}
} catch (e) {
printer.warn(`Could not run migration for ${category}: ${resourceName}`);
throw e;
}
}
}
}
for (const migrateResourcePromise of migrateResourcePromises) {
await migrateResourcePromise;
}
}
export async function initEnv(context: $TSContext) {
const datasource = 'Aurora Serverless';
const service = 'service';
const rdsInit = 'rdsInit';
const rdsRegion = 'rdsRegion';
const rdsClusterIdentifier = 'rdsClusterIdentifier';
const rdsSecretStoreArn = 'rdsSecretStoreArn';
const rdsDatabaseName = 'rdsDatabaseName';
const { amplify } = context;
/**
* Check if we need to do the walkthrough, by looking to see if previous environments have
* configured an RDS datasource
*/
const backendConfigFilePath = pathManager.getBackendConfigFilePath();
// If this is a mobile hub migrated project without locally added resources then there is no
// backend config exists yet.
if (!fs.existsSync(backendConfigFilePath)) {
return;
}
const backendConfig = stateManager.getBackendConfig();
if (!backendConfig[category]) {
return;
}
let resourceName;
const apis = Object.keys(backendConfig[category]);
for (const api of apis) {
if (backendConfig[category][api][service] === AmplifySupportedService.APPSYNC) {
resourceName = api;
break;
}
}
// If an AppSync API does not exist, no need to prompt for rds datasource
if (!resourceName) {
return;
}
// If an AppSync API has not been initialized with RDS, no need to prompt
if (!backendConfig[category][resourceName][rdsInit]) {
return;
}
const providerController = await import(path.join(__dirname, 'provider-utils', provider, 'index'));
if (!providerController) {
printer.error('Provider not configured for this category');
return;
}
/**
* Check team provider info to ensure it hasn't already been created for current env
*/
const currEnv = amplify.getEnvInfo().envName;
const teamProviderInfo = stateManager.getTeamProviderInfo();
if (
teamProviderInfo[currEnv][categories] &&
teamProviderInfo[currEnv][categories][category] &&
teamProviderInfo[currEnv][categories][category][resourceName] &&
teamProviderInfo[currEnv][categories][category][resourceName] &&
teamProviderInfo[currEnv][categories][category][resourceName][rdsRegion]
) {
return;
}
/**
* Execute the walkthrough
*/
return providerController
.addDatasource(context, category, datasource)
.then(answers => {
/**
* Write the new answers to the team provider info
*/
if (!teamProviderInfo[currEnv][categories]) {
teamProviderInfo[currEnv][categories] = {};
}
if (!teamProviderInfo[currEnv][categories][category]) {
teamProviderInfo[currEnv][categories][category] = {};
}
if (!teamProviderInfo[currEnv][categories][category][resourceName]) {
teamProviderInfo[currEnv][categories][category][resourceName] = {};
}
teamProviderInfo[currEnv][categories][category][resourceName][rdsRegion] = answers.region;
teamProviderInfo[currEnv][categories][category][resourceName][rdsClusterIdentifier] = answers.dbClusterArn;
teamProviderInfo[currEnv][categories][category][resourceName][rdsSecretStoreArn] = answers.secretStoreArn;
teamProviderInfo[currEnv][categories][category][resourceName][rdsDatabaseName] = answers.databaseName;
stateManager.setTeamProviderInfo(undefined, teamProviderInfo);
})
.then(() => {
context.amplify.executeProviderUtils(context, 'awscloudformation', 'compileSchema', { forceCompile: true });
});
}
export async function getPermissionPolicies(context: $TSContext, resourceOpsMapping: $TSObject) {
const amplifyMeta = stateManager.getMeta();
const permissionPolicies = [];
const resourceAttributes = [];
await Promise.all(
Object.keys(resourceOpsMapping).map(async resourceName => {
try {
const providerName = amplifyMeta[category][resourceName].providerPlugin;
if (providerName) {
const providerController = await import(path.join(__dirname, 'provider-utils', providerName, 'index'));
const { policy, attributes } = await providerController.getPermissionPolicies(
context,
amplifyMeta[category][resourceName].service,
resourceName,
resourceOpsMapping[resourceName],
);
permissionPolicies.push(policy);
resourceAttributes.push({ resourceName, attributes, category });
} else {
printer.error(`Provider not configured for ${category}: ${resourceName}`);
}
} catch (e) {
printer.warn(`Could not get policies for ${category}: ${resourceName}`);
throw e;
}
}),
);
return { permissionPolicies, resourceAttributes };
}
export async function executeAmplifyCommand(context: $TSContext) {
let commandPath = path.normalize(path.join(__dirname, 'commands'));
if (context.input.command === 'help') {
commandPath = path.join(commandPath, category);
} else {
commandPath = path.join(commandPath, category, context.input.command);
}
const commandModule = await import(commandPath);
try {
await commandModule.run(context);
} catch (error) {
if (error) {
printer.error(error.message || error);
if (error.stack) {
printer.debug(error.stack);
}
await context.usageData.emitError(error);
}
process.exitCode = 1;
}
}
export const executeAmplifyHeadlessCommand = async (context: $TSContext, headlessPayload: string) => {
switch (context.input.command) {
case 'add':
await getCfnApiArtifactHandler(context).createArtifacts(await validateAddApiRequest(headlessPayload));
break;
case 'update':
const resourceName = await getAppSyncApiResourceName(context);
await checkAppsyncApiResourceMigration(context, resourceName, true);
await getCfnApiArtifactHandler(context).updateArtifacts(await validateUpdateApiRequest(headlessPayload));
break;
default:
printer.error(`Headless mode for ${context.input.command} api is not implemented yet`);
}
};
export async function handleAmplifyEvent(context: $TSContext, args) {
printer.info(`${category} handleAmplifyEvent to be implemented`);
printer.info(`Received event args ${args}`);
}
export async function addGraphQLAuthorizationMode(context: $TSContext, args: $TSObject) {
const { authType, printLeadText, authSettings } = args;
const meta = stateManager.getMeta();
const apiName = getAppSyncResourceName(meta);
if (!apiName) {
return;
}
const authConfig = getAppSyncAuthConfig(meta);
const addAuthConfig = await askAuthQuestions(authType, context, printLeadText, authSettings);
authConfig.additionalAuthenticationProviders.push(addAuthConfig);
await context.amplify.updateamplifyMetaAfterResourceUpdate(category, apiName, 'output', { authConfig });
await context.amplify.updateBackendConfigAfterResourceUpdate(category, apiName, 'output', { authConfig });
await getCfnApiArtifactHandler(context).updateArtifacts(
{
version: 1,
serviceModification: {
serviceName: 'AppSync',
additionalAuthTypes: authConfig.additionalAuthenticationProviders.map(authConfigToAppSyncAuthType),
},
},
{
skipCompile: false,
},
);
return addAuthConfig;
}
export async function transformCategoryStack(context: $TSContext, resource: $TSObject) {
if (resource.service === AmplifySupportedService.APPSYNC) {
if (canResourceBeTransformed(resource.resourceName)) {
const backendDir = pathManager.getBackendDirPath();
const overrideDir = path.join(backendDir, resource.category, resource.resourceName);
const isBuild = await buildOverrideDir(backendDir, overrideDir).catch(error => {
printer.error(`Build error : ${error.message}`);
throw new Error(error);
});
await context.amplify.invokePluginMethod(context, 'awscloudformation', undefined, 'compileSchema', [
context,
{
forceCompile: true,
overrideConfig: {
overrideFlag: isBuild,
overrideDir: overrideDir,
resourceName: resource.resourceName,
},
},
]);
}
} else if (resource.service === AmplifySupportedService.APIGW) {
if (canResourceBeTransformed(resource.resourceName)) {
// Rebuild CFN
const apigwStack = new ApigwStackTransform(context, resource.resourceName);
apigwStack.transform();
}
}
}
function canResourceBeTransformed(resourceName: string) {
return stateManager.resourceInputsJsonExists(undefined, AmplifyCategories.API, resourceName);
}