@geek-fun/serverlessinsight 0.8.5 → 0.8.7

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 (39) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -2
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -3
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +19 -183
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -2
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +11 -72
  6. package/AGENTS.md +29 -0
  7. package/README.md +0 -12
  8. package/README.zh-CN.md +146 -286
  9. package/dist/package.json +1 -1
  10. package/dist/src/commands/deploy.js +4 -6
  11. package/dist/src/common/aliyunClient/ramOperations.js +104 -15
  12. package/dist/src/common/iacHelper.js +3 -1
  13. package/dist/src/common/iamStatements.js +21 -1
  14. package/dist/src/common/nameBuilder.js +12 -1
  15. package/dist/src/common/stateBackend/remoteStateBackend.js +1 -3
  16. package/dist/src/common/stateBackend/saasStateBackend.js +26 -5
  17. package/dist/src/common/stateManager.js +8 -4
  18. package/dist/src/common/tencentClient/camOperations.js +24 -12
  19. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  20. package/dist/src/lang/en.js +7 -0
  21. package/dist/src/lang/zh-CN.js +6 -0
  22. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  23. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  24. package/dist/src/stack/aliyunStack/apigwTypes.js +20 -5
  25. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  26. package/dist/src/stack/aliyunStack/fc3Resource.js +172 -18
  27. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  28. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  29. package/dist/src/stack/scfStack/scfResource.js +72 -10
  30. package/dist/src/stack/scfStack/sharedLogset.js +9 -1
  31. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  32. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  33. package/dist/src/stack/volcengineStack/apigwTypes.js +18 -7
  34. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  35. package/dist/src/stack/volcengineStack/vefaasPlanner.js +5 -4
  36. package/dist/src/stack/volcengineStack/vefaasResource.js +74 -10
  37. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  38. package/dist/src/validator/semanticValidation.js +41 -0
  39. package/package.json +1 -1
@@ -7,7 +7,7 @@ const common_1 = require("../../common");
7
7
  const reportResourceEvent_1 = require("../../common/reportResourceEvent");
8
8
  const stateManager_1 = require("../../common/stateManager");
9
9
  const lang_1 = require("../../lang");
