@geek-fun/serverlessinsight 0.8.6 → 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 (33) 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-deploy-app-insight-poc-deploy.json.backup +19 -19
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +11 -11
  6. package/AGENTS.md +29 -0
  7. package/dist/package.json +1 -1
  8. package/dist/src/common/aliyunClient/ramOperations.js +104 -15
  9. package/dist/src/common/iacHelper.js +3 -1
  10. package/dist/src/common/iamStatements.js +21 -1
  11. package/dist/src/common/nameBuilder.js +12 -1
  12. package/dist/src/common/tencentClient/camOperations.js +24 -12
  13. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  14. package/dist/src/lang/en.js +7 -0
  15. package/dist/src/lang/zh-CN.js +6 -0
  16. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  17. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  18. package/dist/src/stack/aliyunStack/apigwTypes.js +20 -5
  19. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  20. package/dist/src/stack/aliyunStack/fc3Resource.js +172 -18
  21. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  22. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  23. package/dist/src/stack/scfStack/scfResource.js +72 -10
  24. package/dist/src/stack/scfStack/sharedLogset.js +9 -1
  25. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  26. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  27. package/dist/src/stack/volcengineStack/apigwTypes.js +18 -7
  28. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  29. package/dist/src/stack/volcengineStack/vefaasPlanner.js +5 -4
  30. package/dist/src/stack/volcengineStack/vefaasResource.js +74 -10
  31. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  32. package/dist/src/validator/semanticValidation.js +41 -0
  33. 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 = 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;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
3
+ exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveScfExecutionStatements = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const tencentClient_1 = require("../../common/tencentClient");
6
6
  const fileUtils_1 = require("../../common/fileUtils");
@@ -269,7 +269,49 @@ const buildScfInstanceFromProvider = (info, sid) => {
269
269
  : {},
270
270
  };
271
271
  };
272
- const createDependentResources = async (context, fn, existingInstances = [], state) => {
272
+ /**
273
+ * Least-privilege SCF execution statements for a function's CAM role
274
+ * (verified against Tencent docs: product/583/38176 role split, 38177 policy
275
+ * syntax — 2026-08).
276
+ *
277
+ * - COS actions are REMOVED: deployment-package access belongs to the
278
+ * configuration role (SCF_QcsRole), not the execution role. Functions whose
279
+ * code uses COS declare it via iam.role.statements.
280
+ * - CLS: the legacy `cls:logset:*` action names are not documented CAM forms
281
+ * (the documented actions are flat, e.g. cls:UploadLog) — the old statement
282
+ * matched no real permission. One conservative grant remains:
283
+ * cls:UploadLog on this function's own topic (si creates it and knows the
284
+ * Id), covering the documented upload action in case SCF's platform log
285
+ * delivery is gated via the execution role.
286
+ * - scf:InvokeFunction is scoped to the function's QCS resource
287
+ * qcs::scf:<region>:uin/<uin>:namespace/<ns>/function/<name> (name-based;
288
+ * the namespace is part of the path) when the UIN is resolvable via CAM
289
+ * GetUserAppId, else falls back to '*' (never wrong-permissions).
290
+ */
291
+ const deriveScfExecutionStatements = (fn, context, uin, clsTopicId) => {
292
+ const namespace = context.parameters?.find((parameter) => parameter.key === 'namespace')?.value ?? 'default';
293
+ const invokeResource = uin && context.region
294
+ ? [`qcs::scf:${context.region}:uin/${uin}:namespace/${namespace}/function/${fn.name}`]
295
+ : ['*'];
296
+ const statements = [
297
+ { effect: 'Allow', action: ['scf:InvokeFunction'], resource: invokeResource },
298
+ ];
299
+ // Verified CLS facts: CAM actions are flat (cls:UploadLog targets the TOPIC
300
+ // resource; CreateLogset/CreateTopic are operation-level -> Resource "*"),
301
+ // and whether SCF's platform log delivery is gated via the execution role is
302
+ // not documented. Keep one conservative statement: UploadLog on this
303
+ // function's own topic (si creates it and knows the Id).
304
+ if (uin && context.region && clsTopicId) {
305
+ statements.push({
306
+ effect: 'Allow',
307
+ action: ['cls:UploadLog'],
308
+ resource: [`qcs::cls:${context.region}:uin/${uin}:topic/${clsTopicId}`],
309
+ });
310
+ }
311
+ return statements;
312
+ };
313
+ exports.deriveScfExecutionStatements = deriveScfExecutionStatements;
314
+ const createDependentResources = async (context, fn, existingInstances = [], state, existingDefinition) => {
273
315
  const client = (0, tencentClient_1.createTencentClient)(context);
274
316
  const clsInstances = [];
275
317
  let clsConfig;
@@ -302,7 +344,7 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
302
344
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
303
345
  logsetId: shared.logsetId,
304
346
  logsetName: shared.logsetName,
305
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
347
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
306
348
  logicalId: `functions.${fn.key}`,
307
349
  });
