This commit is contained in:
2026-03-14 22:31:52 +08:00
parent 327cb02e55
commit 51a909f648

View File

@@ -1256,22 +1256,14 @@ interface AlibabaCloudInstanceIdentityAudienceMeta {
exp: number;
aud: string;
jti?: string;
scope?: string;
args?: string[];
}
export type AlibabaCloudInstanceIdentityMode = "normal" | "secured";
export interface AlibabaCloudInstanceIdentityOptions {
scope?: string;
args?: string[];
}
// https://help.aliyun.com/zh/ecs/user-guide/use-instance-identities
export async function fetchAlibabaCloudInstanceIdentityV1(
audience: string,
mode?: AlibabaCloudInstanceIdentityMode,
options?: AlibabaCloudInstanceIdentityOptions,
): Promise<string> {
let metaDataToken = null;
if (!mode) {
@@ -1302,11 +1294,6 @@ export async function fetchAlibabaCloudInstanceIdentityV1(
jti: "jti-" + Date.now() + "-" + Math.random(),
} as AlibabaCloudInstanceIdentityAudienceMeta;
if (options) {
if (options.scope) audienceMeta.scope = options.scope;
if (options.args) audienceMeta.args = options.args;
}
const pkcs7Options = {};
if (metaDataToken) {
pkcs7Options["X-aliyun-ecs-metadata-token"] = metaDataToken;
@@ -1386,10 +1373,17 @@ async function getSecretValueViaHatterCli(key: string): Promise<string> {
export type SecretValueRunEnv = "ALIBABA_CLOUD" | "HATTER_CLI";
export function getRunEnv(): stirng | null {
return getEnv("RUN_ENV");
}
export async function getSecretValue(
key: string,
runEnv?: SecretValueRunEnv,
): Promise<string> {
if (!runEnv) {
runEnv = getRunEnv();
}
if (runEnv == "ALIBABA_CLOUD") {
return await getSecretValueViaAlibabaCloudInstanceIdentity(key);
}
@@ -1412,19 +1406,16 @@ export interface AssumeRoleByKeyResponse {
export async function assumeRoleByKeyViaAlibabaCloudInstanceIdentity(
roleArn: string,
policy?: string,
mode?: AlibabaCloudInstanceIdentityMode,
): Promise<StsToken> {
const pkcs7 = await fetchAlibabaCloudInstanceIdentityV1(
"hatter.ink",
"/cloud/alibaba_cloud/assume_role_by_key.json",
mode,
{
scope: "assume_role",
args: [roleArn, policy ?? null],
},
);
const httpAssumeRoleResponse = await fetchDataWithTimeout(
`https://global.hatter.ink/cloud/alibaba_cloud/assume_role_by_key.json`,
`https://global.hatter.ink/cloud/alibaba_cloud/assume_role_by_key.json?roleArn=${
encodeURIComponent(roleArn)
}`,
{
headers: {
"Authorization": `PKCS7 ${pkcs7}`,
@@ -1448,3 +1439,16 @@ export async function assumeRoleByKeyViaAlibabaCloudInstanceIdentity(
}
return assumeRoleResponse.data;
}
export async function assumeRoleByKey(
roleArn: string,
runEnv?: SecretValueRunEnv,
): Promise<StsToken> {
if (!runEnv) {
runEnv = getRunEnv();
}
if (runEnv == "ALIBABA_CLOUD") {
return await assumeRoleByKeyViaAlibabaCloudInstanceIdentity(roleArn);
}
throw new Error(`Run env not supported: ${runEnv}`);
}