"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assumeRole = void 0;
exports.getAWSCredentialsFromEKS = getAWSCredentialsFromEKS;
const fs_1 = require("fs");
const client_sts_1 = require("@aws-sdk/client-sts");
const actions_core_1 = require("@segment/actions-core");
const uuid_1 = require("@lukeed/uuid");
const awsCredentialsCache = {
    expires: 0,
    credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' }
};
function getToken() {
    const tokenFilepath = process.env['AWS_WEB_IDENTITY_TOKEN_FILE'] || '/var/run/secrets/kubernetes.io/serviceaccount/token';
    return (0, fs_1.readFileSync)(tokenFilepath, 'utf-8');
}
async function getAWSRoleARNFromK8sAPI(request, K8sToken) {
    const K8sApiResponse = await request('https://kubernetes.default.svc/api/v1/namespaces/default/serviceaccounts/pod-service-account', {
        headers: {
            Authorization: `Bearer ${K8sToken}`
        }
    });
    const roleArn = K8sApiResponse.data?.metadata?.annotations?.['eks.amazonaws.com/role-arn'];
    if (!roleArn) {
        throw new Error('Unable to retrieve AWS Role ARN from Kubernetes API.');
    }
    return roleArn;
}
async function getCredentialsFromSTS(request, awsRoleARN, token) {
    const stsResponse = await request(`https://sts.us-west-2.amazonaws.com/?` +
        `Action=AssumeRoleWithWebIdentity` +
        `&DurationSeconds=3600` +
        `&RoleSessionName=integrations-monoservice` +
        `&RoleArn=${awsRoleARN}` +
        `&WebIdentityToken=${token}` +
        `&Version=2011-06-15`, {
        method: 'GET',
        headers: {
            'User-Agent': 'segment/integrations-monoservice',
            Accept: 'application/json'
        }
    });
    return {
        accessKeyId: stsResponse.data.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials.AccessKeyId,
        secretAccessKey: stsResponse.data.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials.SecretAccessKey,
        sessionToken: stsResponse.data.AssumeRoleWithWebIdentityResponse.AssumeRoleWithWebIdentityResult.Credentials.SessionToken
    };
}
async function getAWSCredentialsFromEKS(request) {
    if (awsCredentialsCache.expires > Date.now()) {
        return awsCredentialsCache.credentials;
    }
    const token = getToken();
    const awsRoleARN = process.env['AWS_ROLE_ARN'] || (await getAWSRoleARNFromK8sAPI(request, token));
    const credentials = await getCredentialsFromSTS(request, awsRoleARN, token);
    awsCredentialsCache.expires = Date.now() + 3300000;
    awsCredentialsCache.credentials = credentials;
    return credentials;
}
const assumeRole = async (roleArn, externalId, region) => {
    const intermediaryARN = process.env.AMAZON_KINESIS_ACTIONS_ROLE_ADDRESS;
    const intermediaryExternalId = process.env.AMAZON_KINESIS_ACTIONS_EXTERNAL_ID;
    const intermediaryCreds = await getSTSCredentials(intermediaryARN, intermediaryExternalId, region);
    return getSTSCredentials(roleArn, externalId, region, intermediaryCreds);
};
exports.assumeRole = assumeRole;
const getSTSCredentials = async (roleId, externalId, region, credentials) => {
    const options = { credentials, region: region };
    const stsClient = new client_sts_1.STSClient(options);
    const roleSessionName = (0, uuid_1.v4)();
    const command = new client_sts_1.AssumeRoleCommand({
        RoleArn: roleId,
        RoleSessionName: roleSessionName,
        ExternalId: externalId
    });
    const result = await stsClient.send(command);
    if (!result.Credentials ||
        !result.Credentials.AccessKeyId ||
        !result.Credentials.SecretAccessKey ||
        !result.Credentials.SessionToken) {
        throw new actions_core_1.IntegrationError('Failed to assume role', actions_core_1.ErrorCodes.INVALID_AUTHENTICATION, 403);
    }
    return {
        accessKeyId: result.Credentials.AccessKeyId,
        secretAccessKey: result.Credentials.SecretAccessKey,
        sessionToken: result.Credentials.SessionToken
    };
};
//# sourceMappingURL=sts.js.map