308
350
  clsInstances.push({
@@ -339,16 +381,36 @@ const createDependentResources = async (context, fn, existingInstances = [], sta
339
381
  }
340
382
  const hasCamRole = existingInstances.some((i) => i.type === 'TENCENT_SCF_ROLE');
341
383
  const serviceName = `${context.app}-${context.service}`;
342
- const defaultRoleName = `${serviceName}-${context.stage}-scf-role`;
384
+ const defaultRoleName = (0, common_1.buildFunctionRoleName)(serviceName, context.stage, fn.key);
343
385
  const roleName = customRoleName ?? defaultRoleName;
386
+ const executionStatements = (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), clsConfig?.topicId);
344
387
  if (hasCamRole) {
345
- // Role already exists - reuse it
346
- return { role: { roleName, arn: roleName }, clsConfig, clsInstances, sharedInstance };
388
+ // Role already exists - reuse it. Keyed on the TENCENT_SCF_ROLE instance
389
+ // type (not the desired name), so pre-existing deployments keep the role
390
+ // they were created with even though the default name now includes fn.key.
391
+ const existingRoleInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE && !i.external);
392
+ const reusedRoleName = existingRoleInstance?.id ?? roleName;
393
+ // Propagate the inline policy (derived baseline + custom statements) only
394
+ // when the custom statements drifted from the last stored definition.
395
+ const desiredStatements = statements;
396
+ const existingRole = existingDefinition?.iam;
397
+ const existingStatements = existingRole && existingRole.role && typeof existingRole.role !== 'string'
398
+ ? existingRole.role.statements
399
+ : undefined;
400
+ if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
401
+ await client.cam.updateRolePolicy(reusedRoleName, desiredStatements, executionStatements);
402
+ }
403
+ return {
404
+ role: { roleName: reusedRoleName, arn: reusedRoleName },
405
+ clsConfig,
406
+ clsInstances,
407
+ sharedInstance,
408
+ };
347
409
  }
348
410
  // Create new CAM role
349
411
  const trustedServices = ['scf.qcloud.com'];
350
412
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
351
- const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies);
413
+ const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies, executionStatements);
352
414
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
353
415
  return {
354
416
  role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName },
@@ -390,7 +452,7 @@ const createResource = async (context, fn, state) => {
390
452
  throw new Error(lang_1.lang.__('HTTP_TRIGGER_AUTH_TYPE_REQUIRED', { functionName: fn.name }));
391
453
  }
392
454
  const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
393
- const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state);
455
+ const dependentResources = await createDependentResources(context, fn, existingResourceState?.instances ?? [], state, existingResourceState?.definition);
394
456
  let config = (0, scfTypes_1.functionToScfConfig)(fn);
395
457
  config.Tags = [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }];
396
458
  if (dependentResources.role) {
@@ -640,7 +702,7 @@ const updateResource = async (context, fn, state) => {
640
702
  const existingRole = existingIam?.role;
641
703
  const existingStatements = existingRole && typeof existingRole !== 'string' ? existingRole.statements : undefined;
642
704
  if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
643
- await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements);
705
+ await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements, (0, exports.deriveScfExecutionStatements)(fn, context, await client.cam.getOwnerUin(), existingClsTopicInstance?.topicId));
644
706
  }
645
707
  // Check for managed policy changes
646
708
  const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
@@ -685,7 +747,7 @@ const updateResource = async (context, fn, state) => {
685
747
  const topic = await (0, sharedLogset_1.ensureFunctionTopic)(context, client, {
686
748
  logsetId: logset.logsetId,
687
749
  logsetName: logset.logsetName,
688
- topicName: (0, sharedLogset_1.buildFunctionTopicName)(context),
750
+ topicName: (0, sharedLogset_1.buildFunctionTopicName)(context, fn.key),
689
751
  logicalId,
690
752
  });
691
753
  clsConfig = {
@@ -16,7 +16,15 @@ const ownershipTag_1 = require("../ownershipTag");
16
16
  exports.SHARED_LOGSET_KEY = 'logs.project';
17
17
  const buildSharedLogsetName = (app, stage) => `${app}-${stage}-cls`;
18
18
  exports.buildSharedLogsetName = buildSharedLogsetName;
19
- const buildFunctionTopicName = (context) => `${context.service}-${context.stage}-fn-logs`;
19
+ /**
20
+ * Topic names are per-function (#214 per-owner teardown): the function key is
21
+ * part of the name. The fnKey-less legacy shape only matches topics created
22
+ * before per-function naming — used by legacy-state branches and delete
23
+ * fallbacks where the actual topic predates this scheme.
24
+ */
25
+ const buildFunctionTopicName = (context, fnKey) => fnKey
26
+ ? `${context.service}-${context.stage}-${fnKey}-fn-logs`
27
+ : `${context.service}-${context.stage}-fn-logs`;
20
28
  exports.buildFunctionTopicName = buildFunctionTopicName;
21
29
  const resolveSharedLogsetName = (shared) => {
22
30
  const instanceId = shared.instances?.[0]?.id;
@@ -25,7 +25,11 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
25
25
  const logicalId = `events.${event.key}`;
26
26
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
27
27
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
28
- const desiredDefinition = (0, apigwTypes_1.buildEventResourceDefinition)(event);
28
+ // Stored-first: an existing event keeps its recorded topic name so the
29
+ // desired definition never phantom-drifts against legacy state.
30
+ const storedTlsTopic = currentState?.instances?.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
31
+ const storedTopicName = storedTlsTopic?.id?.split('/')[1];
32
+ const desiredDefinition = (0, apigwTypes_1.buildEventResourceDefinition)(event, storedTopicName);
29
33
  if (!currentState || currentState.status === 'tainted') {
30
34
  // No usable local state: probe the provider before planning create.
31
35
  // If a same-named gateway already exists WITHOUT our ownership tag it