@geek-fun/serverlessinsight 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +94 -0
  4. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +47 -27
  5. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  6. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +35 -73
  7. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +148 -0
  8. package/AGENTS.md +29 -0
  9. package/dist/package.json +1 -1
  10. package/dist/src/commands/deploy.js +1 -0
  11. package/dist/src/commands/index.js +6 -2
  12. package/dist/src/commands/plan.js +1 -0
  13. package/dist/src/common/aliyunClient/ecsOperations.js +70 -1
  14. package/dist/src/common/aliyunClient/nasOperations.js +21 -0
  15. package/dist/src/common/aliyunClient/ramOperations.js +116 -15
  16. package/dist/src/common/aliyunClient/slsOperations.js +16 -3
  17. package/dist/src/common/concurrency.js +30 -0
  18. package/dist/src/common/context.js +3 -0
  19. package/dist/src/common/dependencyGraph/graph.js +5 -0
  20. package/dist/src/common/iacHelper.js +3 -1
  21. package/dist/src/common/iamStatements.js +21 -1
  22. package/dist/src/common/index.js +5 -0
  23. package/dist/src/common/nameBuilder.js +12 -1
  24. package/dist/src/common/planCompare.js +62 -0
  25. package/dist/src/common/planFormatter.js +15 -3
  26. package/dist/src/common/refreshCache.js +32 -0
  27. package/dist/src/common/refreshPlanner.js +105 -0
  28. package/dist/src/common/tencentClient/camOperations.js +24 -12
  29. package/dist/src/common/tencentClient/clsOperations.js +27 -3
  30. package/dist/src/common/tencentClient/tdsqlcOperations.js +22 -0
  31. package/dist/src/common/throttleRetry.js +56 -0
  32. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  33. package/dist/src/common/volcengineClient/tlsOperations.js +12 -4
  34. package/dist/src/lang/en.js +23 -0
  35. package/dist/src/lang/zh-CN.js +22 -0
  36. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  37. package/dist/src/stack/aliyunStack/apigwPlanner.js +75 -7
  38. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  39. package/dist/src/stack/aliyunStack/apigwTypes.js +86 -5
  40. package/dist/src/stack/aliyunStack/databasePlanner.js +26 -62
  41. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  42. package/dist/src/stack/aliyunStack/esServerlessTypes.js +50 -1
  43. package/dist/src/stack/aliyunStack/fc3Executor.js +5 -3
  44. package/dist/src/stack/aliyunStack/fc3Planner.js +299 -12
  45. package/dist/src/stack/aliyunStack/fc3Resource.js +358 -34
  46. package/dist/src/stack/aliyunStack/fc3Types.js +61 -1
  47. package/dist/src/stack/aliyunStack/ossPlanner.js +21 -63
  48. package/dist/src/stack/aliyunStack/ossTypes.js +25 -1
  49. package/dist/src/stack/aliyunStack/rdsTypes.js +38 -1
  50. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  51. package/dist/src/stack/aliyunStack/tablestorePlanner.js +20 -74
  52. package/dist/src/stack/aliyunStack/tablestoreTypes.js +33 -1
  53. package/dist/src/stack/scfStack/cosPlanner.js +30 -50
  54. package/dist/src/stack/scfStack/cosTypes.js +29 -1
  55. package/dist/src/stack/scfStack/esServerlessPlanner.js +21 -54
  56. package/dist/src/stack/scfStack/esServerlessTypes.js +13 -1
  57. package/dist/src/stack/scfStack/scfExecutor.js +5 -3
  58. package/dist/src/stack/scfStack/scfPlanner.js +72 -51
  59. package/dist/src/stack/scfStack/scfResource.js +109 -12
  60. package/dist/src/stack/scfStack/scfTypes.js +35 -1
  61. package/dist/src/stack/scfStack/sharedLogset.js +12 -3
  62. package/dist/src/stack/scfStack/tdsqlcPlanner.js +37 -55
  63. package/dist/src/stack/scfStack/tdsqlcTypes.js +21 -1
  64. package/dist/src/stack/volcengineStack/apigwPlanner.js +59 -8
  65. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  66. package/dist/src/stack/volcengineStack/apigwTypes.js +44 -8
  67. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  68. package/dist/src/stack/volcengineStack/tosPlanner.js +28 -55
  69. package/dist/src/stack/volcengineStack/tosTypes.js +18 -1
  70. package/dist/src/stack/volcengineStack/vefaasExecutor.js +5 -3
  71. package/dist/src/stack/volcengineStack/vefaasPlanner.js +119 -10
  72. package/dist/src/stack/volcengineStack/vefaasResource.js +112 -13
  73. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  74. package/dist/src/validator/semanticValidation.js +41 -0
  75. package/dist/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +1 -1
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
6
+ exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveFc3ExecutionStatements = exports.resolveRoleGrant = void 0;
7
7
  const aliyunClient_1 = require("../../common/aliyunClient");
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
@@ -11,7 +11,11 @@ const common_1 = require("../../common");
11
11
  const constants_1 = require("../../common/constants");
