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

Issue 204 - Bound tokens for incluster configuration #218

Merged
merged 4 commits into from
Sep 8, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 5 additions & 2 deletions client/src/main/scala/skuber/api/Configuration.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import java.util.{Base64, Date}
import org.yaml.snakeyaml.Yaml
import skuber.Namespace
import skuber.api.client._
import skuber.api.client.token.{FileTokenAuthRefreshable, FileTokenConfiguration}

import scala.io.Source

/**
Expand Down Expand Up @@ -258,7 +260,9 @@ object Configuration {
namespace <- maybeNamespace
hostPort = s"https://$host${if (port.length > 0) ":" + port else ""}"
cluster = Cluster(server = hostPort, certificateAuthority = ca)
ctx = Context(cluster, TokenAuth(token), Namespace.forName(namespace))
ctx = Context(cluster = cluster,
authInfo = FileTokenAuthRefreshable(FileTokenConfiguration(cachedAccessToken= Some(token), tokenPath = Some(tokenPath))),
namespace = Namespace.forName(namespace))
} yield Configuration(clusters = Map("default" -> cluster),
contexts = Map("default" -> ctx),
currentContext = ctx)
Expand Down Expand Up @@ -297,5 +301,4 @@ object Configuration {
}
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ object PodExecImpl {
requestContext.log.info(s"Connected to container ${containerPrintName} of pod ${podName}")
close.future.foreach { _ =>
requestContext.log.info(s"Close the connection of container ${containerPrintName} of pod ${podName}")
promise.success(None)
promise.trySuccess(None)
}
}
Future.sequence(Seq(connected, close.future, promise.future)).map { _ => () }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package skuber.api.client.token

import org.joda.time.DateTime
import skuber.K8SException
import skuber.api.client.{AuthProviderRefreshableAuth, Status}

import scala.concurrent.duration.{Duration, DurationInt}
import scala.util.{Failure, Success}

final case class FileTokenAuthRefreshable(config: FileTokenConfiguration) extends TokenAuthRefreshable with FileReaderComponent {}

final case class FileTokenConfiguration(
cachedAccessToken: Option[String],
tokenPath: Option[String],
Copy link
Owner

Choose a reason for hiding this comment

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

tokenPath should be mandatory rather than Optional

Copy link
Author

Choose a reason for hiding this comment

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

Changed

refreshInterval: Duration = 5.minutes,
)

trait TokenAuthRefreshable extends AuthProviderRefreshableAuth { self: ContentReaderComponent =>
val config: FileTokenConfiguration

private val refreshInterval: Duration = config.refreshInterval
@volatile private var cachedToken: Option[RefreshableToken] = config.cachedAccessToken.map(buildRefreshableToken)

private val tokenPath: String = {
config.tokenPath.getOrElse {
throw new K8SException(
Status(reason = Some("token path not found, please provide the token path for refreshing the token"))
)
}
}

override def name: String = "file-token"
override def toString: String = """FileTokenAuthRefreshable(accessToken=<redacted>)""".stripMargin

override def refreshToken: RefreshableToken = {
val refreshedToken = buildRefreshableToken(generateToken)
cachedToken = Some(refreshedToken)
refreshedToken
}

override def generateToken: String = {
val maybeToken = contentReader.read(tokenPath)
maybeToken match {
case Success(token) => token
case Failure(e) => throw new K8SException(Status(reason = Option(e.getMessage)))
}
}

override def isTokenExpired(refreshableToken: RefreshableToken): Boolean =
refreshableToken.expiry.isBefore(System.currentTimeMillis)

override def accessToken: String = this.synchronized {
cachedToken match {
case Some(token) if isTokenExpired(token) =>
refreshToken.accessToken
case None =>
refreshToken.accessToken
case Some(token) =>
token.accessToken
}
}

private def buildRefreshableToken(accessToken: String): RefreshableToken = {
RefreshableToken(accessToken, DateTime.now.plus(refreshInterval.toMillis))
}
}

26 changes: 26 additions & 0 deletions client/src/main/scala/skuber/api/client/token/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package skuber.api.client

import scala.io.Source
import scala.util.Try

package object token {
trait ContentReaderComponent {
val contentReader: ContentReader

trait ContentReader {
def read(filePath: String): Try[String]
}
}

trait FileReaderComponent extends ContentReaderComponent {
val contentReader: ContentReader = new FileContentReader

class FileContentReader extends ContentReader {
def read(filePath: String): Try[String] = for {
source <- Try(Source.fromFile(filePath, "utf-8"))
content <- Try(source.getLines().mkString("\n"))
_ <- Try(source.close())
} yield content
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package skuber.api.client.token

import org.joda.time.DateTime
import org.specs2.mutable.Specification

import scala.concurrent.duration.DurationInt
import scala.util.Try

class FileTokenAuthRefreshableSpec extends Specification {
"This is a specification for the 'FileTokenAuthRefreshable' class".txt

trait MockFileReaderComponent extends ContentReaderComponent {
val contentReader: ContentReader = new MockFileReaderComponent

class MockFileReaderComponent extends ContentReader {
def read(filePath: String): Try[String] = Try(DateTime.now.toString())
}
}

final case class MockFileTokenAuthRefreshable(config: FileTokenConfiguration) extends TokenAuthRefreshable with MockFileReaderComponent {}

"FileTokenAuthRefreshable" should {
"Retrieve the token if none provided" in {
val initialToken : Option[String] = None
val fileTokenRefreshable = MockFileTokenAuthRefreshable(FileTokenConfiguration(cachedAccessToken = initialToken, tokenPath = Some("/tmp/token"), refreshInterval = 100.milliseconds))
fileTokenRefreshable.accessToken.nonEmpty must beTrue
}

"Refresh the token after the refresh interval" in {
val initialToken = "cachedToken"
val fileTokenRefreshable = MockFileTokenAuthRefreshable(FileTokenConfiguration(Some(initialToken), Some("/tmp/token"), 100.milliseconds))
fileTokenRefreshable.accessToken shouldEqual initialToken

Thread.sleep(150)
val refreshed = fileTokenRefreshable.accessToken
refreshed shouldNotEqual initialToken

Thread.sleep(150)
fileTokenRefreshable.accessToken shouldNotEqual refreshed
}
}
}