Skip to content

Commit

Permalink
Cleaned up and working Azure token acquisition for engine
Browse files Browse the repository at this point in the history
  • Loading branch information
jgainerdewar committed Nov 19, 2022
1 parent dfc8be3 commit 57eb1d5
Showing 1 changed file with 33 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ package cloud.nio.impl.drs

import cats.syntax.validated._
import com.azure.core.credential.TokenRequestContext
import com.azure.core.management.AzureEnvironment
import com.azure.core.management.profile.AzureProfile
import com.azure.identity.DefaultAzureCredentialBuilder
import com.google.auth.oauth2.{AccessToken, OAuth2Credentials}
import com.typesafe.config.Config
import common.validation.ErrorOr.ErrorOr
import net.ceedubs.ficus.Ficus._

import java.time.{Duration => jDuration}
import java.util.concurrent.TimeUnit
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}

/**
* This trait allows us to abstract away different token attainment strategies
Expand Down Expand Up @@ -45,12 +50,36 @@ object GoogleDrsCredentials {

case class AzureDrsCredentials(identityClientId: Option[String]) extends DrsCredentials {

final val tokenAcquisitionTimeout = new jDuration(30, TimeUnit.SECONDS)

val azureProfile = new AzureProfile(AzureEnvironment.AZURE)
val tokenScope = "https://management.azure.com/.default"

def tokenRequestContext: TokenRequestContext = {
val trc = new TokenRequestContext()
trc.addScopes(tokenScope)
trc
}

def defaultCredentialBuilder: DefaultAzureCredentialBuilder =
new DefaultAzureCredentialBuilder()
.authorityHost(azureProfile.getEnvironment.getActiveDirectoryEndpoint)

def getAccessToken: ErrorOr[String] = {
val credentials = identityClientId.foldLeft(new DefaultAzureCredentialBuilder()) {
val credentials = identityClientId.foldLeft(defaultCredentialBuilder) {
(builder, clientId) => builder.managedIdentityClientId(clientId)
}.build()
val tokenRequestContext = new TokenRequestContext()
tokenRequestContext.addScopes(".default")
credentials.getToken(tokenRequestContext).block().getToken.validNel

Try(
credentials
.getToken(tokenRequestContext)
.block(tokenAcquisitionTimeout)
) match {
case Success(token) => token.getToken.validNel
case Failure(error) =>
Option(error.getMessage) // it's possible the message is null
.getOrElse(error.toString)
.invalidNel
}
}
}

0 comments on commit 57eb1d5

Please sign in to comment.