import Ims20190815 from "@alicloud/ims20190815"; import { $OpenApiUtil, OpenApiUtil } from "@alicloud/openapi-core"; import * as $Util from "@alicloud/tea-util"; import type { AppConfig } from "@tablestore/tablestore-agent-shared"; const RAM_ENDPOINT = "ram.aliyuncs.com"; const RAM_API_VERSION = "2015-05-01"; export interface RamPolicy { policyName: string; policyType: "System" | "Custom"; description: string; defaultVersion?: string; attachDate?: string; } export interface RamErrorDetails { upstreamCode?: string; upstreamRequestId?: string; upstreamStatus?: number; [key: string]: unknown; } export interface MappedRamError { code: string; httpStatus: number; message: string; details: RamErrorDetails; } export function getRamClient(config: AppConfig): Ims20190815 { return new Ims20190815( new $OpenApiUtil.Config({ accessKeyId: config.access_key_id ?? "", accessKeySecret: config.access_key_secret ?? "", endpoint: RAM_ENDPOINT, }), ); } export function extractUserName(userPrincipalName: string): string { const atIndex = userPrincipalName.indexOf("@"); return atIndex > 0 ? userPrincipalName.slice(0, atIndex) : userPrincipalName; } export function extractAccountId(userPrincipalName: string): string { const atIndex = userPrincipalName.indexOf("@"); if (atIndex < 0) return ""; const domain = userPrincipalName.slice(atIndex + 1); const dotIndex = domain.indexOf("."); return dotIndex > 0 ? domain.slice(0, dotIndex) : domain; } interface CallApiOptions { action: string; query?: Record; } interface CallApiResult { statusCode?: number; body?: Record; } async function callRam( client: Ims20190815, options: CallApiOptions, ): Promise { const params = new $OpenApiUtil.Params({ action: options.action, version: RAM_API_VERSION, protocol: "HTTPS", pathname: "/", method: "POST", authType: "AK", style: "RPC", reqBodyType: "formData", bodyType: "json", }); const request = new $OpenApiUtil.OpenApiRequest({ query: OpenApiUtil.query(options.query ?? {}), }); const result = (await client.callApi( params, request, new $Util.RuntimeOptions({}), )) as CallApiResult; return result; } function asRecord(value: unknown): Record { return value && typeof value === "object" ? (value as Record) : {}; } function asString(value: unknown): string { return typeof value === "string" ? value : ""; } function normalisePolicyType(value: unknown): "System" | "Custom" { return value === "Custom" ? "Custom" : "System"; } function normalisePolicy(raw: unknown): RamPolicy { const record = asRecord(raw); return { policyName: asString(record.PolicyName), policyType: normalisePolicyType(record.PolicyType), description: asString(record.Description), defaultVersion: asString(record.DefaultVersion) || undefined, attachDate: asString(record.AttachDate) || undefined, }; } function extractPolicyList(body: Record): unknown[] { const container = body.Policies; if (Array.isArray(container)) return container; if (container && typeof container === "object") { const inner = (container as Record).Policy; if (Array.isArray(inner)) return inner; } return []; } export async function listPoliciesForUser( client: Ims20190815, userName: string, ): Promise { const result = await callRam(client, { action: "ListPoliciesForUser", query: { UserName: userName }, }); const body = asRecord(result.body); return extractPolicyList(body).map(normalisePolicy); } export async function attachPolicyToUser( client: Ims20190815, args: { userName: string; policyName: string; policyType: string }, ): Promise { await callRam(client, { action: "AttachPolicyToUser", query: { UserName: args.userName, PolicyName: args.policyName, PolicyType: args.policyType, }, }); } export async function detachPolicyFromUser( client: Ims20190815, args: { userName: string; policyName: string; policyType: string }, ): Promise { await callRam(client, { action: "DetachPolicyFromUser", query: { UserName: args.userName, PolicyName: args.policyName, PolicyType: args.policyType, }, }); } // --------------------------------------------------------------------------- // Custom policy management // --------------------------------------------------------------------------- export interface PolicyVersion { versionId: string; isDefaultVersion: boolean; createDate?: string; } export async function createPolicy( client: Ims20190815, args: { policyName: string; policyDocument: string; description: string }, ): Promise { await callRam(client, { action: "CreatePolicy", query: { PolicyName: args.policyName, PolicyDocument: args.policyDocument, Description: args.description, }, }); } export async function getPolicy( client: Ims20190815, policyName: string, ): Promise<{ defaultVersion: string } | null> { try { const result = await callRam(client, { action: "GetPolicy", query: { PolicyName: policyName, PolicyType: "Custom" }, }); const body = asRecord(result.body); const policy = asRecord(body.Policy); return { defaultVersion: asString(policy.DefaultVersion) || "v1", }; } catch (err) { const record = asRecord(err); const code = asString(record.code) || asString(asRecord(record.data).Code); if ( code === "EntityNotExist.Policy" || code?.startsWith("EntityNotExist.") ) { return null; } throw err; } } export async function getPolicyVersion( client: Ims20190815, policyName: string, versionId: string, ): Promise { const result = await callRam(client, { action: "GetPolicyVersion", query: { PolicyName: policyName, PolicyType: "Custom", VersionId: versionId, }, }); const body = asRecord(result.body); const policyVersion = asRecord(body.PolicyVersion); return asString(policyVersion.PolicyDocument); } export async function createPolicyVersion( client: Ims20190815, args: { policyName: string; policyDocument: string }, ): Promise { await callRam(client, { action: "CreatePolicyVersion", query: { PolicyName: args.policyName, PolicyDocument: args.policyDocument, SetAsDefault: "true", }, }); } function extractPolicyVersionList(body: Record): unknown[] { const container = body.PolicyVersions; if (Array.isArray(container)) return container; if (container && typeof container === "object") { const inner = (container as Record).PolicyVersion; if (Array.isArray(inner)) return inner; } return []; } export async function listPolicyVersions( client: Ims20190815, policyName: string, ): Promise { const result = await callRam(client, { action: "ListPolicyVersions", query: { PolicyName: policyName, PolicyType: "Custom" }, }); const body = asRecord(result.body); return extractPolicyVersionList(body).map((raw) => { const record = asRecord(raw); return { versionId: asString(record.VersionId), isDefaultVersion: record.IsDefaultVersion === true || record.IsDefaultVersion === "true", createDate: asString(record.CreateDate) || undefined, }; }); } export async function deletePolicyVersion( client: Ims20190815, args: { policyName: string; versionId: string }, ): Promise { await callRam(client, { action: "DeletePolicyVersion", query: { PolicyName: args.policyName, VersionId: args.versionId }, }); } export async function deletePolicy( client: Ims20190815, policyName: string, ): Promise { await callRam(client, { action: "DeletePolicy", query: { PolicyName: policyName }, }); } export async function deleteUser( client: Ims20190815, userName: string, ): Promise { await callRam(client, { action: "DeleteUser", query: { UserName: userName }, }); } const MAX_POLICY_VERSIONS = 5; export async function ensureVersionCapacity( client: Ims20190815, policyName: string, ): Promise { const versions = await listPolicyVersions(client, policyName); if (versions.length < MAX_POLICY_VERSIONS) return; const nonDefault = versions .filter((v) => !v.isDefaultVersion) .sort((a, b) => (a.createDate ?? "").localeCompare(b.createDate ?? "")); if (nonDefault.length > 0) { await deletePolicyVersion(client, { policyName, versionId: nonDefault[0].versionId, }); } } export function mapRamError(error: unknown): MappedRamError { const record = asRecord(error); const data = asRecord(record.data); const upstreamCode = asString(record.code) || asString(data.Code) || undefined; const upstreamRequestId = asString(data.RequestId) || asString(record.requestId) || undefined; const upstreamStatus = typeof record.statusCode === "number" ? record.statusCode : typeof record.status === "number" ? record.status : undefined; const message = error instanceof Error ? error.message : asString((record as { message?: unknown }).message) || String(error ?? "Unknown RAM error"); const details: RamErrorDetails = { upstreamCode, upstreamRequestId, upstreamStatus, }; if ( upstreamCode === "NoPermission" || upstreamCode?.startsWith("NoPermission.") || upstreamCode === "Forbidden.RAM" || upstreamCode?.startsWith("Forbidden.") ) { return { code: "FORBIDDEN", httpStatus: 403, message: "当前 AccessKey 缺少 RAM 权限,无法管理用户策略。请使用主账号 AK 或为当前子账号挂载 AliyunRAMFullAccess。原始错误:" + message, details, }; } if ( upstreamCode === "EntityNotExist.User" || upstreamCode === "EntityNotExist.Policy" || upstreamCode?.startsWith("EntityNotExist.") ) { return { code: "NOT_FOUND", httpStatus: 404, message, details, }; } if ( upstreamCode === "EntityAlreadyExists.User.Policy" || upstreamCode?.startsWith("EntityAlreadyExists.") ) { return { code: "CONFLICT", httpStatus: 409, message: "该策略已挂载到此用户。", details, }; } if ( upstreamCode === "InvalidParameter" || upstreamCode?.startsWith("InvalidParameter.") || upstreamCode?.startsWith("Missing") ) { return { code: "VALIDATION_ERROR", httpStatus: 400, message, details, }; } if (upstreamCode?.startsWith("LimitExceeded.")) { return { code: "LIMIT_EXCEEDED", httpStatus: 409, message: "已达到策略数量上限。", details, }; } return { code: "RAM_UPSTREAM_ERROR", httpStatus: 502, message, details, }; }