@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,9 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteApigwResource = exports.updateApigwResource = exports.createApigwResource = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const volcengineClient_1 = require("../../common/volcengineClient");
6
+ const common_1 = require("../../common");
6
7
  const apigwTypes_1 = require("./apigwTypes");
7
8
  const stateManager_1 = require("../../common/stateManager");
8
- const common_1 = require("../../common");
9
+ const common_2 = require("../../common");
9
10
  const logger_1 = require("../../common/logger");
10
11
  const lang_1 = require("../../lang");
11
12
  const ownershipTag_1 = require("../ownershipTag");
@@ -13,7 +14,7 @@ const alreadyExists_1 = require("../alreadyExists");
13
14
  const sharedLogProject_1 = require("./sharedLogProject");
14
15
  const buildGatewayInstance = (info, stage) => ({
15
16
  type: 'VOLCENGINE_APIGW_GATEWAY',
16
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
17
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
17
18
  id: info.gatewayId ?? '',
18
19
  gatewayId: info.gatewayId ?? null,
19
20
  gatewayName: info.gatewayName ?? null,
@@ -32,7 +33,11 @@ const buildGatewayInstance = (info, stage) => ({
32
33
  logSpec: info.logSpec ?? null,
33
34
  resourceSpec: info.resourceSpec ?? null,
34
35
  });
35
- const ensureApigwLogResources = async (context, existingInstances, state, logicalId) => {
36
+ const resolveTlsTopicNameFromInstances = (instances) => {
37
+ const tlsTopic = instances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
38
+ return tlsTopic?.id?.split('/')[1];
39
+ };
40
+ const ensureApigwLogResources = async (context, existingInstances, state, logicalId, eventKey) => {
36
41
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
37
42
  const tlsProjectInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
38
43
  const tlsTopicInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
@@ -47,7 +52,7 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
47
52
  // Shared app-scoped TLS project (#214) with a per-event topic nested under it.
48
53
  const shared = await (0, sharedLogProject_1.ensureSharedLogProject)(context, client, state);
49
54
  const sharedInstance = (0, sharedLogProject_1.buildSharedProjectResourceState)(context, shared);
50
- const topicName = `${context.service}-${context.stage}-apigw-logs`;
55
+ const topicName = (0, sharedLogProject_1.buildApigwLogTopicName)(context.service, context.stage, eventKey);
51
56
  const topic = await (0, sharedLogProject_1.ensureOwnedTopic)(context, client, {
52
57
  projectName: shared.projectName,
53
58
  topicName,
@@ -59,14 +64,14 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
59
64
  instances: [
60
65
  {
61
66
  type: 'VOLCENGINE_TLS_TOPIC',
62
- sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}`),
67
+ sid: (0, common_2.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}`),
63
68
  id: `${shared.projectName}/${topic.topicName}`,
64
69
  projectId: shared.projectId,
65
70
  topicId: topic.topicId,
66
71
  },
67
72
  {
68
73
  type: 'VOLCENGINE_TLS_INDEX',
69
- sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}/index`),
74
+ sid: (0, common_2.buildSid)('volcengine', 'tls', context.stage, `${shared.projectName}/${topic.topicName}/index`),
70
75
  id: `${shared.projectName}/${topic.topicName}/index`,
71
76
  },
72
77
  ],
@@ -75,7 +80,7 @@ const ensureApigwLogResources = async (context, existingInstances, state, logica
75
80
  };
76
81
  const buildServiceInstance = (serviceId, serviceName, gatewayId, stage, info) => ({
77
82
  type: 'VOLCENGINE_APIGW_SERVICE',
78
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, serviceId),
83
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, serviceId),
79
84
  id: serviceId,
80
85
  serviceId,
81
86
  serviceName,
@@ -92,7 +97,7 @@ const buildServiceInstance = (serviceId, serviceName, gatewayId, stage, info) =>
92
97
  });
93
98
  const buildUpstreamInstance = (upstreamId, upstreamName, gatewayId, functionId, stage, info) => ({
94
99
  type: 'VOLCENGINE_APIGW_UPSTREAM',
95
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, upstreamId),
100
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, upstreamId),
96
101
  id: upstreamId,
97
102
  upstreamId,
98
103
  upstreamName,
@@ -109,7 +114,7 @@ const buildUpstreamInstance = (upstreamId, upstreamName, gatewayId, functionId,
109
114
  });
110
115
  const buildRouteInstance = (routeId, routeName, serviceId, stage, info) => ({
111
116
  type: 'VOLCENGINE_APIGW_ROUTE',
112
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, routeId),
117
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', stage, routeId),
113
118
  id: routeId,
114
119
  routeId,
115
120
  routeName,
@@ -124,18 +129,36 @@ const buildRouteInstance = (routeId, routeName, serviceId, stage, info) => ({
124
129
  ...(info?.upstreamList && { upstreamList: info.upstreamList }),
125
130
  });
126
131
  /**
127
- * Resolve the veFaaS function Id for a ${functions.xxx} backend ref from state.
128
- * The function resource must already be deployed (functions deploy before events).
132
+ * Resolve the veFaaS function Id for a backend ref. Template refs carry the
133
+ * key directly; bare values are the deployed function name — mapped to the
134
+ * template key first, then resolved from state. A bare name matching no
135
+ * template function is an EXTERNAL deployed function: its Id is resolved
136
+ * from the provider by name (same account/region, function must exist).
129
137
  */
130
- const resolveFunctionIdFromState = (state, backendRef) => {
131
- const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
132
- const fnState = (0, stateManager_1.getResource)(state, `functions.${fnKey}`);
133
- const instance = fnState?.instances?.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
134
- const functionId = instance?.functionId;
135
- if (!functionId) {
136
- throw new Error(`Cannot resolve veFaaS function Id for backend ${backendRef} (functions.${fnKey} has no functionId in state). Deploy the function first.`);
138
+ const resolveFunctionIdFromState = async (state, backendRef, client) => {
139
+ const context = (0, common_1.getContext)();
140
+ const refMatch = /^\$\{functions\.([\w.]+)\}$/.exec(String(backendRef ?? ''));
141
+ const templateKey = refMatch?.[1];
142
+ const fnKey = templateKey ?? context.iac?.functions?.find((f) => f.name === String(backendRef))?.key;
143
+ if (fnKey) {
144
+ const fnState = (0, stateManager_1.getResource)(state, `functions.${fnKey}`);
145
+ const instance = fnState?.instances?.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
146
+ const functionId = instance?.functionId;
147
+ if (functionId) {
148
+ return functionId;
149
+ }
150
+ if (templateKey) {
151
+ // Template function with no state Id: deploy failed or state is stale —
152
+ // do not mask it by adopting a same-named foreign function.
153
+ throw new Error(`Cannot resolve veFaaS function Id for backend ${backendRef} (functions.${fnKey} has no functionId in state). Deploy the function first.`);
154
+ }
155
+ }
156
+ const external = await client.vefaas.getFunction(String(backendRef ?? ''));
157
+ const externalId = external?.functionId;
158
+ if (!externalId) {
159
+ throw new Error(lang_1.lang.__('EXTERNAL_FUNCTION_NOT_FOUND_VOLCENGINE', { backendRef: String(backendRef ?? '') }));
137
160
  }
138
- return functionId;
161
+ return externalId;
139
162
  };
140
163
  const createApigwResource = async (context, event, serviceName, state) => {
141
164
  const logicalId = `events.${event.key}`;
@@ -186,7 +209,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
186
209
  if (event.log) {
187
210
  const existingEventState = (0, stateManager_1.getResource)(state, logicalId);
188
211
  const existingInstances = existingEventState?.instances ?? [];
189
- const logResources = await ensureApigwLogResources(context, existingInstances, state, logicalId);
212
+ const logResources = await ensureApigwLogResources(context, existingInstances, state, logicalId, event.key);
190
213
  if (logResources.sharedInstance) {
191
214
  state = (0, stateManager_1.setSharedResource)(state, context.stage, 'logs.project', logResources.sharedInstance);
192
215
  }
@@ -214,7 +237,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
214
237
  const partialResourceState = {
215
238
  mode: 'managed',
216
239
  region: context.region,
217
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
240
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
218
241
  instances,
219
242
  status: 'tainted',
220
243
  lastUpdated: new Date().toISOString(),
@@ -228,8 +251,8 @@ const createApigwResource = async (context, event, serviceName, state) => {
228
251
  const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
229
252
  let upstreamId = upstreamByFunction.get(fnKey);
230
253
  if (!upstreamId) {
231
- const functionId = resolveFunctionIdFromState(state, backendRef);
232
- const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
254
+ const functionId = await resolveFunctionIdFromState(state, backendRef, client);
255
+ const upstreamName = (0, apigwTypes_1.buildUpstreamName)(event, backendRef, context.stage);
233
256
  const existingUpstream = await client.apigw.findUpstreamByName(gatewayId, upstreamName);
234
257
  if (existingUpstream?.upstreamId) {
235
258
  upstreamId = existingUpstream.upstreamId;
@@ -268,7 +291,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
268
291
  });
269
292
  instances.push({
270
293
  type: 'VOLCENGINE_APIGW_DOMAIN',
271
- sid: (0, common_1.buildSid)('volcengine', 'apigw', context.stage, domainId || domainName),
294
+ sid: (0, common_2.buildSid)('volcengine', 'apigw', context.stage, domainId || domainName),
272
295
  id: domainId || domainName,
273
296
  domainName,
274
297
  serviceId,
@@ -284,7 +307,7 @@ const createApigwResource = async (context, event, serviceName, state) => {
284
307
  const finalResourceState = {
285
308
  mode: 'managed',
286
309
  region: context.region,
287
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
310
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
288
311
  instances,
289
312
  status: 'ready',
290
313
  lastUpdated: new Date().toISOString(),
@@ -311,7 +334,7 @@ const updateApigwResource = async (context, event, serviceName, state) => {
311
334
  i.type === 'VOLCENGINE_APIGW_UPSTREAM');
312
335
  try {
313
336
  if (event.log) {
314
- const logResources = await ensureApigwLogResources(context, existingState.instances, state, `events.${event.key}`);
337
+ const logResources = await ensureApigwLogResources(context, existingState.instances, state, `events.${event.key}`, event.key);
315
338
  if (logResources.sharedInstance) {
316
339
  state = (0, stateManager_1.setSharedResource)(state, context.stage, 'logs.project', logResources.sharedInstance);
317
340
  }
@@ -350,11 +373,10 @@ const updateApigwResource = async (context, event, serviceName, state) => {
350
373
  }
351
374
  for (const trigger of event.triggers) {
352
375
  const backendRef = String(trigger.backend);
353
- const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
354
- const functionId = resolveFunctionIdFromState(state, backendRef);
376
+ const functionId = await resolveFunctionIdFromState(state, backendRef, client);
355
377
  let upstreamId = upstreamByFunction.get(functionId);
356
378
  if (!upstreamId) {
357
- const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
379
+ const upstreamName = (0, apigwTypes_1.buildUpstreamName)(event, backendRef, context.stage);
358
380
  const existing = await client.apigw.findUpstreamByName(serviceInstance.gatewayId, upstreamName);
359
381
  if (existing?.upstreamId) {
360
382
  upstreamId = existing.upstreamId;
@@ -396,7 +418,7 @@ const updateApigwResource = async (context, event, serviceName, state) => {
396
418
  const resourceState = {
397
419
  mode: 'managed',
398
420
  region: context.region,
399
- definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
421
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event, resolveTlsTopicNameFromInstances(instances)),
400
422
  instances,
401
423
  lastUpdated: new Date().toISOString(),
402
424
  };
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveFunctionReference = exports.buildEventResourceDefinition = exports.extractEventDomainDefinition = exports.triggerToApigwRouteConfig = exports.triggerToApigwUpstreamConfig = exports.eventToApigwServiceConfig = exports.eventToApigwGatewayConfig = exports.resolveFunctionKey = exports.buildRouteName = exports.buildUpstreamName = exports.buildServiceName = exports.buildGatewayName = void 0;
4
4
  const common_1 = require("../../common");
5
5
  const lang_1 = require("../../lang");
6
+ const ownershipTag_1 = require("../ownershipTag");
7
+ const sharedLogProject_1 = require("./sharedLogProject");
6
8
  /**
7
9
  * Gateway instance name — reused for find-by-name adoption across deploys.
8
10
  */
@@ -20,6 +22,7 @@ exports.buildRouteName = buildRouteName;
20
22
  /**
21
23
  * Resolves a function reference like ${functions.xxx} to the actual function name
22
24
  */
25
+ const FUNCTION_REF_PATTERN = /^\$\{functions\.[\w.]+\}$/;
23
26
  const resolveFunctionReference = (backendRef) => {
24
27
  const context = (0, common_1.getContext)();
25
28
  if (!context.iac) {
@@ -28,7 +31,14 @@ const resolveFunctionReference = (backendRef) => {
28
31
  }
29
32
  const functionDef = (0, common_1.getIacDefinition)(context.iac, backendRef);
30
33
  if (!functionDef || !(0, common_1.isFunctionDomain)(functionDef)) {
31
- common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
34
+ // Dangling template refs fail semantic validation; a bare value that matches
35
+ // no template function is an external deployed function name (issue #227).
36
+ if (FUNCTION_REF_PATTERN.test(backendRef)) {
37
+ common_1.logger.warn(lang_1.lang.__('FUNCTION_REF_NOT_RESOLVED', { backendRef }));
38
+ }
39
+ else {
40
+ common_1.logger.info(lang_1.lang.__('EXTERNAL_FUNCTION_BACKEND', { backendRef }));
41
+ }
32
42
  return backendRef;
33
43
  }
34
44
  return functionDef.name;
@@ -50,7 +60,7 @@ const eventToApigwGatewayConfig = (event, serviceName, stage, ownershipValue) =>
50
60
  network: { vpcId: event.network.vpc_id, subnetIds: event.network.subnet_ids },
51
61
  }),
52
62
  logConfig: event.log ? { enable: true, projectId: '', topicId: '' } : undefined,
53
- Tags: [{ Key: 'si-owned-by', Value: ownershipValue }],
63
+ Tags: [{ Key: ownershipTag_1.OWNERSHIP_TAG_KEY, Value: ownershipValue }],
54
64
  };
55
65
  };
56
66
  exports.eventToApigwGatewayConfig = eventToApigwGatewayConfig;
@@ -83,7 +93,7 @@ const triggerToApigwRouteConfig = (event, trigger, serviceId, upstreamId) => {
83
93
  };
84
94
  };
85
95
  exports.triggerToApigwRouteConfig = triggerToApigwRouteConfig;
86
- const extractEventDomainDefinition = (event) => {
96
+ const extractEventDomainDefinition = (event, logTopicOverride) => {
87
97
  const context = (0, common_1.getContext)();
88
98
  return {
89
99
  gatewayName: event.name,
@@ -94,8 +104,9 @@ const extractEventDomainDefinition = (event) => {
94
104
  ...(event.log && context
95
105
  ? {
96
106
  logConfig: {
97
- project: `${context.app}-${context.stage}-tls`,
98
- topic: `${context.service}-${context.stage}-apigw-logs`,
107
+ project: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage),
108
+ topic: logTopicOverride ??
109
+ (0, sharedLogProject_1.buildApigwLogTopicName)(context.service, context.stage, String(event.key)),
99
110
  },
100
111
  }
101
112
  : {}),
@@ -113,7 +124,7 @@ const extractEventDomainDefinition = (event) => {
113
124
  };
114
125
  };
115
126
  exports.extractEventDomainDefinition = extractEventDomainDefinition;
116
- const buildEventResourceDefinition = (event) => {
117
- return (0, exports.extractEventDomainDefinition)(event);
127
+ const buildEventResourceDefinition = (event, logTopicOverride) => {
128
+ return (0, exports.extractEventDomainDefinition)(event, logTopicOverride);
118
129
  };
119
130
  exports.buildEventResourceDefinition = buildEventResourceDefinition;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteTlsLogResources = exports.ensureOwnedTopic = exports.releaseSharedLogProjectIfUnused = exports.buildSharedProjectResourceState = exports.ensureSharedLogProject = exports.buildSharedProjectName = exports.SHARED_LOG_PROJECT_KEY = void 0;
3
+ exports.deleteTlsLogResources = exports.ensureOwnedTopic = exports.releaseSharedLogProjectIfUnused = exports.buildSharedProjectResourceState = exports.ensureSharedLogProject = exports.buildApigwLogTopicName = exports.buildFunctionLogTopicName = 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");
@@ -15,6 +15,12 @@ const ownershipTag_1 = require("../ownershipTag");
15
15
  exports.SHARED_LOG_PROJECT_KEY = 'logs.project';
16
16
  const buildSharedProjectName = (app, stage) => `${app}-${stage}-tls`;
17
17
  exports.buildSharedProjectName = buildSharedProjectName;
18
+ /** Per-function fn-logs topic (#214 per-owner teardown): the function key is part of the name. */
19
+ const buildFunctionLogTopicName = (service, stage, fnKey) => `${service}-${stage}-${fnKey}-fn-logs`;
20
+ exports.buildFunctionLogTopicName = buildFunctionLogTopicName;
21
+ /** Per-event apigw-logs topic (#214 per-owner teardown): the event key is part of the name. */
22
+ const buildApigwLogTopicName = (service, stage, eventKey) => `${service}-${stage}-${eventKey}-apigw-logs`;
23
+ exports.buildApigwLogTopicName = buildApigwLogTopicName;
18
24
  const resolveSharedProjectName = (shared) => {
19
25
  const instanceId = shared.instances?.[0]?.id;
20
26
  return instanceId ?? shared.definition?.projectName;
@@ -130,8 +136,8 @@ const ensureOwnedTopic = async (context, client, params) => {
130
136
  const { projectName, topicName, logicalId } = params;
131
137
  const existing = await client.tls.getTopic(projectName, topicName);
132
138
  if (existing) {
133
- // Service-scoped topics are shared across a service's functions/events, so
134
- // ownership is verified at the owning-stack level, not per logical id.
139
+ // fn-logs topics are per-function (the key is in the name); the apigw topic
140
+ // stays service-scoped. Adoption verifies the owning stack either way.
135
141
  const tag = (existing.tags ?? []).find((t) => t.Key === ownershipTag_1.OWNERSHIP_TAG_KEY);
136
142
  const parsed = (0, ownershipTag_1.parseOwnershipTagValue)(tag?.Value);
137
143
  if (parsed?.stack === `${context.app}-${context.service}`) {
@@ -5,6 +5,7 @@ const common_1 = require("../../common");
5
5
  const stateManager_1 = require("../../common/stateManager");
6
6
  const volcengineClient_1 = require("../../common/volcengineClient");
7
7
  const vefaasTypes_1 = require("./vefaasTypes");
8
+ const sharedLogProject_1 = require("./sharedLogProject");
8
9
  const ownershipTag_1 = require("../ownershipTag");
9
10
  const planFunctionDeletion = (logicalId, definition) => ({
10
11
  logicalId,
@@ -47,7 +48,7 @@ const generateFunctionPlan = async (context, state, functions) => {
47
48
  // planner would report `noop` forever, so `UpdateFunction`'s `TlsConfig`
48
49
  // never gets sent. Derive the same project/topic names the executor
49
50
  // would use (shared stage slot → tracked topic instance → deterministic
50
- // shared names `${app}-${stage}-tls` / `${service}-${stage}-fn-logs`) so
51
+ // names `${app}-${stage}-tls` / `${service}-${stage}-${fn.key}-fn-logs`) so
51
52
  // the diff can see the field change without phantom drift.
52
53
  if (fn.log) {
53
54
  const tlsTopicInstance = currentState?.instances?.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
@@ -61,14 +62,14 @@ const generateFunctionPlan = async (context, state, functions) => {
61
62
  if (projectName) {
62
63
  config.logConfig = {
63
64
  project: projectName,
64
- topic: `${context.service}-${context.stage}-fn-logs`,
65
+ topic: (0, sharedLogProject_1.buildFunctionLogTopicName)(context.service, context.stage, fn.key),
65
66
  };
66
67
  }
67
68
  }
68
69
  else {
69
70
  config.logConfig = {
70
- project: `${context.app}-${context.stage}-tls`,
71
- topic: `${context.service}-${context.stage}-fn-logs`,
71
+ project: (0, sharedLogProject_1.buildSharedProjectName)(context.app, context.stage),
72
+ topic: (0, sharedLogProject_1.buildFunctionLogTopicName)(context.service, context.stage, fn.key),
72
73
  };
73
74
  }
74
75
  }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
4
4
  const volcengineClient_1 = require("../../common/volcengineClient");
5
5
  const common_1 = require("../../common");
6
+ const iamStatements_1 = require("../../common/iamStatements");
6
7
  const types_1 = require("../../types");
7
8
  const vefaasTypes_1 = require("./vefaasTypes");
8
9
  const logger_1 = require("../../common/logger");
@@ -103,6 +104,56 @@ const buildVefaasInstanceFromProvider = (info, sid) => {
103
104
  asyncTaskConfig: info.asyncTaskConfig,
104
105
  };
105
106
  };
107
+ const collectRolePeers = (state, context, roleId) => {
108
+ const peers = [];
109
+ for (const [logicalId, resourceState] of Object.entries((0, common_1.getAllResources)(state))) {
110
+ if (!logicalId.startsWith('functions.'))
111
+ continue;
112
+ const roleInstance = resourceState.instances?.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
113
+ if (roleInstance?.id !== roleId)
114
+ continue;
115
+ const fn = context.iac?.functions?.find((candidate) => candidate.key === logicalId.slice('functions.'.length));
116
+ if (!fn)
117
+ continue;
118
+ const definition = (resourceState.definition ?? {});
119
+ peers.push({
120
+ fn,
121
+ hadVpc: Boolean(definition.vpcConfig),
122
+ hadTosMount: Boolean(definition.tosMountConfig),
123
+ });
124
+ }
125
+ return peers;
126
+ };
127
+ /**
128
+ * Legacy shared roles serve every function that recorded them, so their trust
129
+ * and derived policy must be the union across those functions — a single
130
+ * function's update would otherwise strip another function's requirements.
131
+ */
132
+ const resolveRoleGrant = (context, state, fn, roleId) => {
133
+ const storedPeers = state ? collectRolePeers(state, context, roleId) : [];
134
+ const currentStored = storedPeers.find((peer) => peer.fn.key === fn.key);
135
+ const peers = currentStored
136
+ ? [...storedPeers]
137
+ : [{ fn, hadVpc: false, hadTosMount: false }, ...storedPeers];
138
+ const desiredVpc = peers.some((peer) => Boolean(peer.fn.network));
139
+ const desiredTos = peers.some((peer) => Boolean(peer.fn.storage?.nas?.[0]));
140
+ const derivedBaselineChanged = desiredVpc !== peers.some((peer) => peer.hadVpc) ||
141
+ desiredTos !== peers.some((peer) => peer.hadTosMount);
142
+ if (peers.length <= 1) {
143
+ return {
144
+ trustedServices: (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context),
145
+ executionStatements: (0, vefaasTypes_1.deriveVefaasExecutionStatements)(fn, context),
146
+ derivedBaselineChanged,
147
+ };
148
+ }
149
+ return {
150
+ trustedServices: [
151
+ ...new Set(peers.map((peer) => (0, vefaasTypes_1.getTrustedServicesForFunction)(peer.fn, context)).flat()),
152
+ ],
153
+ executionStatements: (0, iamStatements_1.unionPolicyStatements)(peers.map((peer) => (0, vefaasTypes_1.deriveVefaasExecutionStatements)(peer.fn, context))),
154
+ derivedBaselineChanged,
155
+ };
156
+ };
106
157
  const createDependentResources = async (context, fn, serviceName, existingInstances = [], state) => {
107
158
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
108
159
  const instances = [];
@@ -125,7 +176,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
125
176
  // stage shared slot, the function's topic stays nested under the function.
126
177
  const shared = await (0, sharedLogProject_1.ensureSharedLogProject)(context, client, state);
127
178
  sharedInstance = (0, sharedLogProject_1.buildSharedProjectResourceState)(context, shared);
128
- const topicName = `${context.service}-${context.stage}-fn-logs`;
179
+ const topicName = (0, sharedLogProject_1.buildFunctionLogTopicName)(context.service, context.stage, fn.key);
129
180
  const topic = await (0, sharedLogProject_1.ensureOwnedTopic)(context, client, {
130
181
  projectName: shared.projectName,
131
182
  topicName,
@@ -154,13 +205,16 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
154
205
  // sharedInstance so log resources are tracked and torn down correctly.
155
206
  return { logConfig, role, instances, sharedInstance };
156
207
  }
157
- const roleName = customRoleName ?? `${serviceName}-${context.stage}-role`;
208
+ const roleName = customRoleName ?? (0, common_1.buildFunctionRoleName)(serviceName, context.stage, fn.key);
158
209
  const trustedServices = (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context);
210
+ const executionStatements = (0, vefaasTypes_1.deriveVefaasExecutionStatements)(fn, context);
159
211
  if (hasIamRole) {
160
212
  const iamRoleInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
161
213
  if (iamRoleInstance) {
162
214
  instances.push(iamRoleInstance);
163
- await client.iam.updateRoleTrustPolicy(iamRoleInstance.id, (0, vefaasTypes_1.buildDefaultTrustPolicy)(trustedServices));
215
+ const roleGrant = resolveRoleGrant(context, state, fn, iamRoleInstance.id);
216
+ await client.iam.updateRoleTrustPolicy(iamRoleInstance.id, (0, vefaasTypes_1.buildDefaultTrustPolicy)(roleGrant.trustedServices));
217
+ await client.iam.updateRolePolicy(iamRoleInstance.id, roleGrant.executionStatements, statements);
164
218
  }
165
219
  }
166
220
  else {
@@ -170,6 +224,7 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
170
224
  displayName: roleName,
171
225
  description: `veFaaS execution role for ${serviceName}`,
172
226
  trustPolicy: (0, vefaasTypes_1.buildDefaultTrustPolicy)(trustedServices),
227
+ executionStatements,
173
228
  customStatements: statements,
174
229
  managedPolicies,
175
230
  });
@@ -428,13 +483,19 @@ const updateResource = async (context, fn, state) => {
428
483
  role = { roleName: currentIam.role, trn: currentIam.role };
429
484
  }
430
485
  else if (!hasIamRole && !isTainted) {
431
- const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { disk: undefined, nas: undefined } }, serviceName);
486
+ // Role creation only: skip TLS so existing log resources are untouched,
487
+ // but keep network/storage so the derived execution baseline matches the
488
+ // function's actual VPC/TOS usage.
489
+ const deps = await createDependentResources(context, { ...fn, log: false }, serviceName);
432
490
  role = deps.role;
433
491
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'VOLCENGINE_IAM_ROLE'));
434
492
  }
435
493
  else {
436
494
  const iamRoleInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
437
- if (iamRoleInstance) {
495
+ const roleGrant = iamRoleInstance
496
+ ? resolveRoleGrant(context, state, fn, iamRoleInstance.id)
497
+ : undefined;
498
+ if (iamRoleInstance && roleGrant) {
438
499
  const trn = await resolveRoleTrn(client, context, iamRoleInstance.id, iamRoleInstance.trn);
439
500
  if (!trn) {
440
501
  throw new Error(lang_1.lang.__('IAM_ROLE_TRN_MISSING', { roleName: iamRoleInstance.id }));
@@ -443,17 +504,20 @@ const updateResource = async (context, fn, state) => {
443
504
  roleName: iamRoleInstance.id,
444
505
  trn,
445
506
  };
446
- const trustedServices = (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context);
447
- await client.iam.updateRoleTrustPolicy(iamRoleInstance.id, (0, vefaasTypes_1.buildDefaultTrustPolicy)(trustedServices));
507
+ await client.iam.updateRoleTrustPolicy(iamRoleInstance.id, (0, vefaasTypes_1.buildDefaultTrustPolicy)(roleGrant.trustedServices));
448
508
  }
449
509
  // Check statement changes
450
510
  const currentRoleConfig = currentIam?.role && typeof currentIam.role !== 'string' ? currentIam.role : undefined;
451
511
  const desiredRoleConfig = fn.iam?.role && typeof fn.iam.role !== 'string' ? fn.iam.role : undefined;
452
512
  const desiredIamStatements = desiredRoleConfig?.statements;
453
513
  const currentStatementList = currentRoleConfig?.statements;
454
- const iamChanged = JSON.stringify(currentStatementList) !== JSON.stringify(desiredIamStatements);
455
- if (iamChanged && iamRoleInstance) {
456
- await client.iam.updateRolePolicy(iamRoleInstance.id, desiredIamStatements);
514
+ const customStatementsChanged = JSON.stringify(currentStatementList) !== JSON.stringify(desiredIamStatements);
515
+ // The derived execution baseline is the union across all functions sharing
516
+ // the role: drift is detected by comparing desired peer signals (network /
517
+ // TOS mount) against those recorded in each stored definition.
518
+ const derivedBaselineChanged = roleGrant?.derivedBaselineChanged ?? false;
519
+ if ((derivedBaselineChanged || customStatementsChanged) && iamRoleInstance) {
520
+ await client.iam.updateRolePolicy(iamRoleInstance.id, roleGrant?.executionStatements ?? (0, vefaasTypes_1.deriveVefaasExecutionStatements)(fn, context), desiredIamStatements);
457
521
  }
458
522
  // Check managed policy changes
459
523
  const desiredManagedPolicies = desiredRoleConfig?.managed_policies;
@@ -1,18 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTrustedServicesForFunction = exports.buildDefaultTrustPolicy = exports.extractVefaasDefinition = exports.functionToVefaasConfig = void 0;
3
+ exports.getTrustedServicesForFunction = exports.deriveVefaasExecutionStatements = exports.buildDefaultTrustPolicy = exports.extractVefaasDefinition = exports.functionToVefaasConfig = void 0;
4
+ const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
4
5
  /**
5
6
  * Determines which Volcengine services should be trusted to assume the function's IAM role.
6
7
  *
7
- * IMPORTANT: `trigger.backend` is expected to be an *unresolved* YAML reference string in the
8
- * form `${functions.<functionKey>}` (e.g. `${functions.my_fn}`). This function compares against
9
- * that raw string — NOT against a resolved function name or ARN. If the backend value has already
10
- * been resolved to a function name, this check will silently return false and `apigateway` will
11
- * NOT be added to the trust policy, breaking API Gateway invocation.
8
+ * Backend semantics (issue #227): `${functions.<key>}` references a template function
9
+ * by key; a bare value is the function's *deployed name* — either a template function
10
+ * referenced by name or an external function defined outside this template. External
11
+ * backends still need apigateway trust: the gateway assumes this managed role as its
12
+ * invocation identity.
12
13
  */
13
14
  const getTrustedServicesForFunction = (fn, context) => {
15
+ const templateFunctions = context.iac?.functions ?? [];
16
+ const templateKeys = new Set(templateFunctions.map((templateFn) => templateFn.key));
17
+ const templateNames = new Set(templateFunctions
18
+ .map((templateFn) => templateFn.name)
19
+ .filter((name) => name !== undefined));
14
20
  const expectedBackendRef = `\${functions.${fn.key}}`;
15
- const hasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => String(trigger.backend) === expectedBackendRef));
21
+ const hasApiGateway = context.iac?.events?.some((event) => event.triggers?.some((trigger) => {
22
+ const backend = String(trigger.backend);
23
+ if (backend === expectedBackendRef || backend === fn.name) {
24
+ return true;
25
+ }
26
+ return (!TEMPLATE_REF_PATTERN.test(backend) &&
27
+ !templateKeys.has(backend) &&
28
+ !templateNames.has(backend));
29
+ }));
16
30
  return hasApiGateway ? ['vefaas', 'apigateway'] : ['vefaas'];
17
31
  };
18
32
  exports.getTrustedServicesForFunction = getTrustedServicesForFunction;
@@ -71,3 +85,43 @@ const buildDefaultTrustPolicy = (trustedServices) => {
71
85
  };
72
86
  };
73
87
  exports.buildDefaultTrustPolicy = buildDefaultTrustPolicy;
88
+ /**
89
+ * Derive the least-privilege execution policy statements for a veFaaS function.
90
+ *
91
+ * Verified model (volcengine docs "通过 IAM 角色授予实例访问云服务的权限",
92
+ * 2025-10 + the ServiceRoleForVeFaaS policy, user-provided 2026-08): the
93
+ * function role is an STS credential source for USER CODE — the platform
94
+ * injects AK/SK/SessionToken into the request, and no vefaas:* action is
95
+ * required for the platform to run the function (vefaas management actions
96
+ * like CreateFunction/Release/Sandbox belong to the service-linked role).
97
+ * The baseline is therefore the function-logging (tls) convenience grant;
98
+ * VPC-describe statements are only added when the function configures a
99
+ * network, and TOS-object statements only when it mounts TOS storage.
100
+ * Conditions mirror the truthiness used when mapping the function into a
101
+ * VefaasFunctionConfig (see vefaasResource).
102
+ */
103
+ const deriveVefaasExecutionStatements = (fn, _context) => {
104
+ const vefaasBaseline = [
105
+ {
106
+ effect: 'Allow',
107
+ action: ['tls:CreateProject', 'tls:CreateTopic', 'tls:PutLogs'],
108
+ resource: ['*'],
109
+ },
110
+ ];
111
+ const vpcStatement = {
112
+ effect: 'Allow',
113
+ action: ['vpc:DescribeVpcs', 'vpc:DescribeSubnets', 'vpc:DescribeSecurityGroups'],
114
+ resource: ['*'],
115
+ };
116
+ const tosStatement = {
117
+ effect: 'Allow',
118
+ action: ['tos:GetObject', 'tos:PutObject', 'tos:DeleteObject', 'tos:ListBucket'],
119
+ resource: ['*'],
120
+ };
121
+ return [
122
+ ...vefaasBaseline,
123
+ ...(fn.network ? [vpcStatement] : []),
124
+ ...(fn.storage?.nas?.[0] ? [tosStatement] : []),
125
+ ];
126
+ };
127
+ exports.deriveVefaasExecutionStatements = deriveVefaasExecutionStatements;