12
12
  const types_1 = require("../../types");
13
13
  const fc3Types_1 = require("./fc3Types");
14
+ const slsOperations_1 = require("../../common/aliyunClient/slsOperations");
15
+ const ecsOperations_1 = require("../../common/aliyunClient/ecsOperations");
14
16
  const logger_1 = require("../../common/logger");
17
+ const iamStatements_1 = require("../../common/iamStatements");
18
+ const ramOperations_1 = require("../../common/aliyunClient/ramOperations");
15
19
  const lang_1 = require("../../lang");
16
20
  const ownershipTag_1 = require("../ownershipTag");
17
21
  const alreadyExists_1 = require("../alreadyExists");
@@ -22,10 +26,155 @@ const delay = async (ms) => {
22
26
  setTimeout(resolve, ms);
23
27
  });
24
28
  };
25
- const getTrustedServicesForFunction = (context, fnKey) => {
26
- const fnHasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => String(trigger.backend) === `\${functions.${fnKey}}`));
29
+ const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
30
+ const getTrustedServicesForFunction = (context, fn) => {
31
+ const templateFunctions = context.iac?.functions ?? [];
32
+ const templateKeys = new Set(templateFunctions.map((templateFn) => templateFn.key));
33
+ const templateNames = new Set(templateFunctions.map((templateFn) => templateFn.name));
34
+ const fnHasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => {
35
+ const backend = String(trigger.backend);
36
+ if (backend === `\${functions.${fn.key}}` || backend === fn.name) {
37
+ return true;
38
+ }
39
+ // External backend (issue #227): the gateway assumes this managed role as
40
+ // its invocation identity, so bare external names still require apigateway trust.
41
+ return (!TEMPLATE_REF_PATTERN.test(backend) &&
42
+ !templateKeys.has(backend) &&
43
+ !templateNames.has(backend));
44
+ }));
27
45
  return fnHasApiGateway ? ['fc.aliyuncs.com', 'apigateway.aliyuncs.com'] : ['fc.aliyuncs.com'];
28
46
  };
