@geek-fun/serverlessinsight 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +155 -409
  2. package/dist/package.json +2 -1
  3. package/dist/src/common/aliyunClient/ossOperations.js +41 -0
  4. package/dist/src/common/aliyunClient/ramOperations.js +161 -7
  5. package/dist/src/common/iamStatements.js +48 -0
  6. package/dist/src/common/tencentClient/camOperations.js +317 -0
  7. package/dist/src/common/tencentClient/cosOperations.js +67 -0
  8. package/dist/src/common/tencentClient/index.js +18 -0
  9. package/dist/src/common/tencentClient/scfOperations.js +2 -0
  10. package/dist/src/common/volcengineClient/iamOperations.js +133 -47
  11. package/dist/src/common/volcengineClient/tosOperations.js +79 -0
  12. package/dist/src/lang/en.js +24 -0
  13. package/dist/src/lang/zh-CN.js +24 -0
  14. package/dist/src/parser/bucketParser.js +31 -0
  15. package/dist/src/parser/functionParser.js +34 -0
  16. package/dist/src/stack/aliyunStack/fc3Planner.js +2 -1
  17. package/dist/src/stack/aliyunStack/fc3Resource.js +72 -14
  18. package/dist/src/stack/aliyunStack/ossResource.js +63 -0
  19. package/dist/src/stack/aliyunStack/ossTypes.js +9 -0
  20. package/dist/src/stack/localStack/aliyunFc.js +6 -1
  21. package/dist/src/stack/scfStack/cosResource.js +58 -0
  22. package/dist/src/stack/scfStack/cosTypes.js +9 -0
  23. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  24. package/dist/src/stack/scfStack/scfResource.js +195 -22
  25. package/dist/src/stack/scfStack/scfTypes.js +6 -4
  26. package/dist/src/stack/volcengineStack/tosResource.js +56 -0
  27. package/dist/src/stack/volcengineStack/tosTypes.js +9 -0
  28. package/dist/src/stack/volcengineStack/vefaasPlanner.js +2 -1
  29. package/dist/src/stack/volcengineStack/vefaasResource.js +46 -5
  30. package/dist/src/types/domains/state.js +2 -0
  31. package/dist/src/validator/bucketSchema.js +45 -0
  32. package/dist/src/validator/functionSchema.js +43 -0
  33. package/dist/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +2 -1
  35. package/samples/aliyun-poc-api-cdn.yml +75 -0
@@ -1,14 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = void 0;
4
+ const types_1 = require("../../types");
4
5
  const tencentClient_1 = require("../../common/tencentClient");
5
6
  const fileUtils_1 = require("../../common/fileUtils");
6
7
  const scfTypes_1 = require("./scfTypes");
7
8
  const stateManager_1 = require("../../common/stateManager");
8
9
  const common_1 = require("../../common");
10
+ const constants_1 = require("../../common/constants");
9
11
  const hashUtils_1 = require("../../common/hashUtils");
10
12
  const logger_1 = require("../../common/logger");
11
13
  const lang_1 = require("../../lang");
