Skip to content

Commit

Permalink
Merge pull request #2806 from yue9944882/eks-authentication
Browse files Browse the repository at this point in the history
EKS authentication based on AWS Sigv4
  • Loading branch information
k8s-ci-robot authored Oct 5, 2023
2 parents 4e97f33 + a51debb commit 61c28c8
Show file tree
Hide file tree
Showing 15 changed files with 813 additions and 12 deletions.
4 changes: 4 additions & 0 deletions examples/examples-release-19/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sts</artifactId>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.examples;

import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.VersionInfo;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.credentials.EKSAuthentication;
import io.kubernetes.client.util.version.Version;

import java.io.IOException;

public class EKSAuthenticationExample {
public static void main(String[] args) throws IOException, ApiException {

// Connecting an EKS cluster using {@link io.kubernetes.client.util.credentials.EKSAuthentication }

// This role should have access to the EKS cluster.
String roleArn = "arn:aws:iam::123456789:role/TestRole";
// Arbitrary role session name.
String roleSessionName = "test";
// Region where the EKS cluster at.
String region = "us-west-2";
// EKS cluster name.
String clusterName = "test-2";

STSAssumeRoleSessionCredentialsProvider credProvider = new STSAssumeRoleSessionCredentialsProvider(
new DefaultAWSCredentialsProviderChain().getCredentials(),
roleArn,
roleSessionName);

ApiClient apiClient = ClientBuilder.standard()
.setAuthentication(new EKSAuthentication(credProvider, region, clusterName))
.build();

Version version = new Version(apiClient);
VersionInfo versionInfo = version.getVersion();
System.out.println(versionInfo);
}
}
19 changes: 12 additions & 7 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@
<version>1.6.7</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sts</artifactId>
<version>1.12.560</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
Expand Down Expand Up @@ -233,7 +239,12 @@
<version>1.20.0</version>
<optional>true</optional>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.15.2</version>
<optional>true</optional>
</dependency>

<!-- tests -->
<dependency>
Expand Down Expand Up @@ -307,12 +318,6 @@
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.15.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>

Expand Down
5 changes: 4 additions & 1 deletion util/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>adal4j</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-sts</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.util;
package io.kubernetes.client.persister;

import java.io.IOException;
import java.util.ArrayList;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.util;
package io.kubernetes.client.persister;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import io.kubernetes.client.persister.ConfigPersister;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1CertificateSigningRequest;
import io.kubernetes.client.persister.FilePersister;
import io.kubernetes.client.util.credentials.AccessTokenAuthentication;
import io.kubernetes.client.util.credentials.Authentication;
import io.kubernetes.client.util.credentials.ClientCertificateAuthentication;
Expand Down
5 changes: 3 additions & 2 deletions util/src/main/java/io/kubernetes/client/util/KubeConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import io.kubernetes.client.persister.ConfigPersister;
import io.kubernetes.client.util.authenticators.Authenticator;
import io.kubernetes.client.util.authenticators.AzureActiveDirectoryAuthenticator;
import io.kubernetes.client.util.authenticators.GCPAuthenticator;
Expand Down Expand Up @@ -235,7 +236,7 @@ public Map<String, String> getCredentials() {
}
}
Map<String, String> credentialsViaExecCredential =
credentialsViaExecCredential((Map<String, Object>) currentUser.get("exec"));
getCredentialsViaExecCredential((Map<String, Object>) currentUser.get("exec"));
if (credentialsViaExecCredential != null) {
return credentialsViaExecCredential;
}
Expand Down Expand Up @@ -265,7 +266,7 @@ public Map<String, String> getCredentials() {
* Authenticating » client-go credential plugins</a>
*/
@SuppressWarnings("unchecked")
private Map<String, String> credentialsViaExecCredential(Map<String, Object> execMap) {
private Map<String, String> getCredentialsViaExecCredential(Map<String, Object> execMap) {
if (execMap == null) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.util.credentials;

import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.auth.AWSSessionCredentialsProvider;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.eks.AWS4STSSigner;
import io.kubernetes.client.util.eks.AWS4SignerBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.HashMap;

/**
* EKS cluster authentication which generates a bearer token from AWS AK/SK. It doesn't require an "aws"
* command line tool in the $PATH.
*/
public class EKSAuthentication implements Authentication {

private static final Logger log = LoggerFactory.getLogger(EKSAuthentication.class);

/**
* Instantiates a new Eks authentication.
*
* @param provider the AWS credential provider
* @param region the region where EKS cluster at
* @param clusterName the EKS cluster name
*/
public EKSAuthentication(AWSSessionCredentialsProvider provider, String region, String clusterName) {
this(provider, region, clusterName, MAX_EXPIRY_SECONDS);
}

public EKSAuthentication(AWSSessionCredentialsProvider provider, String region, String clusterName, int expirySeconds) {
this.provider = provider;
this.region = region;
this.clusterName = clusterName;
if (expirySeconds > MAX_EXPIRY_SECONDS) {
expirySeconds = MAX_EXPIRY_SECONDS;
}
this.expirySeconds = expirySeconds;
}

private static final int MAX_EXPIRY_SECONDS = 60 * 15;
private final AWSSessionCredentialsProvider provider;
private final String region;
private final String clusterName;

private final int expirySeconds;

@Override
public void provide(ApiClient client) {
URI uri = URI.create("https://sts." + this.region + ".amazonaws.com/");
AWSSessionCredentials cred = provider.getCredentials();
try {
AWS4STSSigner signer = new AWS4STSSigner(
uri.toURL(),
"GET",
"sts",
this.region);
String token = "k8s-aws-v1." + Base64.getEncoder().withoutPadding().encodeToString(signer.computeSignature(
uri,
new HashMap<String, String>() {{
put("x-k8s-aws-id", clusterName);

}},
new HashMap<String, String>() {{
put("Action", "GetCallerIdentity");
put("Version", "2011-06-15");
}},
expirySeconds,
AWS4SignerBase.EMPTY_BODY_SHA256,
cred.getAWSAccessKeyId(),
cred.getAWSSecretKey(),
cred.getSessionToken()).getBytes());
client.setApiKeyPrefix("Bearer");
client.setApiKey(token);
log.info("Generated BEARER token for ApiClient, expiring at {}", Instant.now().plus(expirySeconds, ChronoUnit.SECONDS));
} catch (MalformedURLException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
Loading

0 comments on commit 61c28c8

Please sign in to comment.