From 6e9f72af4ceb089ed5183db43f1ed287db30919b Mon Sep 17 00:00:00 2001 From: Andre Dietisheim Date: Wed, 21 Aug 2024 19:54:20 +0200 Subject: [PATCH] update token in file listed in KUBECONFIG env var (#6240) Signed-off-by: Andre Dietisheim --- CHANGELOG.md | 2 + .../io/fabric8/kubernetes/client/Config.java | 237 +++++++++++------- .../kubernetes/client/ConfigBuilder.java | 3 +- .../kubernetes/client/ConfigFluent.java | 2 +- .../kubernetes/client/KubeConfigFile.java | 32 +++ .../kubernetes/client/SundrioConfig.java | 5 +- .../client/internal/KubeConfigUtils.java | 58 +++-- .../client/utils/OpenIDConnectionUtils.java | 78 +++--- .../kubernetes/client/utils/Utils.java | 23 +- .../client/ConfigConstructorTest.java | 24 +- .../fabric8/kubernetes/client/ConfigTest.java | 206 ++++++++++++++- .../OpenIDConnectionUtilsBehaviorTest.java | 28 ++- .../utils/OpenIDConnectionUtilsTest.java | 9 +- .../test/resources/test-ec-kubeconfig-mangled | 19 ++ .../src/test/resources/test-kubeconfig-empty | 7 + ...ctxt.yml => test-kubeconfig-nocurrentctxt} | 0 .../resources/test-kubeconfig-onlycurrentctx | 7 + .../OpenShiftOAuthInterceptorTest.java | 20 +- 18 files changed, 569 insertions(+), 191 deletions(-) create mode 100644 kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/KubeConfigFile.java create mode 100644 kubernetes-client-api/src/test/resources/test-ec-kubeconfig-mangled create mode 100644 kubernetes-client-api/src/test/resources/test-kubeconfig-empty rename kubernetes-client-api/src/test/resources/{test-kubeconfig-nocurrentctxt.yml => test-kubeconfig-nocurrentctxt} (100%) create mode 100644 kubernetes-client-api/src/test/resources/test-kubeconfig-onlycurrentctx diff --git a/CHANGELOG.md b/CHANGELOG.md index ef814de72e8..8196b7a8114 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ * Fix #6281: use GitHub binary repo for Kube API Tests * Fix #6282: Allow annotated types with Pattern, Min, and Max with Lists and Maps and CRD generation * Fix #5480: Move `io.fabric8:zjsonpatch` to KubernetesClient project +* Fix #6354: Prevent deadlock in okhttp AsyncBody.cancel +* Fix #6240: Use kubeconfig files listed in the KUBECONFIG env var #### Dependency Upgrade * Fix #6052: Removed dependency on no longer maintained com.github.mifmif:generex diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/Config.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/Config.java index c8002bf81a7..0c9808a87df 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/Config.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/Config.java @@ -62,8 +62,6 @@ import java.util.function.UnaryOperator; import java.util.stream.Collectors; -import static io.fabric8.kubernetes.client.internal.KubeConfigUtils.addTo; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(allowGetters = true, allowSetters = true) public class Config { @@ -119,7 +117,12 @@ public class Config { public static final String KUBERNETES_NAMESPACE_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"; public static final String KUBERNETES_NAMESPACE_FILE = "kubenamespace"; public static final String KUBERNETES_NAMESPACE_SYSTEM_PROPERTY = "kubernetes.namespace"; + /** + * @deprecated use {@link #KUBERNETES_KUBECONFIG_FILES} instead. + */ + @Deprecated public static final String KUBERNETES_KUBECONFIG_FILE = "kubeconfig"; + public static final String KUBERNETES_KUBECONFIG_FILES = "kubeconfig"; public static final String KUBERNETES_SERVICE_HOST_PROPERTY = "KUBERNETES_SERVICE_HOST"; public static final String KUBERNETES_SERVICE_PORT_PROPERTY = "KUBERNETES_SERVICE_PORT"; public static final String KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token"; @@ -151,6 +154,8 @@ public class Config { public static final String HTTP_PROTOCOL_PREFIX = "http://"; public static final String HTTPS_PROTOCOL_PREFIX = "https://"; + public static final File DEFAULT_KUBECONFIG_FILE = Paths.get(System.getProperty("user.home"), ".kube", "config").toFile(); + private static final String ACCESS_TOKEN = "access-token"; private static final String ID_TOKEN = "id-token"; private static final int DEFAULT_WATCH_RECONNECT_INTERVAL = 1000; @@ -235,8 +240,6 @@ public class Config { private Boolean autoConfigure; - @Deprecated - private File file; private List files = new ArrayList<>(); @JsonIgnore @@ -268,7 +271,7 @@ private Config(boolean autoConfigure) { null, null, null, null, null, null, null, null, null, null, - null, autoConfigure, true); + null, autoConfigure, true, null); } /** @@ -376,7 +379,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword, trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups, impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval, - uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, false, true); + uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, false, true, null); } public Config(String masterUrl, String apiVersion, String namespace, Boolean trustCerts, Boolean disableHostnameVerification, @@ -400,7 +403,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword, trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups, impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval, - uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true); + uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true, null); } /* @@ -419,7 +422,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru String impersonateUsername, String[] impersonateGroups, Map> impersonateExtras, OAuthTokenProvider oauthTokenProvider, Map customHeaders, Integer requestRetryBackoffLimit, Integer requestRetryBackoffInterval, Integer uploadRequestTimeout, Boolean onlyHttpWatches, NamedContext currentContext, - List contexts, Boolean autoConfigure, Boolean shouldSetDefaultValues) { + List contexts, Boolean autoConfigure, Boolean shouldSetDefaultValues, List files) { if (Boolean.TRUE.equals(shouldSetDefaultValues)) { this.masterUrl = DEFAULT_MASTER_URL; this.apiVersion = "v1"; @@ -587,7 +590,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru if (Utils.isNotNullOrEmpty(autoOAuthToken)) { this.autoOAuthToken = autoOAuthToken; } - if (contexts != null && !contexts.isEmpty()) { + if (Utils.isNotNullOrEmpty(contexts)) { this.contexts = contexts; } if (Utils.isNotNull(currentContext)) { @@ -601,6 +604,10 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru this.oauthTokenProvider = oauthTokenProvider; this.customHeaders = customHeaders; this.onlyHttpWatches = onlyHttpWatches; + if (Utils.isNotNullOrEmpty(files)) { + this.files = files; + } + } public static void configFromSysPropsOrEnvVars(Config config) { @@ -723,7 +730,7 @@ public static void configFromSysPropsOrEnvVars(Config config) { } String tlsVersionsVar = Utils.getSystemPropertyOrEnvVar(KUBERNETES_TLS_VERSIONS); - if (tlsVersionsVar != null && !tlsVersionsVar.isEmpty()) { + if (Utils.isNotNullOrEmpty(tlsVersionsVar)) { String[] tlsVersionsSplit = tlsVersionsVar.split(","); TlsVersion[] tlsVersions = new TlsVersion[tlsVersionsSplit.length]; for (int i = 0; i < tlsVersionsSplit.length; i++) { @@ -820,7 +827,7 @@ public static Config fromKubeconfig(String context, String kubeconfigContents, S // we allow passing context along here, since downstream accepts it Config config = new Config(false); if (kubeconfigPath != null) { - config.file = new File(kubeconfigPath); + config.setFile(new File(kubeconfigPath)); } if (!loadFromKubeconfig(config, context, kubeconfigContents)) { throw new KubernetesClientException("Could not create Config from kubeconfig"); @@ -839,20 +846,19 @@ public static Config fromKubeconfig(String context, String kubeconfigContents, S */ public Config refresh() { final String currentContextName = this.getCurrentContext() != null ? this.getCurrentContext().getName() : null; - if (this.oauthToken != null && !this.oauthToken.isEmpty()) { + if (Utils.isNotNullOrEmpty(this.oauthToken)) { return this; } if (this.autoConfigure) { return Config.autoConfigure(currentContextName); } - if (this.file != null) { - String kubeconfigContents = getKubeconfigContents(this.file); - if (kubeconfigContents == null) { - return this; // getKubeconfigContents will have logged an exception + // if files is null there's nothing to refresh - the kubeconfigs were directly supplied + if (!Utils.isNullOrEmpty(files)) { + io.fabric8.kubernetes.api.model.Config mergedConfig = mergeKubeConfigs(files); + if (mergedConfig != null) { + loadFromKubeconfig(this, mergedConfig.getCurrentContext(), mergedConfig); } - return Config.fromKubeconfig(currentContextName, kubeconfigContents, this.file.getPath()); } - // nothing to refresh - the kubeconfig was directly supplied return this; } @@ -861,56 +867,39 @@ private static boolean tryKubeConfig(Config config, String context) { if (!Utils.getSystemPropertyOrEnvVar(KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, true)) { return false; } - List kubeConfigFilenames = Arrays.asList(getKubeconfigFilenames()); - if (kubeConfigFilenames.isEmpty()) { - return false; - } - List allKubeConfigFiles = kubeConfigFilenames.stream() - .map(File::new) - .collect(Collectors.toList()); - File mainKubeConfig = allKubeConfigFiles.get(0); - io.fabric8.kubernetes.api.model.Config kubeConfig = createKubeconfig(mainKubeConfig); - if (kubeConfig == null) { + String[] kubeConfigFilenames = getKubeconfigFilenames(); + if (Utils.isNullOrEmpty(kubeConfigFilenames)) { return false; } - config.file = mainKubeConfig; - config.files = allKubeConfigFiles; - - List additionalConfigs = config.files.subList(1, allKubeConfigFiles.size()); - addAdditionalConfigs(kubeConfig, additionalConfigs); - - return loadFromKubeconfig(config, context, mainKubeConfig); + List allFiles = Arrays.stream(kubeConfigFilenames) + .map(File::new) + .collect(Collectors.toList()); + config.files = allFiles; + io.fabric8.kubernetes.api.model.Config mergedConfig = mergeKubeConfigs(allFiles); + return loadFromKubeconfig(config, context, mergedConfig); } - private static void addAdditionalConfigs(io.fabric8.kubernetes.api.model.Config kubeConfig, List files) { - if (files == null - || files.isEmpty()) { - return; + private static io.fabric8.kubernetes.api.model.Config mergeKubeConfigs(List files) { + if (Utils.isNullOrEmpty(files)) { + return null; } - files.stream() - .map(Config::createKubeconfig) - .filter(Objects::nonNull) - .forEach(additionalConfig -> { - addTo(additionalConfig.getContexts(), kubeConfig::getContexts, kubeConfig::setContexts); - addTo(additionalConfig.getClusters(), kubeConfig::getClusters, kubeConfig::setClusters); - addTo(additionalConfig.getUsers(), kubeConfig::getUsers, kubeConfig::setUsers); - }); + return files.stream() + .map(Config::createKubeconfig) + .reduce(null, (merged, additionalConfig) -> { + if (additionalConfig != null) { + return KubeConfigUtils.merge(additionalConfig, merged); + } else { + return merged; + } + }); } private static io.fabric8.kubernetes.api.model.Config createKubeconfig(File file) { - if (file == null) { - return null; - } - if (!file.isFile()) { - LOGGER.debug("Did not find Kubernetes config at: [{}]. Ignoring.", file.getPath()); - return null; - } io.fabric8.kubernetes.api.model.Config kubeConfig = null; LOGGER.debug("Found for Kubernetes config at: [{}].", file.getPath()); try { String content = getKubeconfigContents(file); - if (content != null - && !content.isEmpty()) { + if (Utils.isNotNullOrEmpty(content)) { kubeConfig = KubeConfigUtils.parseConfigFromString(content); } } catch (KubernetesClientException e) { @@ -921,6 +910,10 @@ private static io.fabric8.kubernetes.api.model.Config createKubeconfig(File file } /** + * Returns the first filename of all the filenames that are used in this Config. + * + * @return the first config filename that is used in this config. + * * @deprecated use {@link #getKubeconfigFilenames()} instead */ @Deprecated @@ -932,24 +925,46 @@ public static String getKubeconfigFilename() { fileName = fileNames[0]; if (fileNames.length > 1) { LOGGER.info("Found multiple Kubernetes config files [{}], returning the first one. Use #getKubeconfigFilenames instead", - fileNames[0]); + fileNames[0]); } } return fileName; } + /** + * Returns all the filenames that are used in this Config. + * Several config files can be used by setting the {@link Config#KUBERNETES_KUBECONFIG_FILES} env variable. + * Returns the default file at {@link Config#DEFAULT_KUBECONFIG_FILE} otherwise + * + * @return all the config files that are used in this Config + */ public static String[] getKubeconfigFilenames() { String[] fileNames = null; - String fileName = Utils.getSystemPropertyOrEnvVar(KUBERNETES_KUBECONFIG_FILE); - - fileNames = fileName.split(File.pathSeparator); - if (fileNames.length == 0) { - fileNames = new String[] { new File(getHomeDir(), ".kube" + File.separator + "config").toString() }; + String fileName = Utils.getSystemPropertyOrEnvVar(KUBERNETES_KUBECONFIG_FILES); + if (Utils.isNotNullOrEmpty(fileName)) { + fileNames = fileName.split(File.pathSeparator); + } + if (Utils.isNullOrEmpty(fileNames)) { + fileNames = new String[] { DEFAULT_KUBECONFIG_FILE.toString() }; } return fileNames; } + private static boolean isReadableKubeconfFile(File file) { + if (file == null) { + return false; + } + if (!file.isFile()) { + LOGGER.debug("Did not find Kubernetes config at: [{}]. Ignoring.", file.getPath()); + return false; + } + return true; + } + private static String getKubeconfigContents(File kubeConfigFile) { + if (kubeConfigFile == null) { + return null; + } String kubeconfigContents = null; try (FileReader reader = new FileReader(kubeConfigFile)) { kubeconfigContents = IOHelpers.readFully(reader); @@ -960,21 +975,20 @@ private static String getKubeconfigContents(File kubeConfigFile) { return kubeconfigContents; } - private static boolean loadFromKubeconfig(Config config, String context, File kubeConfigFile) { - String contents = getKubeconfigContents(kubeConfigFile); - if (contents == null) { - return false; - } - return loadFromKubeconfig(config, context, contents); - } - // Note: kubeconfigPath is optional // It is only used to rewrite relative tls asset paths inside kubeconfig when a file is passed, and in the case that // the kubeconfig references some assets via relative paths. private static boolean loadFromKubeconfig(Config config, String context, String kubeconfigContents) { + if (Utils.isNotNullOrEmpty(kubeconfigContents)) { + return loadFromKubeconfig(config, context, KubeConfigUtils.parseConfigFromString(kubeconfigContents)); + } else { + return false; + } + } + + private static boolean loadFromKubeconfig(Config config, String context, io.fabric8.kubernetes.api.model.Config kubeConfig) { try { - if (kubeconfigContents != null && !kubeconfigContents.isEmpty()) { - io.fabric8.kubernetes.api.model.Config kubeConfig = KubeConfigUtils.parseConfigFromString(kubeconfigContents); + if (kubeConfig != null) { mergeKubeConfigContents(config, context, kubeConfig); return true; } @@ -1024,7 +1038,7 @@ private static void mergeKubeConfigAuthInfo(Config config, Cluster currentCluste String caCertFile = currentCluster.getCertificateAuthority(); String clientCertFile = currentAuthInfo.getClientCertificate(); String clientKeyFile = currentAuthInfo.getClientKey(); - File configFile = config.file; + File configFile = config.getFile(); if (configFile != null) { caCertFile = absolutify(configFile, currentCluster.getCertificateAuthority()); clientCertFile = absolutify(configFile, currentAuthInfo.getClientCertificate()); @@ -1129,7 +1143,7 @@ protected static List getAuthenticatorCommandFromExecConfig(ExecConfig e command = shellQuote(command); List args = exec.getArgs(); - if (args != null && !args.isEmpty()) { + if (Utils.isNotNullOrEmpty(args)) { command += " " + args .stream() .map(Config::shellQuote) @@ -1162,6 +1176,7 @@ protected static String getCommandWithFullyQualifiedPath(String command, String private static Context setCurrentContext(String context, Config config, io.fabric8.kubernetes.api.model.Config kubeConfig) { if (context != null) { + // override existing current-context kubeConfig.setCurrentContext(context); } Context currentContext = null; @@ -1214,22 +1229,9 @@ private static boolean tryNamespaceFromPath(Config config) { return false; } - private static String getHomeDir() { - return getHomeDir(Config::isDirectoryAndExists, Config::getSystemEnvVariable); - } - - private static boolean isDirectoryAndExists(String filePath) { - File f = new File(filePath); - return f.exists() && f.isDirectory(); - } - - private static String getSystemEnvVariable(String envVariableName) { - return System.getenv(envVariableName); - } - protected static String getHomeDir(Predicate directoryExists, UnaryOperator getEnvVar) { String home = getEnvVar.apply("HOME"); - if (home != null && !home.isEmpty() && directoryExists.test(home)) { + if (Utils.isNotNullOrEmpty(home) && directoryExists.test(home)) { return home; } String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT); @@ -1243,7 +1245,7 @@ protected static String getHomeDir(Predicate directoryExists, UnaryOpera } } String userProfile = getEnvVar.apply("USERPROFILE"); - if (userProfile != null && !userProfile.isEmpty() && directoryExists.test(userProfile)) { + if (Utils.isNotNullOrEmpty(userProfile) && directoryExists.test(userProfile)) { return userProfile; } } @@ -1756,11 +1758,58 @@ public void setCurrentContext(NamedContext context) { /** * * Returns the path to the file that this configuration was loaded from. Returns {@code null} if no file was used. + * + * @deprecated use {@link #getFiles} instead. * - * @return the path to the kubeConfig file + * @return the kubeConfig file */ public File getFile() { - return file; + if (Utils.isNotNullOrEmpty(files)) { + return files.get(0); + } else { + return null; + } + } + + /** + * Returns the kube config files that are used to configure this client. + * Returns the files that are listed in the KUBERNETES_KUBECONFIG_FILES env or system variables. + * Returns the default kube config file if it's not set'. + * + * @return + */ + public List getFiles() { + return files; + } + + public KubeConfigFile getFileWithAuthInfo(String name) { + if (Utils.isNullOrEmpty(name) + || Utils.isNullOrEmpty(getFiles())) { + return null; + } + return getFiles().stream() + .filter(Config::isReadableKubeconfFile) + .map(file -> { + try { + return new KubeConfigFile(file, KubeConfigUtils.parseConfig(file)); + } catch (IOException e) { + return null; + } + }) + .filter(Objects::nonNull) + .filter(entry -> hasAuthInfoNamed(name, entry.getConfig())) + .findFirst() + .orElse(null); + } + + private boolean hasAuthInfoNamed(String username, io.fabric8.kubernetes.api.model.Config kubeConfig) { + if (Utils.isNullOrEmpty(username) + || kubeConfig == null + || kubeConfig.getUsers() == null) { + return false; + } + return kubeConfig.getUsers().stream() + .anyMatch(namedAuthInfo -> username.equals(namedAuthInfo.getName())); } @JsonIgnore @@ -1787,7 +1836,11 @@ public void setAdditionalProperty(String name, Object value) { } public void setFile(File file) { - this.file = file; + setFiles(Collections.singletonList(file)); + } + + public void setFiles(List files) { + this.files = files; } public void setAutoConfigure(boolean autoConfigure) { diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigBuilder.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigBuilder.java index a829b7ac6ed..3c3c6ae30fb 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigBuilder.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigBuilder.java @@ -57,9 +57,8 @@ public Config build() { fluent.getOauthTokenProvider(), fluent.getCustomHeaders(), fluent.getRequestRetryBackoffLimit(), fluent.getRequestRetryBackoffInterval(), fluent.getUploadRequestTimeout(), fluent.getOnlyHttpWatches(), fluent.getCurrentContext(), fluent.getContexts(), - Optional.ofNullable(fluent.getAutoConfigure()).orElse(!disableAutoConfig()), true); + Optional.ofNullable(fluent.getAutoConfigure()).orElse(!disableAutoConfig()), true, fluent.getFiles()); buildable.setAuthProvider(fluent.getAuthProvider()); - buildable.setFile(fluent.getFile()); return buildable; } } diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigFluent.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigFluent.java index b2d81528893..91458b3a684 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigFluent.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/ConfigFluent.java @@ -78,7 +78,7 @@ public void copyInstance(Config instance) { this.withContexts(instance.getContexts()); this.withAutoConfigure(instance.getAutoConfigure()); this.withAuthProvider(instance.getAuthProvider()); - this.withFile(instance.getFile()); + this.withFiles(instance.getFiles()); } } diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/KubeConfigFile.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/KubeConfigFile.java new file mode 100644 index 00000000000..54d9d4dc782 --- /dev/null +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/KubeConfigFile.java @@ -0,0 +1,32 @@ +/* + * 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; + +import java.io.File; +import io.fabric8.kubernetes.api.model.Config; +import lombok.Getter; + +@Getter +public class KubeConfigFile { + private final File file; + private final Config config; + + /** for testing purposes **/ + public KubeConfigFile(File file, Config config) { + this.file = file; + this.config = config; + } + } \ No newline at end of file diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/SundrioConfig.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/SundrioConfig.java index d6c027f3b3a..c4e789b110b 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/SundrioConfig.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/SundrioConfig.java @@ -19,6 +19,7 @@ import io.fabric8.kubernetes.client.http.TlsVersion; import io.sundr.builder.annotations.Buildable; +import java.io.File; import java.util.List; import java.util.Map; @@ -50,7 +51,7 @@ public SundrioConfig(String masterUrl, String apiVersion, String namespace, Bool String impersonateUsername, String[] impersonateGroups, Map> impersonateExtras, OAuthTokenProvider oauthTokenProvider, Map customHeaders, Integer requestRetryBackoffLimit, Integer requestRetryBackoffInterval, Integer uploadRequestTimeout, Boolean onlyHttpWatches, NamedContext currentContext, - List contexts, Boolean autoConfigure) { + List contexts, Boolean autoConfigure, List files) { super(masterUrl, apiVersion, namespace, trustCerts, disableHostnameVerification, caCertFile, caCertData, clientCertFile, clientCertData, clientKeyFile, clientKeyData, clientKeyAlgo, clientKeyPassphrase, username, password, oauthToken, autoOAuthToken, watchReconnectInterval, watchReconnectLimit, connectionTimeout, requestTimeout, @@ -58,6 +59,6 @@ public SundrioConfig(String masterUrl, String apiVersion, String namespace, Bool httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword, trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups, impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval, - uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true); + uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true, files); } } diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/KubeConfigUtils.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/KubeConfigUtils.java index f5793316ca4..81f344df975 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/KubeConfigUtils.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/internal/KubeConfigUtils.java @@ -18,20 +18,21 @@ import io.fabric8.kubernetes.api.model.AuthInfo; import io.fabric8.kubernetes.api.model.Cluster; import io.fabric8.kubernetes.api.model.Config; +import io.fabric8.kubernetes.api.model.ConfigBuilder; import io.fabric8.kubernetes.api.model.Context; import io.fabric8.kubernetes.api.model.NamedAuthInfo; import io.fabric8.kubernetes.api.model.NamedCluster; import io.fabric8.kubernetes.api.model.NamedContext; +import io.fabric8.kubernetes.api.model.NamedExtension; +import io.fabric8.kubernetes.api.model.PreferencesBuilder; import io.fabric8.kubernetes.client.utils.Serialization; +import io.fabric8.kubernetes.client.utils.Utils; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; /** * Helper class for working with the YAML config file thats located in @@ -165,27 +166,40 @@ public static void persistKubeConfigIntoFile(Config kubeConfig, String kubeConfi } } - /** - * Adds the given source list to the destination list that's provided by the given supplier - * and then set to the destination by the given setter. - * Creates the list if it doesn't exist yet (supplier returns {@code null}. - * Does not copy if the given list is {@code null}. - * - * @param source the source list to add to the destination - * @param destinationSupplier supplies the list that the source shall be added to - * @param destinationSetter sets the list, once the source was added to it - */ - public static void addTo(List source, Supplier> destinationSupplier, Consumer> destinationSetter) { - if (source == null) { - return; + public static Config merge(Config thisConfig, Config thatConfig) { + if (thisConfig == null) { + return thatConfig; } - - List list = destinationSupplier.get(); - if (list == null) { - list = new ArrayList<>(); + ConfigBuilder builder = new ConfigBuilder(thatConfig); + if (thisConfig.getClusters() != null) { + builder.addAllToClusters(thisConfig.getClusters()); + } + if (thisConfig.getContexts() != null) { + builder.addAllToContexts(thisConfig.getContexts()); + } + if (thisConfig.getUsers() != null) { + builder.addAllToUsers(thisConfig.getUsers()); } - list.addAll(source); - destinationSetter.accept(list); + if (thisConfig.getExtensions() != null) { + builder.addAllToExtensions(thisConfig.getExtensions()); + } + if (!builder.hasCurrentContext() + && Utils.isNotNullOrEmpty(thisConfig.getCurrentContext())) { + builder.withCurrentContext(thisConfig.getCurrentContext()); + } + Config merged = builder.build(); + mergePreferences(thisConfig, merged); + return merged; } + public static void mergePreferences(io.fabric8.kubernetes.api.model.Config source, + io.fabric8.kubernetes.api.model.Config destination) { + if (source.getPreferences() != null) { + PreferencesBuilder builder = new PreferencesBuilder(destination.getPreferences()); + if (source.getPreferences() != null) { + builder.addToExtensions(source.getExtensions().toArray(new NamedExtension[] {})); + } + destination.setPreferences(builder.build()); + } + } } diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java index c2ae79374a8..13b02769d6f 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtils.java @@ -20,8 +20,9 @@ import io.fabric8.kubernetes.api.model.AuthInfo; import io.fabric8.kubernetes.api.model.AuthProviderConfig; import io.fabric8.kubernetes.api.model.NamedAuthInfo; +import io.fabric8.kubernetes.api.model.NamedAuthInfoBuilder; import io.fabric8.kubernetes.client.Config; -import io.fabric8.kubernetes.client.Config.KubeConfigFile; +import io.fabric8.kubernetes.client.KubeConfigFile; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.http.HttpRequest; @@ -84,22 +85,22 @@ private OpenIDConnectionUtils() { * @return access token for interacting with Kubernetes API */ public static CompletableFuture resolveOIDCTokenFromAuthConfig( - Config currentConfig, Map currentAuthProviderConfig, HttpClient.Builder clientBuilder) { + Config currentConfig, Map currentAuthProviderConfig, HttpClient.Builder clientBuilder) { String originalToken = currentAuthProviderConfig.get(ID_TOKEN_KUBECONFIG); String idpCert = currentAuthProviderConfig.getOrDefault(IDP_CERT_DATA, getClientCertDataFromConfig(currentConfig)); if (isTokenRefreshSupported(currentAuthProviderConfig)) { final HttpClient httpClient = initHttpClientWithPemCert(idpCert, clientBuilder); final CompletableFuture result = getOpenIdConfiguration(httpClient, currentAuthProviderConfig) - .thenCompose(openIdConfiguration -> refreshOpenIdToken(httpClient, currentAuthProviderConfig, openIdConfiguration)) - .thenApply(oAuthToken -> persistOAuthToken(currentConfig, oAuthToken, null)) - .thenApply(oAuthToken -> { - if (oAuthToken == null || Utils.isNullOrEmpty(oAuthToken.idToken)) { - LOGGER.warn("token response did not contain an id_token, either the scope \\\"openid\\\" wasn't " + - "requested upon login, or the provider doesn't support id_tokens as part of the refresh response."); - return originalToken; - } - return oAuthToken.idToken; - }); + .thenCompose(openIdConfiguration -> refreshOpenIdToken(httpClient, currentAuthProviderConfig, openIdConfiguration)) + .thenApply(oAuthToken -> persistOAuthToken(currentConfig, oAuthToken, null)) + .thenApply(oAuthToken -> { + if (oAuthToken == null || Utils.isNullOrEmpty(oAuthToken.idToken)) { + LOGGER.warn("token response did not contain an id_token, either the scope \\\"openid\\\" wasn't " + + "requested upon login, or the provider doesn't support id_tokens as part of the refresh response."); + return originalToken; + } + return oAuthToken.idToken; + }); result.whenComplete((s, t) -> httpClient.close()); return result; } @@ -128,9 +129,9 @@ static boolean isTokenRefreshSupported(Map currentAuthProviderCo * @return the OpenID Configuration as returned by the OpenID provider */ private static CompletableFuture getOpenIdConfiguration(HttpClient client, - Map authProviderConfig) { + Map authProviderConfig) { final HttpRequest request = client.newHttpRequestBuilder() - .uri(resolveWellKnownUrlForOpenIDIssuer(authProviderConfig)).build(); + .uri(resolveWellKnownUrlForOpenIDIssuer(authProviderConfig)).build(); return client.sendAsync(request, String.class).thenApply(response -> { try { if (response.isSuccessful() && response.body() != null) { @@ -151,13 +152,13 @@ private static CompletableFuture getOpenIdConfiguration(Htt * Issue Token Refresh HTTP Request to OIDC Provider */ private static CompletableFuture refreshOpenIdToken( - HttpClient httpClient, Map authProviderConfig, OpenIdConfiguration openIdConfiguration) { + HttpClient httpClient, Map authProviderConfig, OpenIdConfiguration openIdConfiguration) { if (openIdConfiguration == null || Utils.isNullOrEmpty(openIdConfiguration.tokenEndpoint)) { LOGGER.warn("oidc: discovery object doesn't contain a valid token endpoint: {}", openIdConfiguration); return CompletableFuture.completedFuture(null); } final HttpRequest request = initTokenRefreshHttpRequest(httpClient, authProviderConfig, - openIdConfiguration.tokenEndpoint); + openIdConfiguration.tokenEndpoint); return httpClient.sendAsync(request, String.class).thenApply(r -> { String body = r.body(); if (body != null) { @@ -199,10 +200,11 @@ public static OAuthToken persistOAuthToken(Config currentConfig, OAuthToken oAut } private static void persistOAuthTokenToFile(Config currentConfig, String token, Map authProviderConfig) { - if (currentConfig.getFile() != null && currentConfig.getCurrentContext() != null) { + if (currentConfig.getCurrentContext() != null + && currentConfig.getCurrentContext().getContext() != null) { try { final String userName = currentConfig.getCurrentContext().getContext().getUser(); - KubeConfigFile kubeConfigFile = currentConfig.getFile(userName); + KubeConfigFile kubeConfigFile = currentConfig.getFileWithAuthInfo(userName); if (kubeConfigFile == null) { LOGGER.warn("oidc: failure while persisting new tokens into KUBECONFIG: file for user {} not found", userName); return; @@ -217,7 +219,8 @@ private static void persistOAuthTokenToFile(Config currentConfig, String token, } } - private static void setAuthProviderAndToken(String token, Map authProviderConfig, NamedAuthInfo namedAuthInfo) { + private static void setAuthProviderAndToken(String token, Map authProviderConfig, + NamedAuthInfo namedAuthInfo) { if (namedAuthInfo.getUser() == null) { namedAuthInfo.setUser(new AuthInfo()); } @@ -230,21 +233,28 @@ private static void setAuthProviderAndToken(String token, Map au } } - private static NamedAuthInfo getOrCreateNamedAuthInfo(String userName, io.fabric8.kubernetes.api.model.Config kubeConfig) { + private static NamedAuthInfo getOrCreateNamedAuthInfo(String name, io.fabric8.kubernetes.api.model.Config kubeConfig) { return kubeConfig.getUsers().stream() - .filter(n -> n.getName().equals(userName)) - .findFirst() - .orElseGet(() -> { - NamedAuthInfo result = new NamedAuthInfo(userName, new AuthInfo()); - kubeConfig.getUsers().add(result); - return result; - }); + .filter(n -> n.getName().equals(name)) + .findFirst() + .orElseGet(() -> { + NamedAuthInfo authInfo = new NamedAuthInfoBuilder() + .withName(name) + .withNewUser() + .endUser() + .build(); + kubeConfig.getUsers().add(authInfo); + return authInfo; + }); } private static void persistOAuthTokenToFile(AuthProviderConfig config, Map authProviderConfig) { + if (config == null) { + return; + } Optional.of(config) - .map(AuthProviderConfig::getConfig) - .ifPresent(c -> c.putAll(authProviderConfig)); + .map(AuthProviderConfig::getConfig) + .ifPresent(c -> c.putAll(authProviderConfig)); } /** @@ -268,19 +278,19 @@ private static HttpClient initHttpClientWithPemCert(String idpCert, HttpClient.B clientBuilder.sslContext(keyManagers, trustManagers); return clientBuilder.build(); } catch (KeyStoreException | InvalidKeySpecException | NoSuchAlgorithmException | IOException | UnrecoverableKeyException - | CertificateException e) { + | CertificateException e) { throw KubernetesClientException.launderThrowable("Could not import idp certificate", e); } } private static HttpRequest initTokenRefreshHttpRequest( - HttpClient client, Map authProviderConfig, String tokenRefreshUrl) { + HttpClient client, Map authProviderConfig, String tokenRefreshUrl) { final String clientId = authProviderConfig.get(CLIENT_ID_KUBECONFIG); final String clientSecret = authProviderConfig.getOrDefault(CLIENT_SECRET_KUBECONFIG, ""); final HttpRequest.Builder httpRequestBuilder = client.newHttpRequestBuilder().uri(tokenRefreshUrl); final String credentials = java.util.Base64.getEncoder().encodeToString((clientId + ':' + clientSecret) - .getBytes(StandardCharsets.UTF_8)); + .getBytes(StandardCharsets.UTF_8)); httpRequestBuilder.header("Authorization", "Basic " + credentials); final Map requestBody = new LinkedHashMap<>(); @@ -305,8 +315,8 @@ public static boolean idTokenExpired(Config config) { Map jwtPayloadMap = Serialization.unmarshal(jwtPayloadDecoded, Map.class); int expiryTimestampInSeconds = (Integer) jwtPayloadMap.get(JWT_TOKEN_EXPIRY_TIMESTAMP_KEY); return Instant.ofEpochSecond(expiryTimestampInSeconds) - .minusSeconds(TOKEN_EXPIRY_DELTA) - .isBefore(Instant.now()); + .minusSeconds(TOKEN_EXPIRY_DELTA) + .isBefore(Instant.now()); } catch (Exception e) { return true; } diff --git a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java index 8c491c1158e..8db382b5c66 100644 --- a/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java +++ b/kubernetes-client-api/src/main/java/io/fabric8/kubernetes/client/utils/Utils.java @@ -36,6 +36,7 @@ import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; @@ -291,8 +292,20 @@ public static boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); } - public static boolean isNotNullOrEmpty(Map map) { - return !(map == null || map.isEmpty()); + public static boolean isNotNullOrEmpty(Map map) { + return !isNullOrEmpty(map); + } + + public static boolean isNullOrEmpty(Map map) { + return map == null || map.isEmpty(); + } + + public static boolean isNotNullOrEmpty(Collection collection) { + return !isNullOrEmpty(collection); + } + + public static boolean isNullOrEmpty(Collection collection) { + return collection == null || collection.isEmpty(); } public static boolean isNotNullOrEmpty(String str) { @@ -300,7 +313,11 @@ public static boolean isNotNullOrEmpty(String str) { } public static boolean isNotNullOrEmpty(String[] array) { - return !(array == null || array.length == 0); + return !isNullOrEmpty(array); + } + + public static boolean isNullOrEmpty(String[] array) { + return array == null || array.length == 0; } public static boolean isNotNull(T... refList) { diff --git a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigConstructorTest.java b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigConstructorTest.java index 9caaafed939..98fca170fd3 100644 --- a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigConstructorTest.java +++ b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigConstructorTest.java @@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test; import java.io.File; +import java.util.Collections; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; @@ -47,7 +48,7 @@ void emptyConfiguration() { null, null, null, null, null, null, null, null, null, null, - null, null, false); + null, null, false, null); // Then assertThat(config) @@ -190,7 +191,7 @@ void whenAutoConfigureEnabled_thenUseBothDefaultAndAutoConfiguredValues() { null, null, null, null, null, null, null, null, null, null, - null, true, true); + null, true, true, null); // Then assertThat(config) @@ -237,7 +238,8 @@ void whenAutoConfigureEnabled_thenUseBothDefaultAndAutoConfiguredValues() { .hasFieldOrPropertyWithValue("proxyPassword", "autoconfigured-proxyPassword") .hasFieldOrPropertyWithValue("noProxy", new String[] { "autoconfigured-no-proxy-url1.io", "autoconfigured-no-proxy-url2.io" }) - .hasFieldOrPropertyWithValue("autoOAuthToken", "autoconfigured-token"); + .hasFieldOrPropertyWithValue("autoOAuthToken", "autoconfigured-token") + .hasFieldOrPropertyWithValue("files", Collections.singletonList(Config.DEFAULT_KUBECONFIG_FILE)); } @Test @@ -256,7 +258,7 @@ void whenAutoConfigureDisabled_thenOnlyUseDefaultValues() { null, null, null, null, null, null, null, null, null, null, - null, false, true); + null, false, true, null); assertThat(config) .isNotNull() @@ -299,7 +301,8 @@ void whenAutoConfigureDisabled_thenOnlyUseDefaultValues() { .hasFieldOrPropertyWithValue("proxyUsername", null) .hasFieldOrPropertyWithValue("proxyPassword", null) .hasFieldOrPropertyWithValue("noProxy", null) - .hasFieldOrPropertyWithValue("autoOAuthToken", null); + .hasFieldOrPropertyWithValue("autoOAuthToken", null) + .hasFieldOrPropertyWithValue("files", Collections. emptyList()); } } @@ -364,7 +367,7 @@ void configLoadedViaSystemProperties() { null, null, null, null, null, null, null, null, null, null, - null, true, true); + null, true, true, null); // Then assertThat(config) @@ -411,7 +414,8 @@ void configLoadedViaSystemProperties() { .hasFieldOrPropertyWithValue("proxyPassword", "autoconfigured-proxyPassword") .hasFieldOrPropertyWithValue("noProxy", new String[] { "autoconfigured-no-proxy-url1.io", "autoconfigured-no-proxy-url2.io" }) - .hasFieldOrPropertyWithValue("autoOAuthToken", "autoconfigured-token"); + .hasFieldOrPropertyWithValue("autoOAuthToken", "autoconfigured-token") + .hasFieldOrPropertyWithValue("files", Collections.singletonList(Config.DEFAULT_KUBECONFIG_FILE)); } finally { System.clearProperty("kubernetes.master"); System.clearProperty("kubernetes.namespace"); @@ -472,7 +476,7 @@ void configLoadedViaKubeConfig() { null, null, null, null, null, null, null, null, null, null, - null, true, true); + null, true, true, null); // Then assertThat(config) @@ -513,7 +517,7 @@ void configLoadedViaServiceAccount() { null, null, null, null, null, null, null, null, null, null, - null, true, true); + null, true, true, null); // Then assertThat(config) @@ -563,7 +567,7 @@ void throwsException() { null, null, null, null, null, null, null, null, null, null, - null, true, false)); + null, true, false, null)); } finally { System.clearProperty("kubeconfig"); } diff --git a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java index ad069d389de..d5057e4ee2a 100644 --- a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java +++ b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/ConfigTest.java @@ -17,8 +17,11 @@ import io.fabric8.kubernetes.api.model.ExecConfig; import io.fabric8.kubernetes.api.model.ExecConfigBuilder; +import io.fabric8.kubernetes.api.model.NamedAuthInfo; +import io.fabric8.kubernetes.api.model.NamedCluster; import io.fabric8.kubernetes.api.model.NamedContext; import io.fabric8.kubernetes.client.http.TlsVersion; +import io.fabric8.kubernetes.client.internal.KubeConfigUtils; import io.fabric8.kubernetes.client.lib.FileSystem; import io.fabric8.kubernetes.client.utils.Utils; import org.assertj.core.api.InstanceOfAssertFactories; @@ -79,7 +82,7 @@ class ConfigTest { .filePath(ConfigTest.class.getResource("/test-kubeconfig-exec-args-with-spaces")); private static final String TEST_KUBECONFIG_NO_CURRENT_CONTEXT_FILE = Utils - .filePath(ConfigTest.class.getResource("/test-kubeconfig-nocurrentctxt.yml")); + .filePath(ConfigTest.class.getResource("/test-kubeconfig-nocurrentctxt")); private static final String TEST_KUBECONFIG_EXEC_FILE_CERT_AUTH = Utils .filePath(ConfigTest.class.getResource("/test-kubeconfig-exec-cert-auth")); @@ -426,7 +429,7 @@ void autoConfigure_whenKubernetesServiceEnvironmentVariablesPresent_thenComputeM // Then assertThat(config) .hasFieldOrPropertyWithValue("masterUrl", "https://10.0.0.1:443/") - .hasFieldOrPropertyWithValue("file", null); + .hasFieldOrPropertyWithValue("files", Collections.singletonList(new File("/dev/null"))); } finally { System.clearProperty("KUBERNETES_SERVICE_HOST"); System.clearProperty("KUBERNETES_SERVICE_PORT"); @@ -438,14 +441,14 @@ void autoConfigure_whenKubernetesServiceEnvironmentVariablesPresent_thenComputeM void refresh_whenInvoked_shouldCreateNewInstance() { Config config = Config.autoConfigure(null); assertThat(config) - .hasFieldOrPropertyWithValue("file", null) + .hasFieldOrPropertyWithValue("files", Collections.singletonList(new File("/dev/null"))) .hasFieldOrPropertyWithValue("autoConfigure", true); // ensure that refresh creates a new instance Config refresh = config.refresh(); assertThat(refresh) .isNotSameAs(config) - .hasFieldOrPropertyWithValue("file", null) + .hasFieldOrPropertyWithValue("files", Collections.singletonList(new File("/dev/null"))) .hasFieldOrPropertyWithValue("autoConfigure", true); } @@ -461,7 +464,7 @@ void autoConfigure_whenKubernetesServiceEnvironmentVariablesPresentWithIPv6_then // Then assertThat(config) .hasFieldOrPropertyWithValue("masterUrl", "https://[2001:db8:1f70::999:de8:7648:6e8]:443/") - .hasFieldOrPropertyWithValue("file", null); + .hasFieldOrPropertyWithValue("files", Collections.singletonList(new File("/dev/null"))); } finally { System.clearProperty("KUBERNETES_SERVICE_HOST"); System.clearProperty("KUBERNETES_SERVICE_PORT"); @@ -538,7 +541,7 @@ void noArgConstructor_shouldAutoConfigureFromKubeConfig() { .hasFieldOrPropertyWithValue("autoOAuthToken", "token") .satisfies(c -> assertThat(c.getCaCertFile()).endsWith("testns/ca.pem".replace("/", File.separator))) .satisfies(c -> assertThat(new File(c.getCaCertFile())).isAbsolute()) - .hasFieldOrPropertyWithValue("file", new File(TEST_KUBECONFIG_FILE)); + .hasFieldOrPropertyWithValue("files", Collections.singletonList(new File(TEST_KUBECONFIG_FILE))); } @Test @@ -572,7 +575,7 @@ void fromKubeConfigContent() throws IOException { assertThat(config) .hasFieldOrPropertyWithValue("masterUrl", "https://172.28.128.4:8443/") .hasFieldOrPropertyWithValue("autoConfigure", false) - .hasFieldOrPropertyWithValue("file", null) + .hasFieldOrPropertyWithValue("files", Collections.emptyList()) .isSameAs(config.refresh()); } @@ -1215,11 +1218,11 @@ void refresh_whenOAuthTokenSourceSetToUser_thenConfigUnchanged() { } @Test - void givenEmptyKubeConfig_whenConfigCreated_thenShouldNotProduceNPE() throws URISyntaxException { + void build_given_emptyKubeConfig_then_shouldNotProduceNPE() throws URISyntaxException { try { // Given System.setProperty("kubeconfig", - new File(Objects.requireNonNull(getClass().getResource("/test-empty-kubeconfig")).toURI()).getAbsolutePath()); + getResourceAbsolutePath("/test-empty-kubeconfig")); // When Config config = new ConfigBuilder().build(); @@ -1230,4 +1233,189 @@ void givenEmptyKubeConfig_whenConfigCreated_thenShouldNotProduceNPE() throws URI System.clearProperty("kubeconfig"); } } + + @Test + void builder_given_severalKubeConfigsAndCurrentContextInFirstFile_then_shouldUseCurrentContextInFirstFile() + throws URISyntaxException { + try { + // Given + System.setProperty("kubeconfig", + getResourceAbsolutePath("/test-kubeconfig-onlycurrentctx") + File.pathSeparator + + getResourceAbsolutePath("/test-kubeconfig")); + + // When + Config config = new ConfigBuilder().build(); + + // Then + assertThat(config.getCurrentContext()).isNotNull(); + // current-context set by 1st file, current context in 2nd file is ignored + assertThat(config.getCurrentContext().getName()).isEqualTo("production/172-28-128-4:8443/root"); + } finally { + System.clearProperty("kubeconfig"); + } + } + + @Test + void builder_given_severalKubeConfigsAndCurrentContextInSecondFile_then_shouldUseCurrentContextInSecondFile() + throws URISyntaxException { + try { + // Given + System.setProperty("kubeconfig", + getResourceAbsolutePath("/test-kubeconfig-empty") + File.pathSeparator + + getResourceAbsolutePath("/test-kubeconfig")); + + // When + Config config = new ConfigBuilder().build(); + + // Then + assertThat(config.getCurrentContext()).isNotNull(); + // current-context set by 1st file, current context in 2nd file is ignored + assertThat(config.getCurrentContext().getName()).isEqualTo("testns/172-28-128-4:8443/user"); + } finally { + System.clearProperty("kubeconfig"); + } + } + + @Test + void builder_given_severalKubeConfigsWithSameCluster_then_shouldUseFirstCluster() + throws URISyntaxException, IOException { + try { + // Given + String clusterName = "172-28-128-4:8443"; + + String withSecureCluster = getResourceAbsolutePath("/test-ec-kubeconfig-mangled"); + NamedCluster secureCluster = getCluster(withSecureCluster, clusterName); + assertThat(secureCluster).isNotNull(); + assertThat(secureCluster.getCluster().getServer()).isEqualTo("https://bogus.com"); + + String withInsecureCluster = getResourceAbsolutePath("/test-ec-kubeconfig"); + NamedCluster insecureCluster = getCluster(withInsecureCluster, clusterName); + assertThat(insecureCluster).isNotNull(); + assertThat(insecureCluster.getCluster().getServer()).isEqualTo("https://172.28.128.4:8443"); + + System.setProperty("kubeconfig", + withSecureCluster + File.pathSeparator + + withInsecureCluster); + + // When + Config config = new ConfigBuilder().build(); + + // Then + // cluster in 1st file is not overriden by identically named cluster in 2nd file + assertThat(config.getMasterUrl()).startsWith("https://bogus.com"); + } finally { + System.clearProperty("kubeconfig"); + } + } + + private static NamedCluster getCluster(String filePath, String clusterName) throws IOException { + io.fabric8.kubernetes.api.model.Config config = KubeConfigUtils.parseConfig(new File(filePath)); + return config.getClusters().stream() + .filter(cluster -> clusterName.equals(cluster.getName())) + .findFirst() + .orElse(null); + } + + @Test + void builder_given_severalKubeConfigsWithSameUser_then_shouldUseFirstUser() + throws URISyntaxException, IOException { + try { + // Given + String userName = "user/172-28-128-4:8443"; + + String withUserWithToken = getResourceAbsolutePath("/test-ec-kubeconfig-mangled"); + NamedAuthInfo userWithToken = getUser(withUserWithToken, userName); + assertThat(userWithToken).isNotNull(); + assertThat(userWithToken.getUser().getToken()).isEqualTo("token"); + + String withUserWithoutToken = getResourceAbsolutePath("/test-ec-kubeconfig"); + NamedAuthInfo userWithoutToken = getUser(withUserWithoutToken, userName); + assertThat(userWithoutToken).isNotNull(); + assertThat(userWithoutToken.getUser().getToken()).isNull(); + + System.setProperty("kubeconfig", + withUserWithToken + File.pathSeparator + + withUserWithoutToken); + + // When + Config config = new ConfigBuilder().build(); + + // Then + // user in 1st file is not overriden by identically named user in 2nd file + assertThat(config.getAutoOAuthToken()).isEqualTo("token"); + } finally { + System.clearProperty("kubeconfig"); + } + } + + private static NamedAuthInfo getUser(String filePath, String userName) throws IOException { + io.fabric8.kubernetes.api.model.Config config = KubeConfigUtils.parseConfig(new File(filePath)); + return config.getUsers().stream() + .filter(user -> userName.equals(user.getName())) + .findFirst() + .orElse(null); + } + + @Test + void getKubeconfigFilenames_given_severalFilenamesDefinedInKUBECONFIG_then_returnsAllFilenames() throws URISyntaxException { + try { + // Given + String file1 = getResourceAbsolutePath("/test-kubeconfig-empty"); + // has all contexts, clusters, users + String file2 = getResourceAbsolutePath("/test-kubeconfig"); + System.setProperty("kubeconfig", file1 + File.pathSeparator + file2); + + // When + String[] filenames = Config.getKubeconfigFilenames(); + + // Then + assertThat(filenames) + .isNotNull() + .hasSize(2) + .containsExactly(file1, file2); + } finally { + System.clearProperty("kubeconfig"); + } + } + + private String getResourceAbsolutePath(String filename) throws URISyntaxException { + return new File(Objects.requireNonNull(getClass().getResource(filename)).toURI()).getAbsolutePath(); + } + + @Test + void getKubeconfigFilenames_given_KUBECONFNotSet_then_returnsDefault() { + // Given + System.clearProperty("kubeconfig"); + + // When + String[] filenames = Config.getKubeconfigFilenames(); + + // Then + assertThat(filenames) + .isNotNull() + .containsExactly(Config.DEFAULT_KUBECONFIG_FILE.getAbsolutePath()); + } + + @Test + void getFilenames_given_KUBECONFNotSet_then_returnsDefault() throws URISyntaxException { + try { + // Given + String fileWithToken = getResourceAbsolutePath("/test-kubeconfig-oidc"); + System.setProperty("kubeconfig", + fileWithToken + File.pathSeparator + + Config.DEFAULT_KUBECONFIG_FILE.getAbsolutePath()); + Config config = new ConfigBuilder().build(); + + // When + KubeConfigFile found = config.getFileWithAuthInfo("mmosley"); + + // Then + assertThat(found) + .isNotNull() + .returns(fileWithToken, kubeConfigFile -> kubeConfigFile.getFile().getAbsolutePath()); + } finally { + System.clearProperty("kubeconfig"); + } + } + } diff --git a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsBehaviorTest.java b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsBehaviorTest.java index 1870b8dd910..5ab97fe52d1 100644 --- a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsBehaviorTest.java +++ b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsBehaviorTest.java @@ -19,6 +19,7 @@ import io.fabric8.kubernetes.api.model.NamedAuthInfo; import io.fabric8.kubernetes.api.model.NamedAuthInfoBuilder; import io.fabric8.kubernetes.api.model.NamedClusterBuilder; +import io.fabric8.kubernetes.api.model.NamedContext; import io.fabric8.kubernetes.api.model.NamedContextBuilder; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; @@ -112,7 +113,7 @@ void setUp() throws Exception { .build(); Files.write(kubeConfigFile, Serialization.asYaml(kubeConfig).getBytes(StandardCharsets.UTF_8)); originalConfig = new ConfigBuilder(Config.empty()) - .withFile(tempDir.resolve("kube-config").toFile()) + .withFiles(tempDir.resolve("kube-config").toFile()) .build() .refresh(); // Auth provider configuration (minimal) @@ -493,11 +494,12 @@ void skipsInFileWhenOriginalConfigHasNoCurrentContext() { void logsWarningIfReferencedFileIsMissing() { originalConfig.setFile(kubeConfig); originalConfig = new ConfigBuilder(originalConfig) - .withCurrentContext(new NamedContextBuilder().withName("context").build()).build(); + .withCurrentContext(createNamedContext("context", "default-user")) + .build(); persistOAuthToken(originalConfig, oAuthTokenResponse, "fake.token"); assertThat(systemErr.toString()) .contains("oidc: failure while persisting new tokens into KUBECONFIG") - .contains("FileNotFoundException"); + .contains("file for user default-user not found"); } @Nested @@ -505,18 +507,19 @@ void logsWarningIfReferencedFileIsMissing() { class WithValidKubeConfig { @BeforeEach void setUp() throws IOException { - Files.write(kubeConfig.toPath(), ("---" + + Files.write(kubeConfig.toPath(), ("---\n" + "users:\n" + - "- name: user\n").getBytes(StandardCharsets.UTF_8)); + "- name: user\n" + + "contexts:\n" + + "- context:\n" + + " name: context\n").getBytes(StandardCharsets.UTF_8)); } @Test void persistsTokenInFile() throws IOException { originalConfig.setFile(kubeConfig); originalConfig = new ConfigBuilder(originalConfig) - .withCurrentContext(new NamedContextBuilder() - .withName("context") - .withNewContext().withUser("user").endContext().build()) + .withCurrentContext(createNamedContext("context", "user")) .build(); persistOAuthToken(originalConfig, oAuthTokenResponse, "fake.token"); assertThat(KubeConfigUtils.parseConfig(kubeConfig)) @@ -555,4 +558,13 @@ void persistsOAuthTokenInFile() throws IOException { } } + + private static NamedContext createNamedContext(String name, String user) { + return new NamedContextBuilder() + .withName(name) + .withNewContext() + .withUser(user) + .endContext() + .build(); + } } diff --git a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java index e5a7886a061..ce61dedfe40 100644 --- a/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java +++ b/kubernetes-client-api/src/test/java/io/fabric8/kubernetes/client/utils/OpenIDConnectionUtilsTest.java @@ -40,6 +40,7 @@ import java.util.Base64; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import static io.fabric8.kubernetes.client.http.TestStandardHttpClientFactory.Mode.SINGLETON; import static io.fabric8.kubernetes.client.utils.OpenIDConnectionUtils.CLIENT_ID_KUBECONFIG; @@ -77,9 +78,13 @@ void persistOAuthTokenWithUpdatedToken(@TempDir Path tempDir) throws IOException oAuthTokenResponse.setIdToken("id-token-updated"); oAuthTokenResponse.setRefreshToken("refresh-token-updated"); Path kubeConfig = Files.createTempFile(tempDir, "test", "kubeconfig"); - Files.copy(OpenIDConnectionUtilsTest.class.getResourceAsStream("/test-kubeconfig-oidc"), kubeConfig, + Files.copy( + Objects.requireNonNull(OpenIDConnectionUtilsTest.class.getResourceAsStream("/test-kubeconfig-oidc")), + kubeConfig, StandardCopyOption.REPLACE_EXISTING); - Config originalConfig = Config.fromKubeconfig(null, new String(Files.readAllBytes(kubeConfig), StandardCharsets.UTF_8), + Config originalConfig = Config.fromKubeconfig( + null, + new String(Files.readAllBytes(kubeConfig), StandardCharsets.UTF_8), kubeConfig.toFile().getAbsolutePath()); // When diff --git a/kubernetes-client-api/src/test/resources/test-ec-kubeconfig-mangled b/kubernetes-client-api/src/test/resources/test-ec-kubeconfig-mangled new file mode 100644 index 00000000000..d0b63ee8bd2 --- /dev/null +++ b/kubernetes-client-api/src/test/resources/test-ec-kubeconfig-mangled @@ -0,0 +1,19 @@ +apiVersion: v1 +clusters: +- cluster: + certificate-authority: testns/ca.pem + server: https://bogus.com + name: 172-28-128-4:8443 +contexts: +- context: + cluster: 172-28-128-4:8443 + namespace: default + user: user/172-28-128-4:8443 + name: default/172-28-128-4:8443/user +current-context: default/172-28-128-4:8443/user +kind: Config +preferences: {} +users: +- name: user/172-28-128-4:8443 + user: + token: token diff --git a/kubernetes-client-api/src/test/resources/test-kubeconfig-empty b/kubernetes-client-api/src/test/resources/test-kubeconfig-empty new file mode 100644 index 00000000000..81265e28f6e --- /dev/null +++ b/kubernetes-client-api/src/test/resources/test-kubeconfig-empty @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Config +clusters: null +contexts: null +current-context: null +preferences: {} +users: null \ No newline at end of file diff --git a/kubernetes-client-api/src/test/resources/test-kubeconfig-nocurrentctxt.yml b/kubernetes-client-api/src/test/resources/test-kubeconfig-nocurrentctxt similarity index 100% rename from kubernetes-client-api/src/test/resources/test-kubeconfig-nocurrentctxt.yml rename to kubernetes-client-api/src/test/resources/test-kubeconfig-nocurrentctxt diff --git a/kubernetes-client-api/src/test/resources/test-kubeconfig-onlycurrentctx b/kubernetes-client-api/src/test/resources/test-kubeconfig-onlycurrentctx new file mode 100644 index 00000000000..dc9a9504c8b --- /dev/null +++ b/kubernetes-client-api/src/test/resources/test-kubeconfig-onlycurrentctx @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Config +clusters: null +contexts: null +current-context: production/172-28-128-4:8443/root +preferences: {} +users: null \ No newline at end of file diff --git a/openshift-client/src/test/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptorTest.java b/openshift-client/src/test/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptorTest.java index d2fb1279c51..61ef0f53b21 100644 --- a/openshift-client/src/test/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptorTest.java +++ b/openshift-client/src/test/java/io/fabric8/openshift/client/internal/OpenShiftOAuthInterceptorTest.java @@ -16,9 +16,11 @@ package io.fabric8.openshift.client.internal; import io.fabric8.kubernetes.api.model.ContextBuilder; +import io.fabric8.kubernetes.api.model.NamedAuthInfo; import io.fabric8.kubernetes.api.model.NamedAuthInfoBuilder; import io.fabric8.kubernetes.api.model.NamedContextBuilder; import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.KubeConfigFile; import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.http.HttpResponse; @@ -34,6 +36,7 @@ import java.net.HttpURLConnection; import java.net.URI; import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; @@ -175,10 +178,15 @@ void afterFailure_withUsernamePassword_thenShouldAuthorize() { .withUser("testuser") .build()) .build()); - when(config.getFile()).thenReturn(new File("kube/config")); - when(kubeConfigContent.getUsers()).thenReturn(Collections.singletonList(new NamedAuthInfoBuilder() - .withName("testuser") - .build())); + List users = Collections.singletonList( + new NamedAuthInfoBuilder() + .withName("testuser") + .build()); + when(kubeConfigContent.getUsers()).thenReturn(users); + File file = new File("kube/config"); + when(config.getFiles()).thenReturn(Collections.singletonList(file)); + when(config.getFileWithAuthInfo(any())).thenReturn(new KubeConfigFile(file, kubeConfigContent)); + kubeConfigUtilsMockedStatic.when(() -> KubeConfigUtils.parseConfig(any())).thenReturn(kubeConfigContent); when(client.newBuilder()).thenReturn(derivedClientBuilder); when(client.newHttpRequestBuilder()).thenReturn(builder); when(builder.url(any())).thenReturn(builder); @@ -193,7 +201,6 @@ void afterFailure_withUsernamePassword_thenShouldAuthorize() { when(client.sendAsync(any(), any())) .thenReturn(authEndpointResponseCompletableFuture) .thenReturn(authResponseCompletableFuture); - kubeConfigUtilsMockedStatic.when(() -> KubeConfigUtils.parseConfig(any())).thenReturn(kubeConfigContent); OpenShiftOAuthInterceptor interceptor = new OpenShiftOAuthInterceptor(client, config); // When @@ -204,7 +211,8 @@ void afterFailure_withUsernamePassword_thenShouldAuthorize() { // Then assertThat(result).isCompletedWithValue(true); - kubeConfigUtilsMockedStatic.verify(() -> KubeConfigUtils.persistKubeConfigIntoFile(any(), anyString())); + kubeConfigUtilsMockedStatic.verify( + () -> KubeConfigUtils.persistKubeConfigIntoFile(any(io.fabric8.kubernetes.api.model.Config.class), anyString())); } }