-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Initial version of GKE Auth support without gcloud #4185
Open
talatuyarer
wants to merge
4
commits into
fabric8io:main
Choose a base branch
from
talatuyarer:gcp-gke-auth-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
...es-client-api/src/main/java/io/fabric8/kubernetes/client/utils/GCPAuthenticatorUtils.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
/** | ||
* Copyright (C) 2015 Red Hat, Inc. | ||
* | ||
* 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.fabric8.kubernetes.client.utils; | ||
|
||
import com.google.auth.oauth2.AccessToken; | ||
import com.google.auth.oauth2.GoogleCredentials; | ||
import com.google.common.annotations.VisibleForTesting; | ||
import io.fabric8.kubernetes.api.model.NamedContext; | ||
import io.fabric8.kubernetes.client.internal.KubeConfigUtils; | ||
import java.io.File; | ||
import java.io.IOException; | ||
import java.util.Map; | ||
import java.util.concurrent.CompletableFuture; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
/** | ||
* Utility class for GCP token refresh. | ||
*/ | ||
public class GCPAuthenticatorUtils { | ||
|
||
private static final Logger LOGGER = LoggerFactory.getLogger(GCPAuthenticatorUtils.class); | ||
|
||
public static final String EMPTY = ""; | ||
public static final String ACCESS_TOKEN_PARAM = "access_token"; | ||
public static final String EXPIRY_PARAM = "expiry"; | ||
public static final String SCOPES = "scopes"; | ||
public static final String[] DEFAULT_SCOPES = | ||
new String[]{ | ||
"https://www.googleapis.com/auth/cloud-platform", | ||
"https://www.googleapis.com/auth/userinfo.email" | ||
}; | ||
private static GoogleCredentials credentials; | ||
|
||
private GCPAuthenticatorUtils() { | ||
} | ||
|
||
/** | ||
* Google Application Credentials-based refresh | ||
* https://cloud.google.com/kubernetes-engine/docs/how-to/api-server-authentication#environments-without-gcloud | ||
* @param currentAuthProviderConfig current AuthInfo's AuthProvider config as a map | ||
* @return access token for interacting with Google Kubernetes API | ||
*/ | ||
public static CompletableFuture<String> resolveTokenFromAuthConfig( | ||
Map<String, String> currentAuthProviderConfig) { | ||
String[] scopes = parseScopes(currentAuthProviderConfig); | ||
try { | ||
if (credentials == null) { | ||
credentials = GoogleCredentials.getApplicationDefault().createScoped(scopes); | ||
LOGGER.debug("GoogleCredentials: ", credentials); | ||
} | ||
credentials.refresh(); | ||
AccessToken accessToken = credentials.getAccessToken(); | ||
currentAuthProviderConfig.put(ACCESS_TOKEN_PARAM, accessToken.getTokenValue()); | ||
currentAuthProviderConfig.put(EXPIRY_PARAM, | ||
accessToken.getExpirationTime().toInstant().toString()); | ||
persistKubeConfigWithUpdatedToken(currentAuthProviderConfig); | ||
CompletableFuture.completedFuture(accessToken.getTokenValue()); | ||
} catch (IOException e) { | ||
throw new RuntimeException("The Application Default Credentials are not available.", e); | ||
} | ||
return CompletableFuture.completedFuture(currentAuthProviderConfig.get(ACCESS_TOKEN_PARAM)); | ||
} | ||
|
||
public static String[] parseScopes(Map<String, String> config) { | ||
String scopes = config.get(SCOPES); | ||
if (scopes == null) { | ||
return DEFAULT_SCOPES; | ||
} | ||
if (scopes.isEmpty()) { | ||
return new String[]{}; | ||
} | ||
return scopes.split(","); | ||
} | ||
|
||
/** | ||
* Save Updated Access and Refresh token in local KubeConfig file. | ||
* | ||
* @param kubeConfigPath Path to KubeConfig (by default .kube/config) | ||
* @param updatedAuthProviderConfig updated AuthProvider configuration | ||
* @return boolean value whether update was successful not not | ||
* @throws IOException in case of any failure while writing file | ||
*/ | ||
static boolean persistKubeConfigWithUpdatedToken(String kubeConfigPath, | ||
Map<String, String> updatedAuthProviderConfig) | ||
throws IOException { | ||
io.fabric8.kubernetes.api.model.Config config = KubeConfigUtils.parseConfig( | ||
new File(kubeConfigPath)); | ||
NamedContext currentNamedContext = KubeConfigUtils.getCurrentContext(config); | ||
|
||
if (currentNamedContext != null) { | ||
// Update users > auth-provider > config | ||
int currentUserIndex = KubeConfigUtils.getNamedUserIndexFromConfig(config, | ||
currentNamedContext.getContext().getUser()); | ||
Map<String, String> authProviderConfig = config.getUsers().get(currentUserIndex).getUser() | ||
.getAuthProvider().getConfig(); | ||
authProviderConfig.put(ACCESS_TOKEN_PARAM, updatedAuthProviderConfig.get(ACCESS_TOKEN_PARAM)); | ||
authProviderConfig.put(EXPIRY_PARAM, updatedAuthProviderConfig.get(EXPIRY_PARAM)); | ||
config.getUsers().get(currentUserIndex).getUser().getAuthProvider() | ||
.setConfig(authProviderConfig); | ||
|
||
// Persist changes to KUBECONFIG | ||
try { | ||
KubeConfigUtils.persistKubeConfigIntoFile(config, kubeConfigPath); | ||
return true; | ||
} catch (IOException exception) { | ||
LOGGER.warn("failed to write file {}", kubeConfigPath, exception); | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
private static boolean persistKubeConfigWithUpdatedToken( | ||
Map<String, String> updatedAuthProviderConfig) throws IOException { | ||
return persistKubeConfigWithUpdatedToken( | ||
io.fabric8.kubernetes.client.Config.getKubeconfigFilename(), | ||
updatedAuthProviderConfig); | ||
} | ||
|
||
@VisibleForTesting | ||
static void setCredentials(GoogleCredentials cre){ | ||
credentials = cre; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
...lient-api/src/test/java/io/fabric8/kubernetes/client/utils/GCPAuthenticatorUtilsTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
/** | ||
* Copyright (C) 2015 Red Hat, Inc. | ||
* | ||
* 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.fabric8.kubernetes.client.utils; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
|
||
import com.google.auth.oauth2.AccessToken; | ||
import com.google.auth.oauth2.GoogleCredentials; | ||
import java.io.File; | ||
import java.nio.file.Files; | ||
import java.nio.file.Paths; | ||
import java.nio.file.StandardCopyOption; | ||
import java.time.Instant; | ||
import java.util.Date; | ||
import java.util.HashMap; | ||
import java.util.Map; | ||
import org.junit.jupiter.api.Test; | ||
import org.mockito.Mockito; | ||
|
||
public class GCPAuthenticatorUtilsTest { | ||
|
||
@Test | ||
void testRefreshToken() throws Exception { | ||
// Given | ||
String fakeToken = "new-fake-token"; | ||
String fakeTokenExpiry = "2121-08-05T02:30:24Z"; | ||
Map<String, String> currentAuthProviderConfig = new HashMap<>(); | ||
File tempFile = Files.createTempFile("test", "kubeconfig").toFile(); | ||
Files.copy(getClass().getResourceAsStream("/test-kubeconfig-gcp"), Paths.get(tempFile.getPath()), | ||
StandardCopyOption.REPLACE_EXISTING); | ||
System.setProperty("kubeconfig", tempFile.getAbsolutePath()); | ||
|
||
GoogleCredentials mockGC = Mockito.mock(GoogleCredentials.class); | ||
GCPAuthenticatorUtils.setCredentials(mockGC); | ||
Mockito.when(mockGC.getAccessToken()) | ||
.thenReturn(new AccessToken(fakeToken, Date.from(Instant.parse(fakeTokenExpiry)))); | ||
|
||
// When | ||
String token = GCPAuthenticatorUtils.resolveTokenFromAuthConfig(currentAuthProviderConfig).get(); | ||
|
||
// Then | ||
assertNotNull(token); | ||
assertEquals(fakeToken, token); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
kubernetes-client-api/src/test/resources/test-kubeconfig-gcp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
apiVersion: v1 | ||
clusters: | ||
- cluster: | ||
certificate-authority: testns/ca.pem | ||
server: https://172.28.128.4:8443 | ||
name: 172-28-128-4:8443 | ||
contexts: | ||
- context: | ||
cluster: 172-28-128-4:8443 | ||
namespace: testns | ||
user: user/172-28-128-4:8443 | ||
name: testns/172-28-128-4:8443/user | ||
- context: | ||
cluster: 172-28-128-4:8443 | ||
namespace: production | ||
user: root/172-28-128-4:8443 | ||
name: production/172-28-128-4:8443/root | ||
- context: | ||
cluster: 172-28-128-4:8443 | ||
namespace: production | ||
user: mmosley | ||
name: production/172-28-128-4:8443/mmosley | ||
current-context: production/172-28-128-4:8443/mmosley | ||
kind: Config | ||
preferences: {} | ||
users: | ||
- name: user/172-28-128-4:8443 | ||
user: | ||
token: token | ||
- name: root/172-28-128-4:8443 | ||
user: | ||
token: supertoken | ||
- name: mmosley | ||
user: | ||
auth-provider: | ||
name: gcp | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't understand the usage of a CompletableFuture here, both* return statements return sync values
CompletableFuture.completedFuture
Also, line 72 seems to be missing a
return
?