@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
@@ -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;
@@ -2,11 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateSemantics = void 0;
4
4
  const lang_1 = require("../lang");
5
+ const logger_1 = require("../common/logger");
5
6
  // Direct leaf import on purpose: routing through the src/common barrel would
6
7
  // drag stateManager/lockManager/fs surfaces into the validator graph and
7
8
  // recreate an import cycle with src/parser. These helpers are pure.
8
9
  const providerNames_1 = require("../common/providerNames");
9
10
  const FUNCTION_BACKEND_PATTERN = /^\$\{functions\.([\w.]+)\}$/;
11
+ const TEMPLATE_REF_PATTERN = /^\$\{[^}]+\}$/;
10
12
  /**
11
13
  * Stage is intentionally empty here: it is identical for every generated name
12
14
  * inside one validation run, so collision detection is unaffected while avoiding
@@ -22,6 +24,11 @@ const validateSemantics = (iacJson) => {
22
24
  const events = (iacJson.events ?? {});
23
25
  const functionDefinitions = (iacJson.functions ?? {});
24
26
  const definedFunctionKeys = new Set(Object.keys(functionDefinitions));
27
+ const definedFunctionNames = new Set(Object.values(functionDefinitions)
28
+ .map((fn) => fn && typeof fn === 'object' && typeof fn.name === 'string'
29
+ ? fn.name
30
+ : undefined)
31
+ .filter((name) => name !== undefined));
25
32
  Object.entries(events).forEach(([eventKey, rawEvent]) => {
26
33
  const triggers = Array.isArray(rawEvent.triggers)
27
34
  ? rawEvent.triggers
@@ -69,6 +76,40 @@ const validateSemantics = (iacJson) => {
69
76
  }),
70
77
  });
71
78
  }
79
+ // Bare backend semantics (issue #227): a bare value must be a function's
80
+ // deployed name. A value equal to a template function's KEY is the exact
81
+ // misconfiguration that broke the API Gateway trust policy — reject it;
82
+ // a value matching a template function's name passes with a preference
83
+ // warning; anything else is an external function (statically unverifiable).
84
+ const bareBackend = typeof trigger.backend === 'string' &&
85
+ !backendRef &&
86
+ !TEMPLATE_REF_PATTERN.test(trigger.backend)
87
+ ? trigger.backend
88
+ : undefined;
89
+ if (bareBackend) {
90
+ if (definedFunctionNames.has(bareBackend)) {
91
+ const matchedKey = Object.keys(functionDefinitions).find((key) => typeof functionDefinitions[key]?.name === 'string' &&
92
+ functionDefinitions[key].name === bareBackend);
93
+ logger_1.logger.warn(lang_1.lang.__('SEMANTIC_BACKEND_BARE_NAME', {
94
+ backend: bareBackend,
95
+ key: matchedKey ?? bareBackend,
96
+ eventKey,
97
+ }));
98
+ }
99
+ else if (definedFunctionKeys.has(bareBackend)) {
100
+ errors.push({
101
+ instancePath,
102
+ schemaPath: '#/semantic/bareBackendKey',
103
+ keyword: 'bareBackendKey',
104
+ params: {},
105
+ message: lang_1.lang.__('SEMANTIC_BACKEND_BARE_KEY', {
106
+ backend: bareBackend,
107
+ key: bareBackend,
108
+ eventKey,
109
+ }),
110
+ });
111
+ }
112
+ }
72
113
  // Generated names derive from method+path, so a duplicate trigger would
73
114
  // only re-report the duplicateTrigger error — skip name collision checks.
74
115
  if (isDuplicateTrigger || method.length === 0 || path.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geek-fun/serverlessinsight",
3
- "version": "0.8.5",
3
+ "version": "0.8.7",
4
4
  "description": "Full life cycle cross providers serverless application management for your fast-growing business.",
5
5
  "homepage": "https://serverlessinsight.com",
6
6
  "main": "dist/src/index.js",