47
+ const FC3_LOG_ACTIONS = [
48
+ 'log:PostLogStoreLogs',
49
+ 'log:CreateLogStore',
50
+ 'log:GetLogStore',
51
+ 'log:ListShards',
52
+ 'log:GetCursorOrData',
53
+ ];
54
+ const FC3_ENI_ACTIONS = [
55
+ 'ecs:CreateNetworkInterface',
56
+ 'ecs:DeleteNetworkInterface',
57
+ 'ecs:DescribeNetworkInterfaces',
58
+ 'ecs:CreateNetworkInterfacePermission',
59
+ 'ecs:DescribeNetworkInterfacePermissions',
60
+ 'ecs:DeleteNetworkInterfacePermission',
61
+ ];
62
+ const buildDefaultRoleName = common_1.buildFunctionRoleName;
63
+ const buildFc3CertName = (service, stage) => `${service}-${stage}-fc3-domain`;
64
+ const collectRolePeers = (state, context, roleId) => {
65
+ const peers = [];
66
+ for (const [logicalId, resourceState] of Object.entries((0, common_1.getAllResources)(state))) {
67
+ if (!logicalId.startsWith('functions.'))
68
+ continue;
69
+ const roleInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
70
+ if (roleInstance?.id !== roleId)
71
+ continue;
72
+ const fn = context.iac?.functions?.find((candidate) => candidate.key === logicalId.slice('functions.'.length));
73
+ if (!fn)
74
+ continue;
75
+ const logstoreInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
76
+ const [project, logstore] = logstoreInstance?.id?.split('/') ?? [];
77
+ peers.push({ fn, ...(project && logstore ? { logConfig: { project, logstore } } : {}) });
78
+ }
79
+ return peers;
80
+ };
81
+ const unionTrustedServices = (serviceLists) => [
82
+ ...new Set(serviceLists.flat()),
83
+ ];
84
+ /**
85
+ * Legacy shared roles serve every function that recorded them, so their trust,
86
+ * derived policy and CUSTOM statements must be the union across those
87
+ * functions — a single function's update would otherwise strip another
88
+ * function's requirements.
89
+ */
90
+ const resolveRoleGrant = (context, state, fn, logConfig, roleId) => {
91
+ const storedPeers = state ? collectRolePeers(state, context, roleId) : [];
92
+ const currentStored = storedPeers.find((peer) => peer.fn.key === fn.key);
93
+ const peers = currentStored
94
+ ? [...storedPeers]
95
+ : [{ fn, ...(logConfig ? { logConfig } : {}) }, ...storedPeers];
96
+ const ownCustoms = fn.iam?.role && typeof fn.iam.role !== 'string' ? fn.iam.role.statements : undefined;
97
+ const peerCustoms = peers
98
+ .filter((peer) => peer.fn.key !== fn.key)
99
+ .map((peer) => peer.fn.iam?.role && typeof peer.fn.iam.role !== 'string'
100
+ ? peer.fn.iam.role.statements
101
+ : undefined)
102
+ .filter((statements) => Boolean(statements?.length));
103
+ const sharedRole = peers.length > 1;
104
+ const customStatements = sharedRole
105
+ ? (0, iamStatements_1.unionPolicyStatements)([ownCustoms ?? [], ...peerCustoms])
106
+ : ownCustoms;
107
+ if (!sharedRole) {
108
+ return {
109
+ trustedServices: getTrustedServicesForFunction(context, fn),
110
+ executionStatements: (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig),
111
+ customStatements,
112
+ };
113
+ }
114
+ return {
115
+ trustedServices: unionTrustedServices(peers.map((peer) => getTrustedServicesForFunction(context, peer.fn))),
116
+ executionStatements: (0, iamStatements_1.unionPolicyStatements)(peers.map((peer) => (0, exports.deriveFc3ExecutionStatements)(peer.fn, context, peer.logConfig))),
117
+ customStatements,
118
+ };
119
+ };
120
+ exports.resolveRoleGrant = resolveRoleGrant;
121
+ const buildFcFunctionArn = (context, functionName) => context.accountId
122
+ ? `acs:fc:${context.region}:${context.accountId}:functions/${functionName}`
123
+ : undefined;
124
+ const isTemplateFunctionBackend = (context, backend) => {
125
+ if (/^\$\{functions\./.test(backend))
126
+ return true;
127
+ return (context.iac?.functions ?? []).some((candidate) => candidate.key === backend || candidate.name === backend);
128
+ };
129
+ /**
130
+ * Strict invoke scope (issue #228): this role may invoke its own function plus
131
+ * the service's external backend functions (the gateway may assume any managed
132
+ * role as the fallback identity for external APIs). Falls back to '*' only
133
+ * when the account Id is unknown — never wrong-permissions.
134
+ */
135
+ const resolveFc3InvokeResources = (fn, context) => {
136
+ const ownArn = buildFcFunctionArn(context, fn.name);
137
+ if (!ownArn)
138
+ return ['*'];
139
+ const resources = new Set([ownArn]);
140
+ for (const event of context.iac?.events ?? []) {
141
+ for (const trigger of event.triggers ?? []) {
142
+ const backend = String(trigger.backend ?? '');
143
+ if (!backend || isTemplateFunctionBackend(context, backend))
144
+ continue;
145
+ const externalArn = buildFcFunctionArn(context, backend);
146
+ if (externalArn)
147
+ resources.add(externalArn);
148
+ }
149
+ }
150
+ return [...resources];
151
+ };
152
+ const deriveFc3ExecutionStatements = (fn, context, logConfig) => {
153
+ const statements = [
154
+ {
155
+ effect: 'Allow',
156
+ action: ['fc:InvokeFunction'],
157
+ resource: resolveFc3InvokeResources(fn, context),
158
+ },
159
+ {
160
+ effect: 'Allow',
161
+ action: FC3_LOG_ACTIONS,
162
+ resource: logConfig && context.accountId
163
+ ? [
164
+ `acs:log:${context.region}:${context.accountId}:project/${logConfig.project}/logstore/${logConfig.logstore}`,
165
+ ]
166
+ : ['*'],
167
+ },
168
+ ];
169
+ if (fn.network) {
170
+ statements.push({ effect: 'Allow', action: FC3_ENI_ACTIONS, resource: ['*'] }, { effect: 'Allow', action: ['vpc:DescribeVSwitchAttributes'], resource: ['*'] });
171
+ }
172
+ if (fn.storage?.nas && fn.storage.nas.length > 0) {
173
+ statements.push({ effect: 'Allow', action: ['nas:*'], resource: ['*'] });
174
+ }
175
+ return statements;
176
+ };
177
+ exports.deriveFc3ExecutionStatements = deriveFc3ExecutionStatements;
29
178
  const isRecoverableCreateError = (error) => {
30
179
  const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
31
180
  ? error.code.toLowerCase()
@@ -145,7 +294,7 @@ const buildHttpTriggerConfig = (trigger) => {
145
294
  ...(disableURLInternet !== undefined ? { disableURLInternet } : {}),
146
295
  };
147
296
  };
148
- const createDependentResources = async (context, fn, serviceName, existingInstances = [], state) => {
297
+ const createDependentResources = async (context, fn, serviceName, existingInstances = [], state, options) => {
149
298
  const client = (0, aliyunClient_1.createAliyunClient)(context);
150
299
  const instances = [];
151
300
  let logConfig;
@@ -156,6 +305,10 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
156
305
  const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
157
306
  const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
158
307
  const hasNasResources = existingInstances.some((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
308
+ // Callers that reconcile the role themselves (updateResource) opt out so the
309
+ // helper neither re-creates a just-repaired role nor rewrites the execution
310
+ // policy from a grant derived without the caller's logConfig.
311
+ const skipRole = options?.skipRole === true;
159
312
  if (fn.log) {
160
313
  if (hasSlsProject) {
161
314
  const slsProjectInstance = existingInstances.find((i) => i.type === 'ALIYUN_SLS_PROJECT');
@@ -168,7 +321,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
168
321
  }
169
322
  else {
170
323
  const shared = await (0, sharedLogProject_1.ensureSharedSlsProject)(context, client, state);
171
- const logstore = await (0, sharedLogProject_1.ensureFunctionLogstore)(context, client, shared.projectName);
324
+ const logstore = await (0, sharedLogProject_1.ensureFunctionLogstore)(context, client, shared.projectName, fn.key);
172
325
  instances.push({
173
326
  type: 'ALIYUN_SLS_LOGSTORE',
174
327
  id: `${shared.projectName}/${logstore.logstoreName}`,
@@ -184,13 +337,11 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
184
337
  }
185
338
  }
186
339
  const iamConfig = fn.iam?.role;
187
- const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
188
340
  const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
189
341
  const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
190
- const defaultRoleName = `${serviceName}-${context.stage}-fc-role`;
191
- const trustedServices = getTrustedServicesForFunction(context, fn.key);
342
+ const defaultRoleName = buildDefaultRoleName(serviceName, context.stage, fn.key);
192
343
  const isExternalRole = typeof iamConfig === 'string';
193
- if (isExternalRole) {
344
+ if (isExternalRole && !skipRole) {
194
345
  // External role - use ARN directly, skip creation and management
195
346
  instances.push({
196
347
  type: 'ALIYUN_RAM_ROLE',
@@ -200,17 +351,40 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
200
351
  attributes: {},
201
352
  });
202
353
  }
203
- else if (hasRamRole) {
354
+ else if (!skipRole && hasRamRole) {
204
355
  const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
205
356
  if (ramRoleInstance) {
206
- instances.push(ramRoleInstance);
207
- await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, trustedServices);
357
+ const cloudRole = await client.ram.getRole(ramRoleInstance.id);
358
+ if (!cloudRole) {
359
+ // Issue #234: recorded instance but provider role gone — rebuild with
360
+ // peer-union grants instead of failing on the trust-policy update.
361
+ logger_1.logger.warn(lang_1.lang.__('RAM_ROLE_MISSING_RECREATE', { roleName: ramRoleInstance.id }));
362
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
363
+ const ramRole = await client.ram.createRole(ramRoleInstance.id, roleGrant.trustedServices, undefined, roleGrant.customStatements, managedPolicies, roleGrant.executionStatements);
364
+ instances.push({
365
+ type: 'ALIYUN_RAM_ROLE',
366
+ id: ramRoleInstance.id,
367
+ roleArn: ramRole.arn,
368
+ attributes: { ...ramRole },
369
+ });
370
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
371
+ }
372
+ else {
373
+ instances.push(ramRoleInstance);
374
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
375
+ await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
376
+ await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
377
+ if (managedPolicies?.length) {
378
+ await client.ram.attachManagedPolicies(ramRoleInstance.id, managedPolicies);
379
+ }
380
+ }
208
381
  }
209
382
  }
210
- else {
383
+ else if (!skipRole) {
211
384
  const roleName = customRoleName ?? defaultRoleName;
385
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, roleName);
212
386
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
213
- const ramRole = await client.ram.createRole(roleName, trustedServices, undefined, statements, managedPolicies);
387
+ const ramRole = await client.ram.createRole(roleName, roleGrant.trustedServices, undefined, roleGrant.customStatements, managedPolicies, roleGrant.executionStatements);
214
388
  instances.push({
215
389
  type: 'ALIYUN_RAM_ROLE',
216
390
  id: roleName,
@@ -220,13 +394,17 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
220
394
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
221
395
  }
222
396
  const ramRoleInstance = instances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
223
- const role = isExternalRole
224
- ? { roleName: '', arn: iamConfig }
225
- : {
397
+ let role;
398
+ if (isExternalRole) {
399
+ role = { roleName: '', arn: iamConfig };
400
+ }
401
+ else if (!skipRole) {
402
+ role = {
226
403
  roleName: customRoleName ?? defaultRoleName,
227
404
  arn: ramRoleInstance?.roleArn ??
228
405
  `acs:ram::${context.accountId}:role/${customRoleName ?? defaultRoleName}`,
229
406
  };
407
+ }
230
408
  if (fn.network) {
231
409
  if (hasSecurityGroup) {
232
410
  const sgInstance = existingInstances.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
@@ -549,7 +727,7 @@ const createResource = async (context, fn, state) => {
549
727
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
550
728
  }
551
729
  certConfig = {
552
- certName: `${context.service}-${context.stage}-fc3-domain`,
730
+ certName: buildFc3CertName(context.service, context.stage),
553
731
  certificate: detail.cert,
554
732
  privateKey: detail.key,
555
733
  };
@@ -583,7 +761,7 @@ const readResource = async (context, functionName) => {
583
761
  return await client.fc3.getFunction(functionName);
584
762
  };
585
763
  exports.readResource = readResource;
586
- const updateResource = async (context, fn, state) => {
764
+ const updateResource = async (context, fn, state, options) => {
587
765
  const ctx = (0, common_1.getContext)();
588
766
  const serviceName = `${ctx.app}-${ctx.service}`;
589
767
  const logicalId = `functions.${fn.key}`;
@@ -592,7 +770,6 @@ const updateResource = async (context, fn, state) => {
592
770
  const hasSlsResources = existingInstances.some((i) => i.type === 'ALIYUN_SLS_PROJECT' ||
593
771
  i.type === 'ALIYUN_SLS_LOGSTORE' ||
594
772
  i.type === 'ALIYUN_SLS_INDEX');
595
- const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
596
773
  const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
597
774
  const hasNasResources = existingInstances.some((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
598
775
  const client = (0, aliyunClient_1.createAliyunClient)(context);
@@ -609,7 +786,7 @@ const updateResource = async (context, fn, state) => {
609
786
  // shared-state entry is removed from the returned state.
610
787
  let releasedSharedProject = false;
611
788
  if (fn.log && !hasSlsResources) {
612
- const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
789
+ const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, { skipRole: true });
613
790
  logConfig = deps.logConfig;
614
791
  newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('ALIYUN_SLS_')));
615
792
  if (deps.sharedProject) {
@@ -622,6 +799,26 @@ const updateResource = async (context, fn, state) => {
622
799
  if (slsLogstoreInstance) {
623
800
  const [projectName, logstoreName] = slsLogstoreInstance.id.split('/');
624
801
  logConfig = { project: projectName, logstore: logstoreName };
802
+ // Issue #234 M1: nested repair — only on a drifted plan item (force):
803
+ // reconcile logstore ttl/shards and index presence against what si
804
+ // creates. Shard deficits are repaired upward; Aliyun cannot shrink.
805
+ if (options?.force) {
806
+ const liveLogstore = await client.sls.getLogstore(projectName, logstoreName);
807
+ if (!liveLogstore) {
808
+ logger_1.logger.warn(lang_1.lang.__('NESTED_LOGSTORE_RECREATED', { logstoreName }));
809
+ await client.sls.createLogstore(projectName, logstoreName);
810
+ }
811
+ else if (liveLogstore.ttl !== slsOperations_1.SLS_LOGSTORE_TTL ||
812
+ (liveLogstore.shardCount ?? 0) < slsOperations_1.SLS_LOGSTORE_SHARDS) {
813
+ await client.sls.updateLogstore(projectName, logstoreName, slsOperations_1.SLS_LOGSTORE_TTL, Math.max(liveLogstore.shardCount ?? 0, slsOperations_1.SLS_LOGSTORE_SHARDS));
814
+ logger_1.logger.info(lang_1.lang.__('NESTED_LOGSTORE_UPDATED', { logstoreName }));
815
+ }
816
+ const liveIndex = await client.sls.getIndex(projectName, logstoreName);
817
+ if (!liveIndex) {
818
+ logger_1.logger.warn(lang_1.lang.__('NESTED_INDEX_RECREATED', { logstoreName }));
819
+ await client.sls.createIndex(projectName, logstoreName);
820
+ }
821
+ }
625
822
  }
626
823
  }
627
824
  else {
@@ -633,24 +830,61 @@ const updateResource = async (context, fn, state) => {
633
830
  }
634
831
  }
635
832
  const newIamRole = fn.iam?.role;
833
+ const executionStatements = (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig);
834
+ const iamRoleConfig = newIamRole && typeof newIamRole !== 'string' ? newIamRole : undefined;
835
+ const customRoleName = iamRoleConfig?.name;
836
+ const desiredManagedPolicies = iamRoleConfig?.managed_policies;
837
+ // A role created/recreated in this run must rebind the function even when the
838
+ // compared definition is unchanged — role is not part of extractFc3Definition.
839
+ let roleBindingChanged = false;
840
+ const droppedRamRoleIds = new Set();
841
+ const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
842
+ // Issue #234 dual check: a recorded instance is not trusted on its own — when
843
+ // the provider role is gone, the create path below rebuilds it with
844
+ // peer-union grants and drops the stale instance from the resulting state.
845
+ // External roles are recorded with the ARN as the instance id, which is not a
846
+ // valid GetRole roleName input, and the external branch below never consults
847
+ // the probe — so only recorded managed roles are probed.
848
+ const isRecordedRoleExternal = Boolean(ramRoleInstance?.external);
849
+ const cloudRoleExists = ramRoleInstance && !isRecordedRoleExternal && typeof newIamRole !== 'string'
850
+ ? Boolean(await client.ram.getRole(ramRoleInstance.id))
851
+ : false;
636
852
  if (typeof newIamRole === 'string') {
637
853
  // External role - use ARN directly, skip management
638
854
  role = { roleName: '', arn: newIamRole };
639
855
  }
640
- else if (!hasRamRole) {
641
- const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
642
- role = deps.role;
643
- newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_RAM_ROLE'));
856
+ else if (!ramRoleInstance || isRecordedRoleExternal || !cloudRoleExists) {
857
+ const roleName = (isRecordedRoleExternal ? undefined : ramRoleInstance?.id) ??
858
+ customRoleName ??
859
+ buildDefaultRoleName(serviceName, context.stage, fn.key);
860
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, roleName);
861
+ logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
862
+ const ramRole = await client.ram.createRole(roleName, roleGrant.trustedServices, undefined, roleGrant.customStatements, desiredManagedPolicies, roleGrant.executionStatements);
863
+ role = {
864
+ roleName,
865
+ arn: ramRole.arn ?? `acs:ram::${context.accountId}:role/${roleName}`,
866
+ };
867
+ if (ramRoleInstance) {
868
+ droppedRamRoleIds.add(ramRoleInstance.id);
869
+ }
870
+ newDependentInstances.push({
871
+ type: 'ALIYUN_RAM_ROLE',
872
+ id: roleName,
873
+ roleArn: role.arn,
874
+ attributes: { ...ramRole },
875
+ });
876
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
877
+ roleBindingChanged = true;
644
878
  }
645
879
  else {
646
- const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
647
880
  if (ramRoleInstance) {
648
881
  role = {
649
882
  roleName: ramRoleInstance.id,
650
883
  arn: ramRoleInstance.roleArn ?? `acs:ram::${context.accountId}:role/${ramRoleInstance.id}`,
651
884
  };
652
- const trustedServices = getTrustedServicesForFunction(context, fn.key);
653
- await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, trustedServices);
885
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
886
+ await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
887
+ await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
654
888
  const existingIam = existingState?.definition?.iam;
655
889
  const desiredIam = fn.iam;
656
890
  const iamChanged = !(0, common_1.attributesEqual)(existingIam ?? {}, desiredIam ?? {});
@@ -662,7 +896,7 @@ const updateResource = async (context, fn, state) => {
662
896
  const desiredStatementsVal = (desiredStatements ?? []);
663
897
  const existingStatementsVal = (existingStatements ?? []);
664
898
  if (!(0, common_1.attributesEqual)(existingStatementsVal, desiredStatementsVal)) {
665
- await client.ram.updateRolePolicy(ramRoleInstance.id, desiredStatements);
899
+ await client.ram.updateRolePolicy(ramRoleInstance.id, desiredStatements, executionStatements);
666
900
  }
667
901
  // Check for managed policy changes
668
902
  const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
@@ -678,7 +912,7 @@ const updateResource = async (context, fn, state) => {
678
912
  }
679
913
  }
680
914
  if (fn.network && !hasSecurityGroup) {
681
- const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
915
+ const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, { skipRole: true });
682
916
  securityGroup = deps.securityGroup;
683
917
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP'));
684
918
  }
@@ -686,16 +920,102 @@ const updateResource = async (context, fn, state) => {
686
920
  const sgInstance = existingInstances.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
687
921
  if (sgInstance) {
688
922
  securityGroup = { securityGroupId: sgInstance.id };
923
+ // Issue #234 M2: SG rule reconcile — only on a drifted plan item
924
+ // (force): authorize rules missing from the live set, revoke rules the
925
+ // config no longer declares. Invalid config rules are skipped at create
926
+ // time too.
927
+ if (options?.force && fn.network) {
928
+ const parseRule = (rule) => {
929
+ try {
930
+ return (0, ecsOperations_1.parseSecurityGroupRule)(rule);
931
+ }
932
+ catch {
933
+ return null;
934
+ }
935
+ };
936
+ const desiredIngress = (fn.network.security_group.ingress ?? [])
937
+ .map(parseRule)
938
+ .filter((r) => Boolean(r));
939
+ const desiredEgress = (fn.network.security_group.egress ?? [])
940
+ .map(parseRule)
941
+ .filter((r) => Boolean(r));
942
+ const live = await client.ecs.getSecurityGroupRules(sgInstance.id);
943
+ const liveIngressKeys = (live?.ingressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.sourceCidrIp ?? ''));
944
+ const liveEgressKeys = (live?.egressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.destCidrIp ?? ''));
945
+ const missingIngress = desiredIngress.filter((d) => !liveIngressKeys.includes((0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr)));
946
+ const missingEgress = desiredEgress.filter((d) => !liveEgressKeys.includes((0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr)));
947
+ // The extra check reuses the raw live canonical keys — the same space
948
+ // the missing check uses. Reconstructing a parsed rule here would
949
+ // collapse port ranges (80/443 -> 80) and wrongly revoke matching
950
+ // range rules.
951
+ const desiredIngressKeys = desiredIngress.map((d) => (0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr));
952
+ const desiredEgressKeys = desiredEgress.map((d) => (0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr));
953
+ const extraIngress = (live?.ingressRules ?? []).filter((r, i) => {
954
+ const key = liveIngressKeys[i];
955
+ return !key || !desiredIngressKeys.includes(key);
956
+ });
957
+ const extraEgress = (live?.egressRules ?? []).filter((r, i) => {
958
+ const key = liveEgressKeys[i];
959
+ return !key || !desiredEgressKeys.includes(key);
960
+ });
961
+ if (missingIngress.length > 0 || missingEgress.length > 0) {
962
+ await client.ecs.authorizeSecurityGroupRules(sgInstance.id, 'ingress', missingIngress);
963
+ await client.ecs.authorizeSecurityGroupRules(sgInstance.id, 'egress', missingEgress);
964
+ }
965
+ if (extraIngress.length > 0 || extraEgress.length > 0) {
966
+ const toParsed = (r) => ({
967
+ // Live portRange is already in Aliyun wire format — pass verbatim
968
+ // so the revoke matches the rule exactly (ranges included).
969
+ protocol: r.ipProtocol ?? '',
970
+ cidr: r.sourceCidrIp ?? r.destCidrIp ?? '',
971
+ portRange: r.portRange ?? '',
972
+ });
973
+ await client.ecs.revokeSecurityGroupRules(sgInstance.id, 'ingress', extraIngress.map(toParsed));
974
+ await client.ecs.revokeSecurityGroupRules(sgInstance.id, 'egress', extraEgress.map(toParsed));
975
+ }
976
+ logger_1.logger.info(lang_1.lang.__('NESTED_SG_RULES_REPAIRED', {
977
+ securityGroupId: sgInstance.id,
978
+ added: String(missingIngress.length + missingEgress.length),
979
+ removed: String(extraIngress.length + extraEgress.length),
980
+ }));
981
+ }
689
982
  }
690
983
  }
691
984
  if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network && !hasNasResources) {
692
- const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, undefined, state);
985
+ // The SG branch above already created/reused the security group — pass it
986
+ // so the helper reuses it instead of creating an untracked duplicate.
987
+ const sgExistingInstances = securityGroup
988
+ ? [
989
+ {
990
+ type: 'ALIYUN_ECS_SECURITY_GROUP',
991
+ id: securityGroup.securityGroupId,
992
+ attributes: {},
993
+ },
994
+ ]
995
+ : [];
996
+ const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, sgExistingInstances, state, { skipRole: true });
693
997
  nasConfig = deps.nasConfig;
694
998
  newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('ALIYUN_NAS_')));
695
999
  }
696
1000
  else if (hasNasResources) {
697
1001
  const mountTargetInstances = existingInstances.filter((i) => i.type === 'ALIYUN_NAS_MOUNT_TARGET');
698
1002
  const nasStorageItems = fn.storage?.nas ?? [];
1003
+ // Issue #234 M4: nested repair — only on a drifted plan item (force): a
1004
+ // file system with no live mount targets gets its mount target recreated
1005
+ // (console deletions); extra mount targets are left alone — deleting
1006
+ // shared infrastructure on a reconcile is never safe.
1007
+ if (options?.force && fn.network) {
1008
+ const fsInstances = existingInstances.filter((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
1009
+ for (const fs of fsInstances) {
1010
+ const liveTargets = await client.nas.listMountTargets(fs.id);
1011
+ if (!liveTargets || liveTargets.length === 0) {
1012
+ const mountPath = nasStorageItems[0]?.mount_path ?? '/mnt/nas';
1013
+ const accessGroupName = `${fn.name}-${context.stage}-nas-access-${mountPath}`;
1014
+ await client.nas.createMountTarget(fs.id, accessGroupName, fn.network.vpc_id, fn.network.subnet_ids[0]);
1015
+ logger_1.logger.warn(lang_1.lang.__('NESTED_MOUNT_TARGET_RECREATED', { fileSystemId: fs.id }));
1016
+ }
1017
+ }
1018
+ }
699
1019
  if (mountTargetInstances.length > 0 && nasStorageItems.length > 0) {
700
1020
  nasConfig = {
701
1021
  mountPoints: mountTargetInstances.map((mt, idx) => ({
@@ -752,7 +1072,10 @@ const updateResource = async (context, fn, state) => {
752
1072
  const { codeHash: _existingCodeHash, iam: _existingIam, ...existingConfigOnly } = existingConfig || {};
753
1073
  const { codeHash: _desiredCodeHash, ...desiredConfigOnly } = desiredDefinition;
754
1074
  const configChanged = !(0, common_1.attributesEqual)(existingConfigOnly, desiredConfigOnly);
755
- if (configChanged) {
1075
+ // `force` carries the plan's drifted flag: a live-drift update (state
1076
+ // matches config, cloud edited in console) must re-push the config even
1077
+ // though state-vs-desired sees no change.
1078
+ if (configChanged || roleBindingChanged || options?.force) {
756
1079
  await client.fc3.updateFunctionConfiguration(config);
757
1080
  }
758
1081
  if (codeChanged) {
@@ -842,7 +1165,7 @@ const updateResource = async (context, fn, state) => {
842
1165
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
843
1166
  }
844
1167
  certConfig = {
845
- certName: `${context.service}-${context.stage}-fc3-domain`,
1168
+ certName: buildFc3CertName(context.service, context.stage),
846
1169
  certificate: detail.cert,
847
1170
  privateKey: detail.key,
848
1171
  };
@@ -880,7 +1203,7 @@ const updateResource = async (context, fn, state) => {
880
1203
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
881
1204
  }
882
1205
  certConfig = {
883
- certName: `${context.service}-${context.stage}-fc3-domain`,
1206
+ certName: buildFc3CertName(context.service, context.stage),
884
1207
  certificate: detail.cert,
885
1208
  privateKey: detail.key,
886
1209
  };
@@ -929,6 +1252,7 @@ const updateResource = async (context, fn, state) => {
929
1252
  .filter((i) => i.type !== 'ALIYUN_FC3_HTTP_TRIGGER')
930
1253
  .filter((i) => i.type !== 'ALIYUN_FC3_CUSTOM_DOMAIN')
931
1254
  .filter((i) => !(typeof fn.iam?.role === 'string' && i.type === 'ALIYUN_RAM_ROLE'))
1255
+ .filter((i) => !(i.type === 'ALIYUN_RAM_ROLE' && droppedRamRoleIds.has(i.id)))
932
1256
  .filter((i) => !droppedSlsDependentTypes.includes(i.type))
933
1257
  .map((i) => {
934
1258
  const { sid: existingSid, id: existingId, ...rest } = i;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractFunctionDomainDefinition = exports.extractFc3Definition = exports.functionToFc3Config = void 0;
3
+ exports.cloudFc3ToDefinition = exports.extractFunctionDomainDefinition = exports.extractFc3Definition = exports.functionToFc3Config = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const common_1 = require("../../common");
6
6
  const gpuConfigMap = {
@@ -93,3 +93,63 @@ const extractFunctionDomainDefinition = (fn, codeHash) => {
93
93
  return (0, exports.extractFc3Definition)(config, codeHash);
94
94
  };
95
95
  exports.extractFunctionDomainDefinition = extractFunctionDomainDefinition;
96
+ /**
97
+ * Cloud-side counterpart of extractFc3Definition (issue #234 live drift): maps
98
+ * a GetFunction response back to the desired-definition shape. Must mirror the
99
+ * executor's write shape (`functionToFc3Config`) key-for-key — keys the
100
+ * executor never writes (customContainerConfig entrypoint/accelerationType)
101
+ * are omitted entirely, and command/enableTls are emitted only when the cloud
102
+ * reports them, so image-level or provider-defaulted values can never
103
+ * phantom-drift against a config that does not declare them.
104
+ */
105
+ const cloudFc3ToDefinition = (info) => {
106
+ return {
107
+ functionName: info.functionName ?? null,
108
+ runtime: info.runtime ?? null,
109
+ handler: info.handler ?? null,
110
+ memorySize: info.memorySize ?? null,
111
+ timeout: info.timeout ?? null,
112
+ diskSize: info.diskSize ?? null,
113
+ environment: info.environmentVariables ?? {},
114
+ vpcConfig: info.vpcConfig
115
+ ? {
116
+ vpcId: info.vpcConfig.vpcId ?? null,
117
+ vSwitchIds: info.vpcConfig.vSwitchIds ?? [],
118
+ securityGroupId: info.vpcConfig.securityGroupId ?? null,
119
+ }
120
+ : null,
121
+ gpuConfig: info.gpuConfig
122
+ ? {
123
+ gpuMemorySize: info.gpuConfig.gpuMemorySize ?? null,
124
+ gpuType: info.gpuConfig.gpuType ?? null,
125
+ }
126
+ : null,
127
+ customContainerConfig: info.customContainerConfig
128
+ ? {
129
+ image: info.customContainerConfig.image ?? null,
130
+ port: info.customContainerConfig.port ?? null,
131
+ ...(info.customContainerConfig.command !== undefined
132
+ ? { command: info.customContainerConfig.command }
133
+ : {}),
134
+ }
135
+ : null,
136
+ nasConfig: info.nasConfig
137
+ ? {
138
+ userId: info.nasConfig.userId ?? null,
139
+ groupId: info.nasConfig.groupId ?? null,
140
+ mountPoints: (info.nasConfig.mountPoints ?? []).map((mp) => ({
141
+ serverAddr: mp.serverAddr ?? null,
142
+ mountDir: mp.mountDir ?? null,
143
+ enableTls: mp.enableTls ?? null,
144
+ })),
145
+ }
146
+ : null,
147
+ logConfig: info.logConfig
148
+ ? {
149
+ enableRequestMetrics: info.logConfig.enableRequestMetrics ?? null,
150
+ enableInstanceMetrics: info.logConfig.enableInstanceMetrics ?? null,
151
+ }
152
+ : null,
153
+ };
154
+ };
155
+ exports.cloudFc3ToDefinition = cloudFc3ToDefinition;