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 IMS_ENDPOINT = "ims.aliyuncs.com"; const IMS_API_VERSION = "2019-08-15"; const SERVICE_NAME = "ots.aliyuncs.com"; const LIST_PAGE_SIZE = 100; export interface ImsServiceCredential { serviceCredentialId: string; serviceCredentialName: string; userPrincipalName: string; status: "Active" | "Inactive"; createTime: string; serviceName: string; } export interface ImsCreatedServiceCredential extends ImsServiceCredential { serviceCredentialSecret: string; } export interface ImsErrorDetails { upstreamCode?: string; upstreamRequestId?: string; upstreamStatus?: number; [key: string]: unknown; } export interface MappedImsError { code: string; httpStatus: number; message: string; details: ImsErrorDetails; } export function getImsClient(config: AppConfig): Ims20190815 { return new Ims20190815( new $OpenApiUtil.Config({ accessKeyId: config.access_key_id ?? "", accessKeySecret: config.access_key_secret ?? "", endpoint: IMS_ENDPOINT, }), ); } interface CallApiOptions { action: string; query?: Record; } interface CallApiResult { statusCode?: number; body?: Record; } async function callIms( client: Ims20190815, options: CallApiOptions, ): Promise { const params = new $OpenApiUtil.Params({ action: options.action, version: IMS_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 normaliseStatus(value: unknown): "Active" | "Inactive" { return value === "Inactive" ? "Inactive" : "Active"; } function normaliseServiceCredential(raw: unknown): ImsServiceCredential { const record = asRecord(raw); return { serviceCredentialId: asString(record.ServiceCredentialId), serviceCredentialName: asString(record.ServiceCredentialName), userPrincipalName: asString(record.UserPrincipalName), status: normaliseStatus(record.Status), createTime: asString(record.CreateTime), serviceName: asString(record.ServiceName) || SERVICE_NAME, }; } function extractServiceCredentialList( body: Record, ): unknown[] { const container = body.ServiceCredentials; if (Array.isArray(container)) return container; if (container && typeof container === "object") { const inner = (container as Record).ServiceCredential; if (Array.isArray(inner)) return inner; } return []; } export async function listServiceCredentials( client: Ims20190815, ): Promise { const result = await callIms(client, { action: "ListServiceCredentials", query: { AllUsers: true, ServiceName: SERVICE_NAME, MaxResults: LIST_PAGE_SIZE, }, }); const body = asRecord(result.body); return extractServiceCredentialList(body).map(normaliseServiceCredential); } export async function createImsUser( client: Ims20190815, userName: string, accountId: string, ): Promise<{ userName: string; userPrincipalName: string }> { const userPrincipalName = `${userName}@${accountId}.onaliyun.com`; const result = await callIms(client, { action: "CreateUser", query: { UserPrincipalName: userPrincipalName, DisplayName: "OTS API Key", }, }); const body = asRecord(result.body); const user = asRecord(body.User); return { userName: asString(user.UserPrincipalName) ? userName : userName, userPrincipalName: asString(user.UserPrincipalName) || userPrincipalName, }; } export async function getAccountId(config: AppConfig): Promise { const stsClient = new Ims20190815( new $OpenApiUtil.Config({ accessKeyId: config.access_key_id ?? "", accessKeySecret: config.access_key_secret ?? "", endpoint: "sts.aliyuncs.com", }), ); const params = new $OpenApiUtil.Params({ action: "GetCallerIdentity", version: "2015-04-01", protocol: "HTTPS", pathname: "/", method: "POST", authType: "AK", style: "RPC", reqBodyType: "formData", bodyType: "json", }); const request = new $OpenApiUtil.OpenApiRequest({ query: OpenApiUtil.query({}), }); const result = (await stsClient.callApi( params, request, new $Util.RuntimeOptions({}), )) as { body?: Record }; const body = asRecord(result.body); return asString(body.AccountId); } export async function createServiceCredential( client: Ims20190815, args: { serviceCredentialName: string; userPrincipalName: string; credentialAgeDays?: number; }, ): Promise { const query: Record = { ServiceName: SERVICE_NAME, ServiceCredentialName: args.serviceCredentialName, UserPrincipalName: args.userPrincipalName, }; if (args.credentialAgeDays && args.credentialAgeDays > 0) { query.CredentialAgeDays = args.credentialAgeDays; } const result = await callIms(client, { action: "CreateServiceCredential", query, }); const body = asRecord(result.body); const raw = asRecord(body.ServiceCredential); return { ...normaliseServiceCredential(raw), serviceCredentialSecret: asString(raw.ServiceCredentialSecret), }; } export async function deleteServiceCredential( client: Ims20190815, args: { serviceCredentialId: string; userPrincipalName: string }, ): Promise { await callIms(client, { action: "DeleteServiceCredential", query: { ServiceCredentialId: args.serviceCredentialId, UserPrincipalName: args.userPrincipalName, }, }); } export async function updateServiceCredentialStatus( client: Ims20190815, args: { serviceCredentialId: string; userPrincipalName: string; status: "Active" | "Inactive"; }, ): Promise { await callIms(client, { action: "UpdateServiceCredential", query: { ServiceCredentialId: args.serviceCredentialId, UserPrincipalName: args.userPrincipalName, Status: args.status, }, }); } export function mapImsError(error: unknown): MappedImsError { 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 IMS error"); const details: ImsErrorDetails = { upstreamCode, upstreamRequestId, upstreamStatus, }; if ( upstreamCode === "NoPermission" || upstreamCode?.startsWith("NoPermission.") || upstreamCode === "Forbidden.RAM" || upstreamCode?.startsWith("Forbidden.") ) { return { code: "FORBIDDEN", httpStatus: 403, message: "当前 AccessKey 缺少 RAM/IMS 权限,无法管理服务凭证。请改用主账号 AK,或为当前子账号挂载 AliyunRAMReadOnlyAccess(仅查看)或 AliyunRAMFullAccess(含管理)。原始错误:" + message, details, }; } if ( upstreamCode === "EntityNotExist.ServiceCredential" || upstreamCode === "EntityNotExist.AccessKey" || upstreamCode?.startsWith("EntityNotExist.") ) { return { code: "NOT_FOUND", httpStatus: 404, message, details, }; } if ( upstreamCode === "InvalidParameter" || upstreamCode?.startsWith("InvalidParameter.") || upstreamCode === "MissingServiceCredentialName" || upstreamCode === "MissingUserPrincipalName" || upstreamCode === "MissingServiceCredentialId" || upstreamCode?.startsWith("Missing") ) { return { code: "VALIDATION_ERROR", httpStatus: 400, message, details, }; } if (upstreamCode?.startsWith("DeleteConflict.")) { return { code: "DELETE_CONFLICT", httpStatus: 409, message: "删除前需要先禁用该服务凭证。", details, }; } if (upstreamCode?.startsWith("LimitExceeded.")) { return { code: "LIMIT_EXCEEDED", httpStatus: 409, message: "已达到服务凭证数量上限,请先删除不再使用的凭证后再创建新的。", details, }; } return { code: "IMS_UPSTREAM_ERROR", httpStatus: 502, message, details, }; }