Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "User Service Account Impersonation" as an auth mode for GCP #7224

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ final private[spi] case class UnixPath(path: String) extends CharSequence {

def isAbsolute: Boolean = UnixPath.isAbsolute(path)

def isEmpty: Boolean = path.isEmpty
override def isEmpty: Boolean = path.isEmpty
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compiler was breaking without this, not related to PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, what is your Java version?

I believe Cromwell is usually compiled with Java 11, and CharSequence::isEmpty is "Since: 15"

This override will need to be fixed, but maybe not right now?

Btw, I use SDKMAN! to keep all my Java SDKs under control. The JDK referenced by Cromwell's config isn't available for my M2 mac. I've just changed it on my machine to a newer 11 Temurin release.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! That was the issue. Have you had a moment to review the PR otherwise?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@harrismendell

Have you had a moment to review the PR otherwise?

I've glanced at it, but I'm not an official committer at the moment. I've got multiple of own PRs in the queue to get reviewed 😅

In the meantime I've just coalesced my commits into a fork and just compile and run that melange to keep moving.


def hasTrailingSeparator: Boolean = UnixPath.hasTrailingSeparator(path)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,21 @@ object GoogleConfiguration {
UserServiceAccountMode(name)
}

def userServiceAccountImpersonationAuth(authConfig: Config, name: String): ErrorOr[GoogleAuthMode] = validate {
authConfig.getAs[String]("json-file") match {
case Some(json) => UserServiceAccountImpersonationMode(name, JsonFileFormat(json))
case None => UserServiceAccountImpersonationMode(name)
}
}

val name = authConfig.getString("name")
val scheme = authConfig.getString("scheme")
scheme match {
case "service_account" => serviceAccountAuth(authConfig, name)
case "user_account" => userAccountAuth(authConfig, name)
case "application_default" => applicationDefaultAuth(name)
case "user_service_account" => userServiceAccountAuth(name)
case "user_service_account_impersonation" => userServiceAccountImpersonationAuth(authConfig, name)
case "mock" => MockAuthMode(name).validNel
case wut => s"Unsupported authentication scheme: $wut".invalidNel
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ package cromwell.cloudsupport.gcp.auth
import java.io.{ByteArrayInputStream, FileNotFoundException, InputStream}
import java.net.HttpURLConnection._
import java.nio.charset.StandardCharsets

import better.files.File
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.http.{HttpResponseException, HttpTransport}
import com.google.api.client.json.gson.GsonFactory
import com.google.auth.Credentials
import com.google.auth.http.HttpTransportFactory
import com.google.auth.oauth2.{GoogleCredentials, OAuth2Credentials, ServiceAccountCredentials, UserCredentials}
import com.google.auth.oauth2.{GoogleCredentials, ImpersonatedCredentials, OAuth2Credentials, ServiceAccountCredentials, UserCredentials}
import com.google.cloud.NoCredentials
import com.typesafe.scalalogging.LazyLogging
import cromwell.cloudsupport.gcp.auth.ApplicationDefaultMode.applicationDefaultCredentials
Expand Down Expand Up @@ -43,6 +42,7 @@ object GoogleAuthMode {
lazy val HttpTransportFactory: HttpTransportFactory = () => httpTransport

val UserServiceAccountKey = "user_service_account_json"
val UserServiceAccountEmailKey = "user_service_account_email"
val DockerCredentialsEncryptionKeyNameKey = "docker_credentials_key_name"
val DockerCredentialsTokenKey = "docker_credentials_token"

Expand Down Expand Up @@ -73,6 +73,18 @@ object GoogleAuthMode {
private def refreshCredentials(credentials: Credentials): Unit = {
credentials.refresh()
}

def createServiceAccountCredentials(fileFormat: CredentialFileFormat): ServiceAccountCredentials = {
val credentialsFile = File(fileFormat.file)
checkReadable(credentialsFile)

fileFormat match {
case PemFileFormat(accountId, _) =>
ServiceAccountCredentials.fromPkcs8(accountId, accountId, credentialsFile.contentAsString, null, null)
case _: JsonFileFormat => ServiceAccountCredentials.fromStream(credentialsFile.newInputStream)
}
}

}

sealed trait GoogleAuthMode extends LazyLogging {
Expand Down Expand Up @@ -115,12 +127,18 @@ sealed trait GoogleAuthMode extends LazyLogging {
*/
private[auth] var credentialsValidation: CredentialsValidation = refreshCredentials

protected def validateCredentials[A <: GoogleCredentials](credential: A,
scopes: Iterable[String]): GoogleCredentials = {
val scopedCredentials = credential.createScoped(scopes.asJavaCollection)
Try(credentialsValidation(scopedCredentials)) match {
case Failure(ex) => throw new RuntimeException(s"Google credentials are invalid: ${ex.getMessage}", ex)
case Success(_) => scopedCredentials
protected def validateCredentials[A <: GoogleCredentials](
credential: A,
scopes: Iterable[String]
): GoogleCredentials = {
val credentialsToValidate =
if (scopes != null) credential.createScoped(scopes.asJavaCollection)
else credential
Try(credentialsValidation(credentialsToValidate)) match {
case Failure(ex) =>
throw new RuntimeException(s"Google credentials are invalid: ${ex.getMessage}", ex)
case Success(_) =>
credentialsToValidate
}
}
}
Expand Down Expand Up @@ -149,14 +167,10 @@ final case class ServiceAccountMode(override val name: String,
private val credentialsFile = File(fileFormat.file)
checkReadable(credentialsFile)

private lazy val serviceAccountCredentials: ServiceAccountCredentials = {
fileFormat match {
case PemFileFormat(accountId, _) =>
logger.warn("The PEM file format will be deprecated in the upcoming Cromwell version. Please use JSON instead.")
ServiceAccountCredentials.fromPkcs8(accountId, accountId, credentialsFile.contentAsString, null, null)
case _: JsonFileFormat => ServiceAccountCredentials.fromStream(credentialsFile.newInputStream)
}
if (fileFormat.isInstanceOf[PemFileFormat]) {
logger.warn("The PEM file format will be deprecated in the upcoming Cromwell version. Please use JSON instead.")
}
private lazy val serviceAccountCredentials: ServiceAccountCredentials = createServiceAccountCredentials(fileFormat)

override def credentials(unusedOptions: OptionLookup,
scopes: Iterable[String]): GoogleCredentials = {
Expand Down Expand Up @@ -206,6 +220,37 @@ final case class ApplicationDefaultMode(name: String) extends GoogleAuthMode {
}
}

final case class UserServiceAccountImpersonationMode(
override val name: String,
jsonFileFormat: Option[JsonFileFormat] = None // Optional credential file format
) extends GoogleAuthMode {

private def extractServiceAccount(options: OptionLookup): String = {
extract(options, UserServiceAccountEmailKey)
}

override def credentials(options: OptionLookup, scopes: Iterable[String]): GoogleCredentials = {
// Credentials for the source service account that should have
// roles/iam.serviceAccountTokenCreator on the target service account
val credentials = jsonFileFormat match {
case Some(format) => createServiceAccountCredentials(format)
case None => GoogleCredentials.getApplicationDefault
}

val impersonatedCredentials = ImpersonatedCredentials.create(
credentials,
extractServiceAccount(options),
null,
scopes.toList.asJava,
3600
)

// We don't pass in scopes because they are added to the credentials
// when we create ImpersonatedCredentials above.
validateCredentials(impersonatedCredentials, null)
}
}

sealed trait ClientSecrets {
val clientId: String
val clientSecret: String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,5 @@ object GoogleAuthModeSpec extends ServiceAccountTestSupport {

lazy val refreshTokenOptions: OptionLookup = Map("refresh_token" -> "the_refresh_token")
lazy val userServiceAccountOptions: OptionLookup = Map("user_service_account_json" -> serviceAccountJsonContents)
lazy val userServiceAccountImpersonationOptions: OptionLookup = Map("user_service_account_email" -> "the email")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cromwell.cloudsupport.gcp.auth

import common.assertion.CromwellTimeoutSpec
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class UserServiceAccountImpersonationModeSpec extends AnyFlatSpec with CromwellTimeoutSpec with Matchers {

behavior of "UserServiceAccountImpersonationMode"

it should "generate a non-validated credential" in {
val impersonationMode = UserServiceAccountImpersonationMode("user-service-account-impersonation")
val workflowOptions = GoogleAuthModeSpec.userServiceAccountImpersonationOptions
impersonationMode.credentialsValidation = GoogleAuthMode.NoCredentialsValidation
val credentials = impersonationMode.credentials(workflowOptions)
credentials.getAuthenticationType should be("OAuth2")
}

it should "fail to generate credentials without a user_service_account_email workflow option" in {
val impersonationMode = UserServiceAccountImpersonationMode("user-service-account-impersonation")
val exception = intercept[OptionLookupException](impersonationMode.credentials())
exception.getMessage should be("user_service_account_email")
}
}