10
- const executeSingleItem = async (context, item, eventsMap, serviceName, roleArn, currentState) => {
10
+ const executeSingleItem = async (context, item, eventsMap, serviceName, resolveRoleArn, currentState) => {
11
11
  switch (item.action) {
12
12
  case 'noop':
13
13
  common_1.logger.info(lang_1.lang.__('NO_CHANGESForResource', { logicalId: item.logicalId }));
@@ -18,7 +18,7 @@ const executeSingleItem = async (context, item, eventsMap, serviceName, roleArn,
18
18
  throw new Error(`Event not found for logical ID: ${item.logicalId}`);
19
19
  }
20
20
  common_1.logger.info(lang_1.lang.__('CREATING_RESOURCE', { resourceType: 'API Gateway resources', name: event.name }));
21
- const newState = await (0, apigwResource_1.createApigwResource)(context, event, serviceName, roleArn, currentState);
21
+ const newState = await (0, apigwResource_1.createApigwResource)(context, event, serviceName, resolveRoleArn, currentState);
22
22
  common_1.logger.info(lang_1.lang.__('RESOURCE_CREATED', { resourceType: 'API Gateway resources', name: event.name }));
23
23
  return newState;
24
24
  }
@@ -28,7 +28,7 @@ const executeSingleItem = async (context, item, eventsMap, serviceName, roleArn,
28
28
  throw new Error(`Event not found for logical ID: ${item.logicalId}`);
29
29
  }
30
30
  common_1.logger.info(lang_1.lang.__('UPDATING_RESOURCE', { resourceType: 'API Gateway resources', name: event.name }));
31
- const newState = await (0, apigwResource_1.updateApigwResource)(context, event, serviceName, roleArn, currentState);
31
+ const newState = await (0, apigwResource_1.updateApigwResource)(context, event, serviceName, resolveRoleArn, currentState);
32
32
  common_1.logger.info(lang_1.lang.__('RESOURCE_UPDATED', { resourceType: 'API Gateway resources', name: event.name }));
33
33
  return newState;
34
34
  }
@@ -57,7 +57,7 @@ const executeSingleItem = async (context, item, eventsMap, serviceName, roleArn,
57
57
  /**
58
58
  * Execute API Gateway plan with partial failure support
59
59
  */
60
- const executeApigwPlan = async (context, plan, events, serviceName, roleArn, initialState, onStateChange) => {
60
+ const executeApigwPlan = async (context, plan, events, serviceName, resolveRoleArn, initialState, onStateChange) => {
61
61
  const eventsMap = new Map(events?.map((e) => [`events.${e.key}`, e]) ?? []);
62
62
  const successfulItems = [];
63
63
  let currentState = initialState;
@@ -71,7 +71,7 @@ const executeApigwPlan = async (context, plan, events, serviceName, roleArn, ini
71
71
  });
72
72
  const __siStartedAt = Date.now();
73
73
  try {
74
- const newState = await executeSingleItem(context, item, eventsMap, serviceName, roleArn, currentState);
74
+ const newState = await executeSingleItem(context, item, eventsMap, serviceName, resolveRoleArn, currentState);
75
75
  if (newState !== null) {
76
76
  currentState = newState;
77
77
  successfulItems.push(item);
@@ -273,7 +273,7 @@ const buildLogConfigInstance = (context, slsProject, slsLogStore) => ({
273
273
  attributes: { slsProject, slsLogStore },
274
274
  });
275
275
  const ensureGatewayLogConfig = async (context, client, state) => {
276
- const slsLogStore = `${context.service}-${context.stage}-apigw-logs`;
276
+ const slsLogStore = (0, sharedLogProject_1.buildGatewayLogstoreName)(context.service, context.stage);
277
277
  const ours = { slsProject: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage), slsLogStore };
278
278
  const existing = await client.apigw.describeGatewayLogConfig();
279
279
  const matchesOurs = existing &&
@@ -373,9 +373,10 @@ const buildDomainBindingConfig = async (domain, groupId, serviceName, eventKey,
373
373
  ...certConfig,
374
374
  };
375
375
  };
376
- const createApigwResource = async (context, event, serviceName, roleArn, state) => {
376
+ const createApigwResource = async (context, event, serviceName, resolveRoleArn, state) => {
377
377
  const logicalId = `events.${event.key}`;
378
378
  const client = (0, aliyunClient_1.createAliyunClient)(context);
379
+ const roleArnFor = (0, apigwTypes_1.normalizeRoleArnResolver)(resolveRoleArn);
379
380
  const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage, context, logicalId);
380
381
  // Stamp the ownership tag — the create-time contract that lets a later run
381
382
  // (state reset, mid-run failure) idempotently adopt the group we create
@@ -471,7 +472,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
471
472
  }
472
473
  // Create APIs and deployments for each trigger
473
474
  for (const trigger of event.triggers) {
474
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
475
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArnFor(String(trigger.backend)));
475
476
  const apiId = await client.apigw.createApi(apiConfig);
476
477
  // Get API info for state
477
478
  const apiInfo = await client.apigw.getApi(groupId, apiId);
@@ -586,15 +587,16 @@ const readApigwResourceByName = async (context, groupName) => {
586
587
  return await client.apigw.findApiGroupByName(groupName);
587
588
  };
588
589
  exports.readApigwResourceByName = readApigwResourceByName;
589
- const updateApigwResource = async (context, event, serviceName, roleArn, state) => {
590
+ const updateApigwResource = async (context, event, serviceName, resolveRoleArn, state) => {
590
591
  const logicalId = `events.${event.key}`;
591
592
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
592
593
  const client = (0, aliyunClient_1.createAliyunClient)(context);
594
+ const roleArnFor = (0, apigwTypes_1.normalizeRoleArnResolver)(resolveRoleArn);
593
595
  let existingInstances;
594
596
  let groupId;
595
597
  // Precompute expected API names from triggers to safely filter cloud APIs
596
598
  const expectedApiNames = new Set(event.triggers.map((trigger) => {
597
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, 'placeholder', serviceName, context.region, context.stage, roleArn);
599
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, 'placeholder', serviceName, context.region, context.stage, roleArnFor(String(trigger.backend)));
598
600
  return apiConfig.apiName;
599
601
  }));
600
602
  const buildCloudInstance = (cloudGroup, cloudApis) => {
@@ -622,7 +624,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
622
624
  // Shared helper: try to find the group from cloud. On any error (or not found),
623
625
  // fall back to full creation since there's nothing to update.
624
626
  const findCloudGroupOrCreate = async () => {
625
- return (0, exports.createApigwResource)(context, event, serviceName, roleArn, state);
627
+ return (0, exports.createApigwResource)(context, event, serviceName, resolveRoleArn, state);
626
628
  };
627
629
  if (existingState) {
628
630
  existingInstances = existingState.instances;
@@ -692,7 +694,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
692
694
  const existingApis = existingInstances.filter((i) => i.type === 'ALIYUN_APIGW_API');
693
695
  const neededApiKeys = new Set();
694
696
  for (const trigger of event.triggers) {
695
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
697
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArnFor(String(trigger.backend)));
696
698
  const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
697
699
  neededApiKeys.add(apiKey);
698
700
  const existingApi = existingApis.find((a) => {
@@ -723,7 +725,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
723
725
  const apiInfo = await client.apigw.getApi(groupId, existingApi.id);
724
726
  if (apiInfo) {
725
727
  const isNeeded = event.triggers.some((t) => {
726
- const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArn).apiName;
728
+ const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArnFor(String(t.backend))).apiName;
727
729
  return apiInfo.apiName === expectedName;
728
730
  });
729
731
  if (!isNeeded) {
@@ -1,12 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractEventDomainDefinition = exports.buildEventLogSnapshot = exports.inferProtocolConfig = exports.extractApigwDeploymentDefinition = exports.extractApigwApiDefinition = exports.extractApigwGroupDefinition = exports.triggerToApigwApiConfig = exports.eventToApigwGroupConfig = exports.generateApiKey = exports.buildAliyunApigwApiName = void 0;
3
+ exports.extractEventDomainDefinition = exports.buildEventLogSnapshot = exports.inferProtocolConfig = exports.extractApigwDeploymentDefinition = exports.extractApigwApiDefinition = exports.extractApigwGroupDefinition = exports.triggerToApigwApiConfig = exports.eventToApigwGroupConfig = exports.normalizeRoleArnResolver = exports.generateApiKey = exports.buildAliyunApigwApiName = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const lang_1 = require("../../lang");
6
6
  const ownershipTag_1 = require("../ownershipTag");
7
+ const sharedLogProject_1 = require("./sharedLogProject");
7
8
  var common_2 = require("../../common");
8
9
  Object.defineProperty(exports, "buildAliyunApigwApiName", { enumerable: true, get: function () { return common_2.buildAliyunApigwApiName; } });
9
10
  Object.defineProperty(exports, "generateApiKey", { enumerable: true, get: function () { return common_2.generateApiKey; } });
11
+ const normalizeRoleArnResolver = (param) => {
12
+ if (typeof param === 'function') {
13
+ return param;
14
+ }
15
+ return () => param;
16
+ };
17
+ exports.normalizeRoleArnResolver = normalizeRoleArnResolver;
10
18
  /**
11
19
  * Convert EventDomain to API Gateway group config
12
20
  *
@@ -38,6 +46,7 @@ exports.eventToApigwGroupConfig = eventToApigwGroupConfig;
38
46
  /**
39
47
  * Resolves a function reference like ${functions.xxx} to the actual function name
40
48
  */
49
+ const FUNCTION_REF_PATTERN = /^\$\{functions\.[\w.]+\}$/;
41
50
  const resolveFunctionReference = (backendRef) => {
42
51
  // Get IAC from context
43
52
  const context = (0, common_1.getContext)();
@@ -48,8 +57,14 @@ const resolveFunctionReference = (backendRef) => {
48
57
  // Use getIacDefinition to resolve function references
49
58
  const functionDef = (0, common_1.getIacDefinition)(context.iac, backendRef);
50
59
  if (!functionDef || !(0, common_1.isFunctionDomain)(functionDef)) {
51
- // Not a function reference or function not found, return as is
52
- common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
60
+ // Dangling template refs fail semantic validation; a bare value that matches
61
+ // no template function is an external deployed function name (issue #227).
62
+ if (FUNCTION_REF_PATTERN.test(backendRef)) {
63
+ common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
64
+ }
65
+ else {
66
+ common_1.logger.info(lang_1.lang.__('EXTERNAL_FUNCTION_BACKEND', { backendRef }));
67
+ }
53
68
  return backendRef;
54
69
  }
55
70
  const functionName = functionDef.name;
@@ -208,8 +223,8 @@ const buildEventLogSnapshot = (event, context) => {
208
223
  return {
209
224
  logEnabled: event.log === true || event.log === 'true',
210
225
  logConfig: {
211
- project: `${context.app}-${context.stage}-sls`,
212
- logstore: `${context.service}-${context.stage}-apigw-logs`,
226
+ project: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage),
227
+ logstore: (0, sharedLogProject_1.buildGatewayLogstoreName)(context.service, context.stage),
213
228
  },
214
229
  };
215
230
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deployAliyunStack = void 0;
3
+ exports.deployAliyunStack = exports.buildRoleArnResolver = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const lang_1 = require("../../lang");
6
6
  const fc3Planner_1 = require("./fc3Planner");
@@ -43,6 +43,36 @@ const logDependencyGraph = (orderedItems, dotGraph) => {
43
43
  });
44
44
  common_1.logger.debug(`${lang_1.lang.__('DOT_GRAPH_OUTPUT')}:\n${dotGraph}`);
45
45
  };
46
+ const TEMPLATE_FUNCTION_REF_PATTERN = /^\$\{functions\.([\w.]+)\}$/;
47
+ const findFirstManagedRoleArn = (state) => {
48
+ for (const [logicalId, resourceState] of Object.entries(state.resources ?? {})) {
49
+ if (logicalId.startsWith('functions.')) {
50
+ const ramRoleInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
51
+ if (ramRoleInstance?.roleArn) {
52
+ return ramRoleInstance.roleArn;
53
+ }
54
+ }
55
+ }
56
+ return undefined;
57
+ };
58
+ /** @public Resolves a trigger backend to its role ARN; template refs and bare names map to that function's role, else first managed role. */
59
+ const buildRoleArnResolver = (state, functions) => {
60
+ const fallbackArn = findFirstManagedRoleArn(state);
61
+ const keyByName = new Map((functions ?? []).map((f) => [f.name, f.key]));
62
+ return (backend) => {
63
+ const refMatch = backend.match(TEMPLATE_FUNCTION_REF_PATTERN);
64
+ const fnKey = refMatch ? refMatch[1] : keyByName.get(backend);
65
+ if (fnKey) {
66
+ const resourceState = state.resources?.[`functions.${fnKey}`];
67
+ const ramRoleInstance = resourceState?.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
68
+ if (ramRoleInstance?.roleArn) {
69
+ return ramRoleInstance.roleArn;
70
+ }
71
+ }
72
+ return fallbackArn;
73
+ };
74
+ };
75
+ exports.buildRoleArnResolver = buildRoleArnResolver;
46
76
  const deployAliyunStack = async (iac, backend) => {
47
77
  const context = (0, common_1.getContext)();
48
78
  // Cache IAC for access throughout the deployment
@@ -123,8 +153,8 @@ const deployAliyunStack = async (iac, backend) => {
123
153
  });
124
154
  }
125
155
  // Execute event plan after functions are created (events depend on functions)
126
- const roleArn = (0, common_1.getRoleArnFromState)(state);
127
- const eventResult = await (0, apigwExecutor_1.executeApigwPlan)(context, eventPlan, iac.events, iac.service, roleArn, state, onStateChange);
156
+ const resolveRoleArn = (0, exports.buildRoleArnResolver)(state, iac.functions);
157
+ const eventResult = await (0, apigwExecutor_1.executeApigwPlan)(context, eventPlan, iac.events, iac.service, resolveRoleArn, state, onStateChange);
128
158
  state = eventResult.state;
129
159
  if (eventResult.partialFailure) {
130
160
  handlePartialFailure({
@@ -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 = 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"));
@@ -12,6 +12,8 @@ const constants_1 = require("../../common/constants");
12
12
  const types_1 = require("../../types");
13
13
  const fc3Types_1 = require("./fc3Types");
14
14
  const logger_1 = require("../../common/logger");
15
+ const iamStatements_1 = require("../../common/iamStatements");
16
+ const ramOperations_1 = require("../../common/aliyunClient/ramOperations");
15
17
  const lang_1 = require("../../lang");
16
18
  const ownershipTag_1 = require("../ownershipTag");
17
19
  const alreadyExists_1 = require("../alreadyExists");
@@ -22,10 +24,154 @@ const delay = async (ms) => {
22
24
  setTimeout(resolve, ms);
23
25
  });
24
26
  };
25
- const getTrustedServicesForFunction = (context, fnKey) => {
26
- const fnHasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => String(trigger.backend) === `\${functions.${fnKey}}`));
27
+ const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
28
+ const getTrustedServicesForFunction = (context, fn) => {
29
+ const templateFunctions = context.iac?.functions ?? [];
30
+ const templateKeys = new Set(templateFunctions.map((templateFn) => templateFn.key));
31
+ const templateNames = new Set(templateFunctions.map((templateFn) => templateFn.name));
32
+ const fnHasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => {
33
+ const backend = String(trigger.backend);
34
+ if (backend === `\${functions.${fn.key}}` || backend === fn.name) {
35
+ return true;
36
+ }
37
+ // External backend (issue #227): the gateway assumes this managed role as
38
+ // its invocation identity, so bare external names still require apigateway trust.
39
+ return (!TEMPLATE_REF_PATTERN.test(backend) &&
40
+ !templateKeys.has(backend) &&
41
+ !templateNames.has(backend));
42
+ }));
27
43
  return fnHasApiGateway ? ['fc.aliyuncs.com', 'apigateway.aliyuncs.com'] : ['fc.aliyuncs.com'];
28
44
  };
45
+ const FC3_LOG_ACTIONS = [
46
+ 'log:PostLogStoreLogs',
47
+ 'log:CreateLogStore',
48
+ 'log:GetLogStore',
49
+ 'log:ListShards',
50
+ 'log:GetCursorOrData',
51
+ ];
52
+ const FC3_ENI_ACTIONS = [
53
+ 'ecs:CreateNetworkInterface',
54
+ 'ecs:DeleteNetworkInterface',
55
+ 'ecs:DescribeNetworkInterfaces',
56
+ 'ecs:CreateNetworkInterfacePermission',
57
+ 'ecs:DescribeNetworkInterfacePermissions',
58
+ 'ecs:DeleteNetworkInterfacePermission',
59
+ ];
60
+ const buildDefaultRoleName = common_1.buildFunctionRoleName;
61
+ const buildFc3CertName = (service, stage) => `${service}-${stage}-fc3-domain`;
62
+ const collectRolePeers = (state, context, roleId) => {
63
+ const peers = [];
64
+ for (const [logicalId, resourceState] of Object.entries((0, common_1.getAllResources)(state))) {
65
+ if (!logicalId.startsWith('functions.'))
66
+ continue;
67
+ const roleInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
68
+ if (roleInstance?.id !== roleId)
69
+ continue;
70
+ const fn = context.iac?.functions?.find((candidate) => candidate.key === logicalId.slice('functions.'.length));
71
+ if (!fn)
72
+ continue;
73
+ const logstoreInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
74
+ const [project, logstore] = logstoreInstance?.id?.split('/') ?? [];
75
+ peers.push({ fn, ...(project && logstore ? { logConfig: { project, logstore } } : {}) });
76
+ }
77
+ return peers;
78
+ };
79
+ const unionTrustedServices = (serviceLists) => [
80
+ ...new Set(serviceLists.flat()),
81
+ ];
82
+ /**
83
+ * Legacy shared roles serve every function that recorded them, so their trust,
84
+ * derived policy and CUSTOM statements must be the union across those
85
+ * functions — a single function's update would otherwise strip another
86
+ * function's requirements.
87
+ */
88
+ const resolveRoleGrant = (context, state, fn, logConfig, roleId) => {
89
+ const storedPeers = state ? collectRolePeers(state, context, roleId) : [];
90
+ const currentStored = storedPeers.find((peer) => peer.fn.key === fn.key);
91
+ const peers = currentStored
92
+ ? [...storedPeers]
93
+ : [{ fn, ...(logConfig ? { logConfig } : {}) }, ...storedPeers];
94
+ const ownCustoms = fn.iam?.role && typeof fn.iam.role !== 'string' ? fn.iam.role.statements : undefined;
95
+ const peerCustoms = peers
96
+ .filter((peer) => peer.fn.key !== fn.key)
97
+ .map((peer) => peer.fn.iam?.role && typeof peer.fn.iam.role !== 'string'
98
+ ? peer.fn.iam.role.statements
99
+ : undefined)
100
+ .filter((statements) => Boolean(statements?.length));
101
+ const sharedRole = peers.length > 1;
102
+ const customStatements = sharedRole
103
+ ? (0, iamStatements_1.unionPolicyStatements)([ownCustoms ?? [], ...peerCustoms])
104
+ : ownCustoms;
105
+ if (!sharedRole) {
106
+ return {
107
+ trustedServices: getTrustedServicesForFunction(context, fn),
108
+ executionStatements: (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig),
109
+ customStatements,
110
+ };
111
+ }
112
+ return {
113
+ trustedServices: unionTrustedServices(peers.map((peer) => getTrustedServicesForFunction(context, peer.fn))),
114
+ executionStatements: (0, iamStatements_1.unionPolicyStatements)(peers.map((peer) => (0, exports.deriveFc3ExecutionStatements)(peer.fn, context, peer.logConfig))),
115
+ customStatements,
116
+ };
117
+ };
118
+ const buildFcFunctionArn = (context, functionName) => context.accountId
119
+ ? `acs:fc:${context.region}:${context.accountId}:functions/${functionName}`
120
+ : undefined;
121
+ const isTemplateFunctionBackend = (context, backend) => {
122
+ if (/^\$\{functions\./.test(backend))
123
+ return true;
124
+ return (context.iac?.functions ?? []).some((candidate) => candidate.key === backend || candidate.name === backend);
125
+ };
126
+ /**
127
+ * Strict invoke scope (issue #228): this role may invoke its own function plus
128
+ * the service's external backend functions (the gateway may assume any managed
129
+ * role as the fallback identity for external APIs). Falls back to '*' only
130
+ * when the account Id is unknown — never wrong-permissions.
131
+ */
132
+ const resolveFc3InvokeResources = (fn, context) => {
133
+ const ownArn = buildFcFunctionArn(context, fn.name);
134
+ if (!ownArn)
135
+ return ['*'];
136
+ const resources = new Set([ownArn]);
137
+ for (const event of context.iac?.events ?? []) {
138
+ for (const trigger of event.triggers ?? []) {
139
+ const backend = String(trigger.backend ?? '');
140
+ if (!backend || isTemplateFunctionBackend(context, backend))
141
+ continue;
142
+ const externalArn = buildFcFunctionArn(context, backend);
143
+ if (externalArn)
144
+ resources.add(externalArn);
145
+ }
146
+ }
147
+ return [...resources];
148
+ };
149
+ const deriveFc3ExecutionStatements = (fn, context, logConfig) => {
150
+ const statements = [
151
+ {
152
+ effect: 'Allow',
153
+ action: ['fc:InvokeFunction'],
154
+ resource: resolveFc3InvokeResources(fn, context),
155
+ },
156
+ {
157
+ effect: 'Allow',
158
+ action: FC3_LOG_ACTIONS,
159
+ resource: logConfig && context.accountId
160
+ ? [
161
+ `acs:log:${context.region}:${context.accountId}:project/${logConfig.project}/logstore/${logConfig.logstore}`,
162
+ ]
163
+ : ['*'],
164
+ },
165
+ ];
166
+ if (fn.network) {
167
+ statements.push({ effect: 'Allow', action: FC3_ENI_ACTIONS, resource: ['*'] }, { effect: 'Allow', action: ['vpc:DescribeVSwitchAttributes'], resource: ['*'] });
168
+ }
169
+ if (fn.storage?.nas && fn.storage.nas.length > 0) {
170
+ statements.push({ effect: 'Allow', action: ['nas:*'], resource: ['*'] });
171
+ }
172
+ return statements;
173
+ };
174
+ exports.deriveFc3ExecutionStatements = deriveFc3ExecutionStatements;
29
175
  const isRecoverableCreateError = (error) => {
30
176
  const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
31
177
  ? error.code.toLowerCase()
@@ -145,7 +291,7 @@ const buildHttpTriggerConfig = (trigger) => {
145
291
  ...(disableURLInternet !== undefined ? { disableURLInternet } : {}),
146
292
  };
147
293
  };
148
- const createDependentResources = async (context, fn, serviceName, existingInstances = [], state) => {
294
+ const createDependentResources = async (context, fn, serviceName, existingInstances = [], state, executionStatementsOverride) => {
149
295
  const client = (0, aliyunClient_1.createAliyunClient)(context);
150
296
  const instances = [];
151
297
  let logConfig;
@@ -168,7 +314,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
168
314
  }
169
315
  else {
170
316
  const shared = await (0, sharedLogProject_1.ensureSharedSlsProject)(context, client, state);
171
- const logstore = await (0, sharedLogProject_1.ensureFunctionLogstore)(context, client, shared.projectName);
317
+ const logstore = await (0, sharedLogProject_1.ensureFunctionLogstore)(context, client, shared.projectName, fn.key);
172
318
  instances.push({
173
319
  type: 'ALIYUN_SLS_LOGSTORE',
174
320
  id: `${shared.projectName}/${logstore.logstoreName}`,
@@ -187,8 +333,9 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
187
333
  const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
188
334
  const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
189
335
  const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
190
- const defaultRoleName = `${serviceName}-${context.stage}-fc-role`;
191
- const trustedServices = getTrustedServicesForFunction(context, fn.key);
336
+ const defaultRoleName = buildDefaultRoleName(serviceName, context.stage, fn.key);
337
+ const trustedServices = getTrustedServicesForFunction(context, fn);
338
+ const executionStatements = executionStatementsOverride ?? (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig);
192
339
  const isExternalRole = typeof iamConfig === 'string';
193
340
  if (isExternalRole) {
194
341
  // External role - use ARN directly, skip creation and management
@@ -204,13 +351,18 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
204
351
  const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
205
352
  if (ramRoleInstance) {
206
353
  instances.push(ramRoleInstance);
207
- await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, trustedServices);
354
+ const roleGrant = resolveRoleGrant(context, state, fn, logConfig, ramRoleInstance.id);
355
+ await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
356
+ await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
357
+ if (managedPolicies?.length) {
358
+ await client.ram.attachManagedPolicies(ramRoleInstance.id, managedPolicies);
359
+ }
208
360
  }
209
361
  }
210
362
  else {
211
363
  const roleName = customRoleName ?? defaultRoleName;
212
364
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
213
- const ramRole = await client.ram.createRole(roleName, trustedServices, undefined, statements, managedPolicies);
365
+ const ramRole = await client.ram.createRole(roleName, trustedServices, undefined, statements, managedPolicies, executionStatements);
214
366
  instances.push({
215
367
  type: 'ALIYUN_RAM_ROLE',
216
368
  id: roleName,
@@ -549,7 +701,7 @@ const createResource = async (context, fn, state) => {
549
701
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
550
702
  }
551
703
  certConfig = {
552
- certName: `${context.service}-${context.stage}-fc3-domain`,
704
+ certName: buildFc3CertName(context.service, context.stage),
553
705
  certificate: detail.cert,
554
706
  privateKey: detail.key,
555
707
  };
@@ -633,12 +785,13 @@ const updateResource = async (context, fn, state) => {
633
785
  }
634
786
  }
635
787
  const newIamRole = fn.iam?.role;
788
+ const executionStatements = (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig);
636
789
  if (typeof newIamRole === 'string') {
637
790
  // External role - use ARN directly, skip management
638
791
  role = { roleName: '', arn: newIamRole };
639
792
  }
640
793
  else if (!hasRamRole) {
641
- const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
794
+ const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, executionStatements);
642
795
  role = deps.role;
643
796
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_RAM_ROLE'));
644
797
  }
@@ -649,8 +802,9 @@ const updateResource = async (context, fn, state) => {
649
802
  roleName: ramRoleInstance.id,
650
803
  arn: ramRoleInstance.roleArn ?? `acs:ram::${context.accountId}:role/${ramRoleInstance.id}`,
651
804
  };
652
- const trustedServices = getTrustedServicesForFunction(context, fn.key);
653
- await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, trustedServices);
805
+ const roleGrant = resolveRoleGrant(context, state, fn, logConfig, ramRoleInstance.id);
806
+ await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
807
+ await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
654
808
  const existingIam = existingState?.definition?.iam;
655
809
  const desiredIam = fn.iam;
656
810
  const iamChanged = !(0, common_1.attributesEqual)(existingIam ?? {}, desiredIam ?? {});
@@ -662,7 +816,7 @@ const updateResource = async (context, fn, state) => {
662
816
  const desiredStatementsVal = (desiredStatements ?? []);
663
817
  const existingStatementsVal = (existingStatements ?? []);
664
818
  if (!(0, common_1.attributesEqual)(existingStatementsVal, desiredStatementsVal)) {
665
- await client.ram.updateRolePolicy(ramRoleInstance.id, desiredStatements);
819
+ await client.ram.updateRolePolicy(ramRoleInstance.id, desiredStatements, executionStatements);
666
820
  }
667
821
  // Check for managed policy changes
668
822
  const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
@@ -678,7 +832,7 @@ const updateResource = async (context, fn, state) => {
678
832
  }
679
833
  }
680
834
  if (fn.network && !hasSecurityGroup) {
681
- const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
835
+ const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, executionStatements);
682
836
  securityGroup = deps.securityGroup;
683
837
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP'));
684
838
  }
@@ -689,7 +843,7 @@ const updateResource = async (context, fn, state) => {
689
843
  }
690
844
  }
691
845
  if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network && !hasNasResources) {
692
- const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, undefined, state);
846
+ const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, undefined, state, executionStatements);
693
847
  nasConfig = deps.nasConfig;
694
848
  newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('ALIYUN_NAS_')));
695
849
  }
@@ -842,7 +996,7 @@ const updateResource = async (context, fn, state) => {
842
996
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
843
997
  }
844
998
  certConfig = {
845
- certName: `${context.service}-${context.stage}-fc3-domain`,
999
+ certName: buildFc3CertName(context.service, context.stage),
846
1000
  certificate: detail.cert,
847
1001
  privateKey: detail.key,
848
1002
  };
@@ -880,7 +1034,7 @@ const updateResource = async (context, fn, state) => {
880
1034
  throw new Error(lang_1.lang.__('CERT_REFERENCE_NOT_FOUND', { reference: certId }));
881
1035
  }
882
1036
  certConfig = {
883
- certName: `${context.service}-${context.stage}-fc3-domain`,
1037
+ certName: buildFc3CertName(context.service, context.stage),
884
1038
  certificate: detail.cert,
885
1039
  privateKey: detail.key,
886
1040
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ensureGatewayLogstore = exports.ensureFunctionLogstore = exports.releaseSharedSlsProjectIfUnused = exports.isSharedProjectOwnedByApp = exports.adoptSharedSlsProjectState = exports.buildSharedProjectResourceState = exports.ensureSharedSlsProject = exports.resolveSharedProjectName = exports.buildSharedProjectName = exports.SHARED_LOG_PROJECT_KEY = void 0;
3
+ exports.ensureGatewayLogstore = exports.ensureFunctionLogstore = exports.releaseSharedSlsProjectIfUnused = exports.isSharedProjectOwnedByApp = exports.adoptSharedSlsProjectState = exports.buildSharedProjectResourceState = exports.ensureSharedSlsProject = exports.resolveSharedProjectName = exports.buildGatewayLogstoreName = exports.buildFunctionLogstoreName = exports.buildSharedProjectName = exports.SHARED_LOG_PROJECT_KEY = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const logger_1 = require("../../common/logger");
6
6
  const lang_1 = require("../../lang");
@@ -13,8 +13,25 @@ const ownershipTag_1 = require("../ownershipTag");
13
13
  * reports zero remaining logstores.
14
14
  */
15
15
  exports.SHARED_LOG_PROJECT_KEY = 'logs.project';
16
- const buildSharedProjectName = (app, stage) => `${app}-${stage}-sls`;
16
+ const SLS_NAME_MAX_LENGTH = 63;
17
+ const buildSharedProjectName = (app, stage) => (0, common_1.buildConstrainedName)({
18
+ parts: [app, stage, 'sls'],
19
+ maxLength: SLS_NAME_MAX_LENGTH,
20
+ charset: 'hyphen',
21
+ });
17
22
  exports.buildSharedProjectName = buildSharedProjectName;
23
+ const buildFunctionLogstoreName = (service, stage, fnKey) => (0, common_1.buildConstrainedName)({
24
+ parts: [service, stage, fnKey, 'fn-logs'],
25
+ maxLength: SLS_NAME_MAX_LENGTH,
26
+ charset: 'hyphen',
27
+ });
28
+ exports.buildFunctionLogstoreName = buildFunctionLogstoreName;
29
+ const buildGatewayLogstoreName = (service, stage) => (0, common_1.buildConstrainedName)({
30
+ parts: [service, stage, 'apigw-logs'],
31
+ maxLength: SLS_NAME_MAX_LENGTH,
32
+ charset: 'hyphen',
33
+ });
34
+ exports.buildGatewayLogstoreName = buildGatewayLogstoreName;
18
35
  const resolveSharedProjectName = (shared) => {
19
36
  const instanceId = shared.instances?.[0]?.id;
20
37
  return instanceId ?? shared.definition?.projectName;
@@ -127,11 +144,11 @@ const ensureLogstoreInSharedProject = async (context, client, projectName, logst
127
144
  await client.sls.waitForLogstore(projectName, logstoreName);
128
145
  return { logstoreName };
129
146
  };
130
- const ensureFunctionLogstore = async (context, client, projectName) => {
131
- return ensureLogstoreInSharedProject(context, client, projectName, `${context.service}-${context.stage}-fn-logs`);
147
+ const ensureFunctionLogstore = async (context, client, projectName, fnKey) => {
148
+ return ensureLogstoreInSharedProject(context, client, projectName, (0, exports.buildFunctionLogstoreName)(context.service, context.stage, fnKey));
132
149
  };
133
150
  exports.ensureFunctionLogstore = ensureFunctionLogstore;
134
151
  const ensureGatewayLogstore = async (context, client, projectName) => {
135
- return ensureLogstoreInSharedProject(context, client, projectName, `${context.service}-${context.stage}-apigw-logs`);
152
+ return ensureLogstoreInSharedProject(context, client, projectName, (0, exports.buildGatewayLogstoreName)(context.service, context.stage));
136
153
  };
137
154
  exports.ensureGatewayLogstore = ensureGatewayLogstore;
@@ -30,7 +30,7 @@ const generateFunctionPlan = async (context, state, functions) => {
30
30
  config = {
31
31
  ...config,
32
32
  ClsLogsetName: (0, sharedLogset_1.buildSharedLogsetName)(context.app, context.stage),
33
- ClsTopicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
33
+ ClsTopicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
34
34
  };
35
35
  }
36
36
  const codePath = fn.code.path;