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

support gcp authentication refresh token #1810

Merged
merged 6 commits into from
Aug 9, 2021
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -12,10 +12,17 @@
*/
package io.kubernetes.client.util.authenticators;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.kubernetes.client.util.KubeConfig;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -28,21 +35,36 @@ public class GCPAuthenticator implements Authenticator {
KubeConfig.registerAuthenticator(new GCPAuthenticator());
}

private static final String ACCESS_TOKEN = "access-token";
private static final String EXPIRY = "expiry";
private static final String CMD_ARGS = "cmd-args";
private static final String CMD_PATH = "cmd-path";

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

private final ProcessBuilder pb;

public GCPAuthenticator() {
this(new ProcessBuilder());
}

public GCPAuthenticator(ProcessBuilder pb) {
this.pb = pb;
}

@Override
public String getName() {
return "gcp";
}

@Override
public String getToken(Map<String, Object> config) {
return (String) config.get("access-token");
return (String) config.get(ACCESS_TOKEN);
}

@Override
public boolean isExpired(Map<String, Object> config) {
Object expiryObj = config.get("expiry");
Object expiryObj = config.get(EXPIRY);
Instant expiry = null;
if (expiryObj instanceof Date) {
expiry = ((Date) expiryObj).toInstant();
Expand All @@ -58,6 +80,38 @@ public boolean isExpired(Map<String, Object> config) {

@Override
public Map<String, Object> refresh(Map<String, Object> config) {
throw new IllegalStateException("Unimplemented");
if (!config.containsKey(CMD_ARGS) || !config.containsKey(CMD_PATH))
throw new RuntimeException("Could not refresh token");
String cmdPath = (String) config.get(CMD_PATH);
String cmdArgs = (String) config.get(CMD_ARGS);
String fullCmd = cmdPath + cmdArgs;
try {
Process process = this.pb.command(Arrays.asList(fullCmd.split(" "))).start();
process.waitFor(10, TimeUnit.SECONDS);
if (process.exitValue() != 0) {
String stdErr = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8);
throw new IllegalStateException(
"Failed to executing access token command "
+ fullCmd
+ ": exitValue: "
+ process.exitValue()
+ ", stdErr: "
+ stdErr);
}
String output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
String credentialJson = output.substring(output.indexOf("{"), output.lastIndexOf("}") + 1);
JsonObject root = JsonParser.parseString(credentialJson).getAsJsonObject();
if (root.has("credential")) {
JsonObject credJson = root.getAsJsonObject("credential");
if (credJson.has("access_token") && credJson.has("token_expiry")) {
config.put(ACCESS_TOKEN, credJson.get("access_token").getAsString());
config.put(EXPIRY, credJson.get("token_expiry").getAsString());
return config;
}
}
throw new IllegalStateException("Failed to parsing access token output: " + output);
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Could not refresh token", e);
}
}
}
31 changes: 26 additions & 5 deletions util/src/test/java/io/kubernetes/client/util/KubeConfigTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import io.kubernetes.client.util.authenticators.Authenticator;
import io.kubernetes.client.util.authenticators.AzureActiveDirectoryAuthenticator;
import io.kubernetes.client.util.authenticators.GCPAuthenticator;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
Expand All @@ -28,6 +29,7 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;

/** Tests for the KubeConfigConfig helper class */
public class KubeConfigTest {
Expand Down Expand Up @@ -169,14 +171,33 @@ public void testGCPAuthProviderExpiredToken() {
+ " expiry-key: '{.credential.token_expiry}'\n"
+ " token-key: '{.credential.access_token}'\n"
+ " name: gcp";
KubeConfig.registerAuthenticator(new GCPAuthenticator());
String fakeExecResult =
"{\n"
+ " \"credential\": {\n"
+ " \"access_token\": \"new-fake-token\",\n"
+ " \"id_token\": \"id-fake-token\",\n"
+ " \"token_expiry\": \"2121-08-05T02:30:24Z\"\n"
+ " }\n"
+ "}";
ProcessBuilder mockPB = Mockito.mock(ProcessBuilder.class, Mockito.RETURNS_DEEP_STUBS);
Process mockProcess = Mockito.mock(Process.class);
Mockito.when(mockProcess.exitValue()).thenReturn(0);
Mockito.when(mockProcess.getInputStream())
.thenReturn(new ByteArrayInputStream(fakeExecResult.getBytes(StandardCharsets.UTF_8)));
try {
Mockito.when(mockPB.command(Mockito.anyList()).start()).thenReturn(mockProcess);
} catch (IOException ex) {
ex.printStackTrace();
fail("Unexpected exception: " + ex);
}

KubeConfig.registerAuthenticator(new GCPAuthenticator(mockPB));
try {
KubeConfig kc = KubeConfig.loadKubeConfig(new StringReader(gcpConfigExpiredToken));
kc.getAccessToken();
assertEquals("new-fake-token", kc.getAccessToken());
} catch (Exception ex) {
if (!(ex instanceof IllegalStateException)) {
fail("Unexpected exception: " + ex);
}
ex.printStackTrace();
fail("Unexpected exception: " + ex);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mock-maker-inline