14
+ const delay = async (ms) => {
15
+ await new Promise((resolve) => {
16
+ setTimeout(resolve, ms);
17
+ });
18
+ };
12
19
  const buildScfInstanceFromProvider = (info, sid) => {
13
20
  const envMap = info.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
14
21
  const triggersArray = info.Triggers?.map((t) => ({
@@ -153,10 +160,89 @@ const buildScfInstanceFromProvider = (info, sid) => {
153
160
  : {},
154
161
  };
155
162
  };
163
+ const createDependentResources = async (context, fn, existingInstances = []) => {
164
+ const client = (0, tencentClient_1.createTencentClient)(context);
165
+ const iamConfig = fn.iam?.role;
166
+ // No IAM role configured - skip
167
+ if (!iamConfig) {
168
+ return {};
169
+ }
170
+ const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
171
+ const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
172
+ const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
173
+ // External role (string) - skip creation, use ARN directly
174
+ if (typeof iamConfig === 'string') {
175
+ return { role: { roleName: '', arn: iamConfig } };
176
+ }
177
+ const hasCamRole = existingInstances.some((i) => i.type === 'TENCENT_SCF_ROLE');
178
+ const serviceName = `${context.app}-${context.service}`;
179
+ const defaultRoleName = `${serviceName}-${context.stage}-scf-role`;
180
+ const roleName = customRoleName ?? defaultRoleName;
181
+ if (hasCamRole) {
182
+ // Role already exists - reuse it
183
+ return { role: { roleName, arn: roleName } };
184
+ }
185
+ // Create new CAM role
186
+ const trustedServices = ['scf.tencentcloudapi.com'];
187
+ logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
188
+ const camRole = await client.cam.createRole(roleName, trustedServices, `ServerlessInsight SCF execution role for ${serviceName}`, statements, managedPolicies);
189
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
190
+ return { role: { roleName: camRole.roleName, arn: camRole.roleArn ?? roleName } };
191
+ };
192
+ const deleteDependentResources = async (context, instances) => {
193
+ const client = (0, tencentClient_1.createTencentClient)(context);
194
+ for (const instance of instances) {
195
+ switch (instance.type) {
196
+ case types_1.ResourceTypeEnum.TENCENT_SCF_ROLE: {
197
+ if (instance.external)
198
+ break; // Skip external roles
199
+ logger_1.logger.info(lang_1.lang.__('DELETING_RAM_ROLE', { id: instance.id }));
200
+ await client.cam.deleteRole(instance.id);
201
+ break;
202
+ }
203
+ default:
204
+ logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
205
+ }
206
+ }
207
+ };
156
208
  const createResource = async (context, fn, state) => {
157
- const config = (0, scfTypes_1.functionToScfConfig)(fn);
209
+ const logicalId = `functions.${fn.key}`;
210
+ const existingResourceState = (0, stateManager_1.getResource)(state, logicalId);
211
+ const existingDependentInstances = (existingResourceState?.instances ?? []).filter((i) => i.type !== undefined);
212
+ const dependentResources = await createDependentResources(context, fn, existingDependentInstances);
213
+ let config = (0, scfTypes_1.functionToScfConfig)(fn);
214
+ if (dependentResources.role) {
215
+ config = {
216
+ ...config,
217
+ Role: dependentResources.role.arn,
218
+ };
219
+ }
158
220
  const codePath = fn.code.path;
159
221
  const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
222
+ const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
223
+ const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
224
+ const dependentInstances = [];
225
+ if (dependentResources.role) {
226
+ const iamConfig = fn.iam?.role;
227
+ const isExternalRole = typeof iamConfig === 'string';
228
+ const roleSid = (0, common_1.buildSid)('tencent', 'scf-role', context.stage, dependentResources.role.roleName ?? '');
229
+ dependentInstances.push({
230
+ sid: roleSid,
231
+ type: types_1.ResourceTypeEnum.TENCENT_SCF_ROLE,
232
+ id: dependentResources.role.roleName ?? '',
233
+ ...(dependentResources.role.arn ? { roleArn: dependentResources.role.arn } : {}),
234
+ ...(isExternalRole ? { external: true } : {}),
235
+ });
236
+ }
237
+ const taintedResourceState = {
238
+ mode: 'managed',
239
+ region: context.region,
240
+ definition,
241
+ instances: dependentInstances,
242
+ lastUpdated: new Date().toISOString(),
243
+ status: 'tainted',
244
+ };
245
+ const stateAfterDependents = (0, stateManager_1.setResource)(state, logicalId, taintedResourceState);
160
246
  const client = (0, tencentClient_1.createTencentClient)(context);
161
247
  await client.scf.createFunction(config, codeBase64);
162
248
  // Refresh state from provider to get all attributes
@@ -164,18 +250,19 @@ const createResource = async (context, fn, state) => {
164
250
  if (!functionInfo) {
165
251
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
166
252
  }
167
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
168
- const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash);
169
253
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
170
254
  const resourceState = {
171
255
  mode: 'managed',
172
256
  region: context.region,
173
257
  definition,
174
- instances: [buildScfInstanceFromProvider(functionInfo, sid)],
258
+ instances: [
259
+ buildScfInstanceFromProvider(functionInfo, sid),
260
+ ...dependentInstances,
261
+ ],
175
262
  lastUpdated: new Date().toISOString(),
263
+ status: 'ready',
176
264
  };
177
- const logicalId = `functions.${fn.key}`;
178
- return (0, stateManager_1.setResource)(state, logicalId, resourceState);
265
+ return (0, stateManager_1.setResource)(stateAfterDependents, logicalId, resourceState);
179
266
  };
180
267
  exports.createResource = createResource;
181
268
  const readResource = async (context, functionName) => {
@@ -184,47 +271,133 @@ const readResource = async (context, functionName) => {
184
271
  };
185
272
  exports.readResource = readResource;
186
273
  const updateResource = async (context, fn, state) => {
187
- const config = (0, scfTypes_1.functionToScfConfig)(fn);
188
- const codePath = fn.code.path;
274
+ const logicalId = `functions.${fn.key}`;
275
+ const existingState = (0, stateManager_1.getResource)(state, logicalId);
276
+ const existingInstances = (existingState?.instances ?? []);
277
+ const hasCamRole = existingInstances.some((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE);
189
278
  const client = (0, tencentClient_1.createTencentClient)(context);
279
+ const newIamRole = fn.iam?.role;
280
+ let role;
281
+ if (typeof newIamRole === 'string') {
282
+ // External role - use ARN directly, skip management
283
+ role = { roleName: '', arn: newIamRole };
284
+ }
285
+ else if (!hasCamRole) {
286
+ // No existing role - create one
287
+ const deps = await createDependentResources(context, fn);
288
+ role = deps.role;
289
+ }
290
+ else {
291
+ // Role exists - update trust/managed policies if iam changed
292
+ const ramRoleInstance = existingInstances.find((i) => i.type === types_1.ResourceTypeEnum.TENCENT_SCF_ROLE && !i.external);
293
+ if (ramRoleInstance) {
294
+ role = {
295
+ roleName: ramRoleInstance.id,
296
+ arn: ramRoleInstance.roleArn ?? ramRoleInstance.id,
297
+ };
298
+ const existingIam = existingState?.definition?.iam;
299
+ const desiredIam = fn.iam;
300
+ const iamChanged = !(0, common_1.attributesEqual)(existingIam ?? {}, desiredIam ?? {});
301
+ if (iamChanged) {
302
+ // Check for statement changes
303
+ const desiredStatements = newIamRole ? newIamRole.statements : undefined;
304
+ const existingRole = existingIam?.role;
305
+ const existingStatements = existingRole && typeof existingRole !== 'string' ? existingRole.statements : undefined;
306
+ if (!(0, common_1.attributesEqual)((existingStatements ?? []), (desiredStatements ?? []))) {
307
+ await client.cam.updateRolePolicy(ramRoleInstance.id, desiredStatements);
308
+ }
309
+ // Check for managed policy changes
310
+ const desiredManagedPolicies = newIamRole ? newIamRole.managed_policies : undefined;
311
+ const existingManagedPolicies = existingRole && typeof existingRole !== 'string'
312
+ ? existingRole.managed_policies
313
+ : undefined;
314
+ if (!(0, common_1.attributesEqual)((existingManagedPolicies ?? []), (desiredManagedPolicies ?? []))) {
315
+ await client.cam.updateManagedPolicies(ramRoleInstance.id, desiredManagedPolicies ?? []);
316
+ }
317
+ }
318
+ }
319
+ }
320
+ let config = (0, scfTypes_1.functionToScfConfig)(fn);
321
+ if (role) {
322
+ config = {
323
+ ...config,
324
+ Role: role.arn,
325
+ };
326
+ }
327
+ const codePath = fn.code.path;
328
+ const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
329
+ const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
190
330
  // Update configuration
191
331
  await client.scf.updateFunctionConfiguration(config);
192
332
  // Update code
193
- const codeBase64 = (0, fileUtils_1.readFileAsBase64)(codePath);
194
333
  await client.scf.updateFunctionCode(fn.name, codeBase64);
195
334
  // Refresh state from provider to get all attributes
196
335
  const functionInfo = await client.scf.getFunction(fn.name);
197
336
  if (!functionInfo) {
198
337
  throw new Error(`Failed to refresh state for function: ${fn.name}`);
199
338
  }
200
- const codeHash = (0, hashUtils_1.computeFileHash)(codePath);
201
- const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash);
339
+ const definition = (0, scfTypes_1.extractScfDefinition)(config, codeHash, fn.iam);
202
340
  const sid = (0, common_1.buildSid)('tencent', 'scf', context.stage, fn.name);
341
+ // Rebuild dependent instances list
342
+ const existingDependentInstances = existingInstances
343
+ .filter((i) => i.type !== undefined)
344
+ .map((i) => {
345
+ const { type, id, sid, roleArn, external } = i;
346
+ return {
347
+ sid: sid ?? (0, common_1.buildSid)('tencent', 'scf-role', context.stage, id),
348
+ type,
349
+ id,
350
+ ...(roleArn ? { roleArn } : {}),
351
+ ...(external ? { external } : {}),
352
+ };
353
+ });
354
+ const newDependentInstances = [];
355
+ if (role && !hasCamRole && typeof newIamRole !== 'string') {
356
+ const newRoleSid = (0, common_1.buildSid)('tencent', 'scf-role', context.stage, role.roleName ?? '');
357
+ newDependentInstances.push({
358
+ sid: newRoleSid,
359
+ type: types_1.ResourceTypeEnum.TENCENT_SCF_ROLE,
360
+ id: role.roleName ?? '',
361
+ ...(role.arn ? { roleArn: role.arn } : {}),
362
+ });
363
+ }
203
364
  const resourceState = {
204
365
  mode: 'managed',
205
366
  region: context.region,
206
367
  definition,
207
- instances: [buildScfInstanceFromProvider(functionInfo, sid)],
368
+ instances: [
369
+ buildScfInstanceFromProvider(functionInfo, sid),
370
+ ...existingDependentInstances,
371
+ ...newDependentInstances,
372
+ ],
208
373
  lastUpdated: new Date().toISOString(),
209
374
  };
210
- const logicalId = `functions.${fn.key}`;
211
375
  return (0, stateManager_1.setResource)(state, logicalId, resourceState);
212
376
  };
213
377
  exports.updateResource = updateResource;
214
378
  const deleteResource = async (context, functionName, logicalId, state) => {
379
+ const existingState = (0, stateManager_1.getResource)(state, logicalId);
380
+ const existingInstances = (existingState?.instances ?? []);
381
+ const hasFunction = existingInstances.some((i) => i.type === undefined);
215
382
  const client = (0, tencentClient_1.createTencentClient)(context);
216
- try {
217
- await client.scf.deleteFunction(functionName);
218
- }
219
- catch (err) {
220
- const errorCode = err?.code;
221
- if (errorCode === 'ResourceNotFound.FunctionName') {
222
- logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: functionName }));
383
+ if (hasFunction) {
384
+ try {
385
+ await client.scf.deleteFunction(functionName);
223
386
  }
224
- else {
225
- throw err;
387
+ catch (err) {
388
+ const errorCode = err?.code;
389
+ if (errorCode === 'ResourceNotFound.FunctionName') {
390
+ logger_1.logger.warn(lang_1.lang.__('RESOURCE_NOT_FOUND_PROVIDER', { resourceType: 'Function', name: functionName }));
391
+ }
392
+ else {
393
+ throw err;
394
+ }
226
395
  }
227
396
  }
397
+ const dependentInstances = existingInstances.filter((i) => i.type !== undefined);
398
+ if (dependentInstances.length > 0) {
399
+ await deleteDependentResources(context, dependentInstances);
400
+ }
228
401
  return (0, stateManager_1.removeResource)(state, logicalId);
229
402
  };
230
403
  exports.deleteResource = deleteResource;
@@ -2,13 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.extractFunctionDomainDefinition = exports.extractScfDefinition = exports.functionToScfConfig = void 0;
4
4
  const common_1 = require("../../common");
5
- const functionToScfConfig = (fn) => {
5
+ const functionToScfConfig = (fn, role) => {
6
6
  const config = {
7
7
  FunctionName: fn.name,
8
8
  Runtime: (0, common_1.mapRuntime)(fn.code.runtime, common_1.ProviderEnum.TENCENT),
9
9
  Handler: fn.code.handler,
10
10
  MemorySize: fn.memory ?? 128,
11
11
  Timeout: fn.timeout ?? 3,
12
+ ...(role ? { Role: role } : {}),
12
13
  };
13
14
  if (fn.environment && Object.keys(fn.environment).length > 0) {
14
15
  config.Environment = {
@@ -46,9 +47,9 @@ const functionToScfConfig = (fn) => {
46
47
  return config;
47
48
  };
48
49
  exports.functionToScfConfig = functionToScfConfig;
49
- const extractScfDefinition = (config, codeHash) => {
50
+ const extractScfDefinition = (config, codeHash, iam) => {
50
51
  const envMap = config.Environment?.Variables?.reduce((acc, v) => ({ ...acc, [v.Key]: v.Value }), {}) ?? {};
51
- return {
52
+ const baseDefinition = {
52
53
  functionName: config.FunctionName,
53
54
  runtime: config.Runtime,
54
55
  handler: config.Handler,
@@ -62,10 +63,11 @@ const extractScfDefinition = (config, codeHash) => {
62
63
  useGpu: config.UseGpu ?? null,
63
64
  imageConfig: config.ImageConfig ?? null,
64
65
  };
66
+ return iam ? { ...baseDefinition, iam } : baseDefinition;
65
67
  };
66
68
  exports.extractScfDefinition = extractScfDefinition;
67
69
  const extractFunctionDomainDefinition = (fn, codeHash) => {
68
70
  const config = (0, exports.functionToScfConfig)(fn);
69
- return (0, exports.extractScfDefinition)(config, codeHash);
71
+ return (0, exports.extractScfDefinition)(config, codeHash, fn.iam);
70
72
  };
71
73
  exports.extractFunctionDomainDefinition = extractFunctionDomainDefinition;
@@ -10,6 +10,46 @@ const tosTypes_1 = require("./tosTypes");
10
10
  const logger_1 = require("../../common/logger");
11
11
  const lang_1 = require("../../lang");
12
12
  const node_path_1 = __importDefault(require("node:path"));
13
+ const buildTosBucketPolicyJson = (iam) => {
14
+ if (!iam?.resource?.statements || iam.resource.statements.length === 0)
15
+ return null;
16
+ return {
17
+ Statement: iam.resource.statements.map((stmt) => {
18
+ const s = {
19
+ Effect: stmt.effect,
20
+ Principal: stmt.principal,
21
+ Action: stmt.action,
22
+ Resource: stmt.resource,
23
+ };
24
+ if (stmt.condition) {
25
+ s.Condition = stmt.condition;
26
+ }
27
+ return s;
28
+ }),
29
+ };
30
+ };
31
+ const applyBucketPolicy = async (client, bucket) => {
32
+ if (!bucket.iam)
33
+ return;
34
+ const policy = buildTosBucketPolicyJson(bucket.iam);
35
+ if (!policy) {
36
+ // iam exists but has no statements — delete any existing policy
37
+ await deleteBucketPolicy(client, bucket.name);
38
+ return;
39
+ }
40
+ logger_1.logger.info(lang_1.lang.__('BUCKET_POLICY_APPLYING', { bucketName: bucket.name }));
41
+ await client.tos.putBucketPolicy(bucket.name, policy);
42
+ logger_1.logger.info(lang_1.lang.__('BUCKET_POLICY_APPLIED', { bucketName: bucket.name }));
43
+ };
44
+ const deleteBucketPolicy = async (client, bucketName) => {
45
+ try {
46
+ await client.tos.deleteBucketPolicy(bucketName);
47
+ logger_1.logger.info(lang_1.lang.__('BUCKET_POLICY_DELETED', { bucketName }));
48
+ }
49
+ catch {
50
+ // Best effort cleanup
51
+ }
52
+ };
13
53
  const createResource = async (context, bucket, state) => {
14
54
  const config = (0, tosTypes_1.bucketToTosConfig)(bucket);
15
55
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
@@ -36,6 +76,8 @@ const createResource = async (context, bucket, state) => {
36
76
  logger_1.logger.info(lang_1.lang.__('TOS_BUCKET_TRACKED_CAN_RETRY'));
37
77
  }
38
78
  }
79
+ // Apply IAM bucket policy if configured
80
+ await applyBucketPolicy(client, bucket);
39
81
  const resourceState = {
40
82
  mode: 'managed',
41
83
  region: context.region,
@@ -74,6 +116,18 @@ const updateResource = async (context, bucket, state) => {
74
116
  ? (0, common_1.computeDirectoryHash)(node_path_1.default.resolve(process.cwd(), bucket.website.code))
75
117
  : undefined;
76
118
  const instances = [(0, tosTypes_1.buildTosInstanceFromProvider)(bucketInfo, sid)];
119
+ // Apply IAM bucket policy if configured (update or remove)
120
+ const existingDef = (state.resources[logicalId]?.definition ?? {});
121
+ const oldPolicyJson = existingDef.policy;
122
+ const newPolicyJson = bucket.iam ? JSON.stringify(bucket.iam) : null;
123
+ if (newPolicyJson !== (oldPolicyJson ?? null)) {
124
+ if (newPolicyJson) {
125
+ await applyBucketPolicy(client, bucket);
126
+ }
127
+ else {
128
+ await deleteBucketPolicy(client, bucket.name);
129
+ }
130
+ }
77
131
  const resourceState = {
78
132
  mode: 'managed',
79
133
  region: context.region,
@@ -86,6 +140,8 @@ const updateResource = async (context, bucket, state) => {
86
140
  exports.updateResource = updateResource;
87
141
  const deleteResource = async (context, bucketName, logicalId, state) => {
88
142
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
143
+ // Clean up bucket policy before deleting bucket
144
+ await deleteBucketPolicy(client, bucketName);
89
145
  try {
90
146
  await client.tos.deleteBucket(bucketName);
91
147
  }
@@ -10,6 +10,9 @@ const bucketToTosConfig = (bucket) => {
10
10
  const config = {
11
11
  bucketName: bucket.name,
12
12
  };
13
+ if (bucket.iam) {
14
+ config.iam = bucket.iam;
15
+ }
13
16
  if (bucket.security?.acl) {
14
17
  config.acl = aclMap[bucket.security.acl];
15
18
  }
@@ -25,6 +28,11 @@ const bucketToTosConfig = (bucket) => {
25
28
  return config;
26
29
  };
27
30
  exports.bucketToTosConfig = bucketToTosConfig;
31
+ const serializeBucketPolicy = (iam) => {
32
+ if (!iam?.resource?.statements || iam.resource.statements.length === 0)
33
+ return null;
34
+ return JSON.stringify(iam);
35
+ };
28
36
  const extractTosBucketDefinition = (config, websiteCodeHash) => {
29
37
  return {
30
38
  bucketName: config.bucketName,
@@ -37,6 +45,7 @@ const extractTosBucketDefinition = (config, websiteCodeHash) => {
37
45
  }
38
46
  : null,
39
47
  websiteCodeHash: websiteCodeHash ?? null,
48
+ policy: serializeBucketPolicy(config.iam),
40
49
  };
41
50
  };
42
51
  exports.extractTosBucketDefinition = extractTosBucketDefinition;
@@ -26,7 +26,8 @@ const generateFunctionPlan = async (context, state, functions) => {
26
26
  const config = (0, vefaasTypes_1.functionToVefaasConfig)(fn);
27
27
  const codePath = fn.code.path;
28
28
  const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
29
- const desiredDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
29
+ const baseDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
30
+ const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
30
31
  if (!currentState || currentState.status === 'tainted') {
31
32
  return {
32
33
  logicalId,
@@ -157,7 +157,15 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
157
157
  logConfig = { project: projectName, topic: topicName };
158
158
  }
159
159
  }
160
- const roleName = `${serviceName}-${context.stage}-role`;
160
+ const iamConfig = fn.iam?.role;
161
+ const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
162
+ const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
163
+ const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
164
+ if (iamConfig && typeof iamConfig === 'string') {
165
+ const role = { roleName: iamConfig, trn: iamConfig };
166
+ return { logConfig, role, instances: [] };
167
+ }
168
+ const roleName = customRoleName ?? `${serviceName}-${context.stage}-role`;
161
169
  const trustedServices = (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context);
162
170
  if (hasIamRole) {
163
171
  const iamRoleInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_IAM_ROLE');
@@ -173,6 +181,8 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
173
181
  displayName: roleName,
174
182
  description: `veFaaS execution role for ${serviceName}`,
175
183
  trustPolicy: (0, vefaasTypes_1.buildDefaultTrustPolicy)(trustedServices),
184
+ customStatements: statements,
185
+ managedPolicies,
176
186
  });
177
187
  instances.push({
178
188
  type: 'VOLCENGINE_IAM_ROLE',
@@ -222,10 +232,16 @@ const deleteDependentResources = async (context, instances) => {
222
232
  logger_1.logger.info(lang_1.lang.__('DELETING_TLS_PROJECT', { id: instance.id }));
223
233
  await client.tls.deleteProject(instance.id);
224
234
  break;
225
- case 'VOLCENGINE_IAM_ROLE':
235
+ case 'VOLCENGINE_IAM_ROLE': {
236
+ const attrs = instance.attributes;
237
+ if (attrs?.external === true) {
238
+ logger_1.logger.info(`Skipping deletion of external IAM role: ${instance.id} (managed externally)`);
239
+ break;
240
+ }
226
241
  logger_1.logger.info(lang_1.lang.__('DELETING_IAM_ROLE', { id: instance.id }));
227
242
  await client.iam.deleteRole(instance.id);
228
243
  break;
244
+ }
229
245
  default:
230
246
  logger_1.logger.warn(lang_1.lang.__('UNKNOWN_RESOURCE_TYPE', { type: instance.type }));
231
247
  }
@@ -264,7 +280,8 @@ const createResource = async (context, fn, state) => {
264
280
  });
265
281
  const codePath = fn.code.path;
266
282
  const codeHash = (0, common_1.computeFileHash)(codePath);
267
- const definition = (0, vefaasTypes_1.extractVefaasDefinition)(config, codeHash);
283
+ const resourceAttributes = (0, vefaasTypes_1.extractVefaasDefinition)(config, codeHash);
284
+ const definition = fn.iam ? { ...resourceAttributes, iam: fn.iam } : resourceAttributes;
268
285
  const sid = (0, common_1.buildSid)('volcengine', context.service, context.stage, fn.name);
269
286
  const dependentInstances = dependentResources.instances.map((dep) => ({
270
287
  sid: dep.sid ??
@@ -370,7 +387,14 @@ const updateResource = async (context, fn, state) => {
370
387
  logConfig = { project: projectName, topic: topicName };
371
388
  }
372
389
  }
373
- if (!hasIamRole && !isTainted) {
390
+ // Determine if the current role is external (string TRN)
391
+ const currentIam = currentState.definition?.iam;
392
+ const isExternalRole = currentIam?.role && typeof currentIam.role === 'string';
393
+ if (isExternalRole) {
394
+ // External role - skip role management, use TRN directly
395
+ role = { roleName: currentIam.role, trn: currentIam.role };
396
+ }
397
+ else if (!hasIamRole && !isTainted) {
374
398
  const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { disk: undefined, nas: undefined } }, serviceName);
375
399
  role = deps.role;
376
400
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'VOLCENGINE_IAM_ROLE'));
@@ -392,6 +416,22 @@ const updateResource = async (context, fn, state) => {
392
416
  const trustedServices = (0, vefaasTypes_1.getTrustedServicesForFunction)(fn, context);
393
417
  await client.iam.updateRoleTrustPolicy(iamRoleInstance.id, (0, vefaasTypes_1.buildDefaultTrustPolicy)(trustedServices));
394
418
  }
419
+ // Check statement changes
420
+ const currentRoleConfig = currentIam?.role && typeof currentIam.role !== 'string' ? currentIam.role : undefined;
421
+ const desiredRoleConfig = fn.iam?.role && typeof fn.iam.role !== 'string' ? fn.iam.role : undefined;
422
+ const desiredIamStatements = desiredRoleConfig?.statements;
423
+ const currentStatementList = currentRoleConfig?.statements;
424
+ const iamChanged = JSON.stringify(currentStatementList) !== JSON.stringify(desiredIamStatements);
425
+ if (iamChanged && iamRoleInstance) {
426
+ await client.iam.updateRolePolicy(iamRoleInstance.id, desiredIamStatements);
427
+ }
428
+ // Check managed policy changes
429
+ const desiredManagedPolicies = desiredRoleConfig?.managed_policies;
430
+ const currentManagedPoliciesList = currentRoleConfig?.managed_policies;
431
+ const managedPoliciesChanged = JSON.stringify(currentManagedPoliciesList) !== JSON.stringify(desiredManagedPolicies);
432
+ if (managedPoliciesChanged && iamRoleInstance) {
433
+ await client.iam.updateManagedPolicies(iamRoleInstance.id, desiredManagedPolicies ?? []);
434
+ }
395
435
  }
396
436
  const config = (0, vefaasTypes_1.functionToVefaasConfig)(fn, {
397
437
  role: role?.trn,
@@ -412,7 +452,8 @@ const updateResource = async (context, fn, state) => {
412
452
  });
413
453
  const codePath = fn.code.path;
414
454
  const desiredCodeHash = (0, common_1.computeFileHash)(codePath);
415
- const desiredDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
455
+ const baseDefinition = (0, vefaasTypes_1.extractVefaasDefinition)(config, desiredCodeHash);
456
+ const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
416
457
  const currentDefinition = currentState.definition || {};
417
458
  const currentCodeHash = currentDefinition.codeHash;
418
459
  const codeChanged = currentCodeHash !== desiredCodeHash;
@@ -27,6 +27,8 @@ var ResourceTypeEnum;
27
27
  ResourceTypeEnum["ALIYUN_SLS_LOGSTORE"] = "ALIYUN_SLS_LOGSTORE";
28
28
  ResourceTypeEnum["ALIYUN_SLS_INDEX"] = "ALIYUN_SLS_INDEX";
29
29
  ResourceTypeEnum["ALIYUN_RAM_ROLE"] = "ALIYUN_RAM_ROLE";
30
+ ResourceTypeEnum["VOLCENGINE_IAM_ROLE"] = "VOLCENGINE_IAM_ROLE";
31
+ ResourceTypeEnum["TENCENT_SCF_ROLE"] = "TENCENT_SCF_ROLE";
30
32
  ResourceTypeEnum["ALIYUN_ECS_SECURITY_GROUP"] = "ALIYUN_ECS_SECURITY_GROUP";
31
33
  ResourceTypeEnum["ALIYUN_NAS_ACCESS_GROUP"] = "ALIYUN_NAS_ACCESS_GROUP";
32
34
  ResourceTypeEnum["ALIYUN_NAS_FILE_SYSTEM"] = "ALIYUN_NAS_FILE_SYSTEM";
@@ -122,6 +122,50 @@ const bucketWebsiteDomainSchema = {
122
122
  },
123
123
  ],
124
124
  };
125
+ const iamStatementPrincipalSchema = {
126
+ type: 'object',
127
+ minProperties: 1,
128
+ additionalProperties: { type: 'string' },
129
+ };
130
+ const iamStatementSchema = {
131
+ type: 'object',
132
+ properties: {
133
+ effect: { type: 'string', enum: ['Allow', 'Deny'] },
134
+ principal: iamStatementPrincipalSchema,
135
+ action: {
136
+ oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' }, minItems: 1 }],
137
+ },
138
+ resource: {
139
+ oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' }, minItems: 1 }],
140
+ },
141
+ condition: {
142
+ type: 'object',
143
+ additionalProperties: true,
144
+ },
145
+ },
146
+ required: ['effect', 'principal', 'action', 'resource'],
147
+ additionalProperties: false,
148
+ };
149
+ const iamResourceSchema = {
150
+ type: 'object',
151
+ properties: {
152
+ statements: {
153
+ type: 'array',
154
+ items: iamStatementSchema,
155
+ minItems: 1,
156
+ },
157
+ },
158
+ required: ['statements'],
159
+ additionalProperties: false,
160
+ };
161
+ const iamSchema = {
162
+ type: 'object',
163
+ properties: {
164
+ resource: iamResourceSchema,
165
+ },
166
+ required: ['resource'],
167
+ additionalProperties: false,
168
+ };
125
169
  exports.bucketSchema = {
126
170
  $id: 'https://serverlessinsight.geekfun.club/schemas/bucketschema.json',
127
171
  type: 'object',
@@ -183,6 +227,7 @@ exports.bucketSchema = {
183
227
  required: ['code'],
184
228
  additionalProperties: false,
185
229
  },
230
+ iam: iamSchema,
186
231
  },
187
232
  required: ['name'],
188
233
  additionalProperties: false,