export async function getOIDCToken()

in src/lib/awsConnectionParameters.ts [472:512]


export async function getOIDCToken(connectedService: string): Promise<string> {
    const jobId = tl.getVariable('System.JobId') || ''
    const planId = tl.getVariable('System.PlanId') || ''
    const projectId = tl.getVariable('System.TeamProjectId') || ''
    const hub = tl.getVariable('System.HostType') || ''
    const uri = tl.getVariable('System.CollectionUri') || ''
    const token = tl.getVariable('System.AccessToken')

    if (token == undefined) {
        throw new Error(
            'System.AccessToken is undefined. Ensure that you have enabled OAuth token access for your pipeline/agent job: https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=classic#systemaccesstoken'
        )
    }

    try {
        const authHandler = getHandlerFromToken(token)
        const response = await withRetries(
            async () => {
                const connection = new WebApi(uri, authHandler)
                const api: ITaskApi = await connection.getTaskApi()
                return await api.createOidcToken({}, projectId, hub, planId, jobId, connectedService)
            },
            {
                maxRetries: 5,
                delay: 5000,
                backoff: 3
            }
        )
        if (response === undefined || response.oidcToken === undefined) {
            throw new Error('Invalid response when requesting OIDC token.')
        }

        const claims = JSON.parse(Buffer.from(response.oidcToken.split('.')[1], 'base64').toString('utf-8'))

        console.log('OIDC Token generated: issuer: {%s} sub: {%s}, aud: {%s}', claims.iss, claims.sub, claims.aud)
        return response.oidcToken
    } catch (err) {
        console.log('Failed to generate OIDC token. May fall back to other (potentially invalid) credential sources.')
        throw err
    }
}