From 6fef2a04bf9b061d3b033e29d1cb5beb8b5c3b77 Mon Sep 17 00:00:00 2001 From: Brad House Date: Sun, 22 Nov 2026 17:52:08 +0000 Subject: [PATCH] Join CKS nodes with a fresh token and a pinned CA Problem: - The bootstrap token was derived from the cluster UUID (visible in the API) and never expired. - Nodes joined with --discovery-token-unsafe-skip-ca-verification. - The HA certificate key was also derived from the UUID. Change: - Create: CloudStack generates the cluster CA, a random token and a random certificate key. The token expires after the start timeout. - Create: the CA is copied to the first control node over SSH, not put in userdata; kubeadm init waits for it. Every other node pins its hash. - Create: once all nodes are ready, the token and the kubeadm-certs secret are deleted. - Scale and add-node: `kubeadm token create --print-join-command` on the control node gives a new token and the CA hash, so clusters created before this change keep scaling. The token is deleted afterwards, and also when an add-node fails before any node was given it. - Joins use --discovery-token-ca-cert-hash. - The API server certificate always lists the control node's own IP as well as the public IP, since nodes join on the former and now verify the certificate. The external etcd kubeadm config advertises the control node's own IP (as kubeadm does in the stacked case); the public IP stays the controlPlaneEndpoint. - Add-node joins on the control node's own IP, as before, unless the API server certificate served there is not valid for it (external etcd clusters created before this change). Then it joins on the address kubeadm prints with the join command, which the certificate covers. If the certificate can't be checked, the control node's IP is used. Not done here: deleting the old UUID token on existing clusters. Signed-off-by: Brad House --- .../KubernetesClusterActionWorker.java | 88 +++++++++++- .../KubernetesClusterAddWorker.java | 15 +- .../KubernetesClusterScaleWorker.java | 6 + .../KubernetesClusterStartWorker.java | 136 ++++++++++++++++-- .../cluster/utils/KubernetesClusterUtil.java | 88 ++++++++++-- .../resources/conf/k8s-control-node-add.yml | 2 +- .../main/resources/conf/k8s-control-node.yml | 13 +- .../src/main/resources/conf/k8s-node.yml | 2 +- .../KubernetesClusterActionWorkerTest.java | 81 +++++++++++ .../KubernetesClusterStartWorkerTest.java | 68 +++++++++ .../utils/KubernetesClusterUtilTest.java | 73 ++++++++++ 11 files changed, 535 insertions(+), 37 deletions(-) create mode 100644 plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorkerTest.java diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java index 7a06b11e3bf4..3a25cc4fb723 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorker.java @@ -234,6 +234,9 @@ public class KubernetesClusterActionWorker { * For all other clusters: same value as {@link #publicIpAddress}. */ protected String apiPublicIpAddress; protected int sshPort; + protected String joinToken; + protected String joinCaCertHash; + protected String joinEndpointIp; /** * Returns the public IP that Kubernetes nodes should use as the API server cluster endpoint. @@ -792,6 +795,87 @@ protected boolean createCloudStackSecret(String[] keys) { return false; } + /** + * Creates a bootstrap token on the control node for nodes about to join, and reads the + * cluster CA hash they pin with --discovery-token-ca-cert-hash. + */ + protected void createJoinToken(final long ttlSeconds) { + Pair publicIpSshPort = getKubernetesClusterServerIpSshPort(null); + String command = String.format("sudo /opt/bin/kubeadm token create --ttl %s --print-join-command", KubernetesClusterUtil.getJoinTokenTtl(ttlSeconds)); + Pair tokenAndHash = null; + try { + Pair result = SshHelper.sshExecute(publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(), + getManagementServerSshPublicKeyFile(), null, command, 10000, 10000, 60000); + if (result.first()) { + tokenAndHash = KubernetesClusterUtil.parseJoinCommand(result.second()); + joinEndpointIp = KubernetesClusterUtil.parseJoinEndpointIp(result.second()); + } else { + logger.warn("Failed to create a join token on Kubernetes cluster {}: {}", kubernetesCluster, result.second()); + } + } catch (Exception e) { + logger.warn("Failed to create a join token on Kubernetes cluster: {}", kubernetesCluster, e); + } + if (tokenAndHash == null) { + throw new CloudRuntimeException(String.format("Failed to create a join token on Kubernetes cluster: %s", kubernetesCluster.getName())); + } + joinToken = tokenAndHash.first(); + joinCaCertHash = tokenAndHash.second(); + } + + /** + * Whether the API server certificate served on the IP is valid for it, as a join that pins the CA needs, + * or null if that can not be told. + */ + protected Boolean isApiServerCertificateValidFor(final String ip) { + String command = String.format("echo | timeout 10 openssl s_client -connect %s:%d 2>/dev/null | openssl x509 -noout -checkip %s; true", + ip, CLUSTER_API_PORT, ip); + try { + Pair publicIpSshPort = getKubernetesClusterServerIpSshPort(null); + Pair result = SshHelper.sshExecute(publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(), + getManagementServerSshPublicKeyFile(), null, command, 10000, 10000, 30000); + return KubernetesClusterUtil.parseCertificateCheckIp(result.second(), ip); + } catch (Exception e) { + logger.warn("Unable to check the API server certificate of Kubernetes cluster {} on {}", kubernetesCluster, ip, e); + return null; + } + } + + /** + * The API server address nodes join on: the control node's own IP, as at create, unless the API server + * certificate is known not to be valid for it (external etcd clusters created before it was added). + * Then the address kubeadm prints with the join command, which the certificate always covers. + */ + protected String getNodeJoinIp() { + final String controlNodeIp = getControlVmPrivateIp(); + if (controlNodeIp == null) { + return joinEndpointIp; + } + if (joinEndpointIp == null || joinEndpointIp.equals(controlNodeIp) || !Boolean.FALSE.equals(isApiServerCertificateValidFor(controlNodeIp))) { + return controlNodeIp; + } + logger.info("The API server certificate of Kubernetes cluster {} is not valid for {}, nodes join on {}", kubernetesCluster, controlNodeIp, joinEndpointIp); + return joinEndpointIp; + } + + protected void deleteJoinToken() { + if (joinToken == null) { + return; + } + try { + String command = String.format("sudo /opt/bin/kubeadm token delete %s", joinToken.substring(0, 6)); + Pair publicIpSshPort = getKubernetesClusterServerIpSshPort(null); + Pair result = SshHelper.sshExecute(publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(), + getManagementServerSshPublicKeyFile(), null, command, 10000, 10000, 60000); + if (!result.first()) { + logger.warn("Failed to delete the join token on Kubernetes cluster {}, it expires on its own: {}", kubernetesCluster, result.second()); + } + } catch (Exception e) { + logger.warn("Failed to delete the join token on Kubernetes cluster {}, it expires on its own", kubernetesCluster, e); + } + joinToken = null; + joinCaCertHash = null; + } + protected File retrieveScriptFile(String filename) { File file = null; try { @@ -1022,6 +1106,7 @@ public String getKubernetesNodeConfig(final String joinIp, final boolean ejectIs final String sshPubKey = "{{ k8s.ssh.pub.key }}"; final String joinIpKey = "{{ k8s_control_node.join_ip }}"; final String clusterTokenKey = "{{ k8s_control_node.cluster.token }}"; + final String caCertHashKey = "{{ k8s_control_node.cluster.ca_cert_hash }}"; final String ejectIsoKey = "{{ k8s.eject.iso }}"; final String routerIpKey = "{{ k8s.vr.iso.mounted.ip }}"; final String installWaitTime = "{{ k8s.install.wait.time }}"; @@ -1046,7 +1131,8 @@ public String getKubernetesNodeConfig(final String joinIp, final boolean ejectIs } k8sNodeConfig = k8sNodeConfig.replace(sshPubKey, pubKey); k8sNodeConfig = k8sNodeConfig.replace(joinIpKey, joinIp); - k8sNodeConfig = k8sNodeConfig.replace(clusterTokenKey, KubernetesClusterUtil.generateClusterToken(kubernetesCluster)); + k8sNodeConfig = k8sNodeConfig.replace(clusterTokenKey, joinToken); + k8sNodeConfig = k8sNodeConfig.replace(caCertHashKey, joinCaCertHash); k8sNodeConfig = k8sNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso)); k8sNodeConfig = k8sNodeConfig.replace(routerIpKey, routerIp); k8sNodeConfig = k8sNodeConfig.replace(installWaitTime, String.valueOf(waitTime)); diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterAddWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterAddWorker.java index 8b694adf1cca..15e4d790f68d 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterAddWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterAddWorker.java @@ -86,10 +86,11 @@ public boolean addNodesToCluster(List nodeIds, boolean mountCksIsoOnVr, bo } catch (ManagementServerException e) { throw new CloudRuntimeException(String.format("Failed to retrieve public IP for the network: %s ", network.getName())); } + createJoinToken(KubernetesClusterService.KubernetesClusterAddNodeTimeout.value()); attachCksIsoForNodesAdditionToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr); stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.AddNodeRequested); - String controlNodeGuestIp = getControlVmPrivateIp(); - Ternary nodesAddedAndMemory = importNodeToCluster(nodeIds, network, publicIp, controlNodeGuestIp, mountCksIsoOnVr); + String joinIp = getNodeJoinIp(); + Ternary nodesAddedAndMemory = importNodeToCluster(nodeIds, network, publicIp, joinIp, mountCksIsoOnVr); int nodesAdded = nodesAddedAndMemory.first(); updateKubernetesCluster(kubernetesCluster.getId(), nodesAddedAndMemory, manualUpgrade); if (nodeIds.size() != nodesAdded) { @@ -97,6 +98,7 @@ public boolean addNodesToCluster(List nodeIds, boolean mountCksIsoOnVr, bo logger.info(msg); detachCksIsoFromNodesAddedToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr); stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed); + deleteUnusedJoinToken(); ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), CallContext.current().getCallingAccountId(), EventVO.LEVEL_ERROR, KubernetesClusterEventTypes.EVENT_KUBERNETES_CLUSTER_NODES_ADD, msg, kubernetesCluster.getId(), ApiCommandResourceType.KubernetesCluster.toString(), 0); @@ -105,6 +107,7 @@ public boolean addNodesToCluster(List nodeIds, boolean mountCksIsoOnVr, bo Pair publicIpSshPort = getKubernetesClusterServerIpSshPort(null); KubernetesClusterUtil.validateKubernetesClusterReadyNodesCount(kubernetesCluster, publicIpSshPort.first(), publicIpSshPort.second(), getControlNodeLoginUser(), sshKeyFile, addNodeTimeoutTime, 15000); + deleteJoinToken(); detachCksIsoFromNodesAddedToCluster(nodeIds, kubernetesCluster.getId(), mountCksIsoOnVr); stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationSucceeded); String description = String.format("Successfully added %s nodes to Kubernetes Cluster %s", nodesAdded, kubernetesCluster.getUuid()); @@ -114,10 +117,18 @@ public boolean addNodesToCluster(List nodeIds, boolean mountCksIsoOnVr, bo return true; } catch (Exception e) { stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed); + deleteUnusedJoinToken(); throw new CloudRuntimeException(e); } } + /** A node rebooted with join userdata may still be joining; otherwise the token is no longer needed */ + private void deleteUnusedJoinToken() { + if (finalNodeIds.isEmpty()) { + deleteJoinToken(); + } + } + private void detachCksIsoFromNodesAddedToCluster(List nodeIds, long kubernetesClusterId, boolean mountCksIsoOnVr) { if (mountCksIsoOnVr) { detachIsoOnVirtualRouter(kubernetesClusterId); diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java index 8f8d3aff87eb..1b3b078cc19c 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterScaleWorker.java @@ -497,6 +497,11 @@ private void scaleUpKubernetesClusterSize(final long newVmCount) throws CloudRun LaunchPermissionVO launchPermission = new LaunchPermissionVO(clusterTemplate.getId(), owner.getId()); launchPermissionDao.persist(launchPermission); } + try { + createJoinToken(KubernetesClusterService.KubernetesClusterScaleTimeout.value()); + } catch (CloudRuntimeException e) { + logTransitStateToFailedIfNeededAndThrow(Level.ERROR, String.format("Scaling failed for Kubernetes cluster : %s, unable to create a join token", kubernetesCluster.getName()), e); + } try { clusterVMs = provisionKubernetesClusterNodeVms((int)(newVmCount + kubernetesCluster.getNodeCount()), (int)kubernetesCluster.getNodeCount(), apiPublicIpAddress, kubernetesCluster.getDomainId(), kubernetesCluster.getAccountId()); updateLoginUserDetails(clusterVMs.stream().map(InternalIdentity::getId).collect(Collectors.toList())); @@ -517,6 +522,7 @@ private void scaleUpKubernetesClusterSize(final long newVmCount) throws CloudRun boolean readyNodesCountValid = KubernetesClusterUtil.validateKubernetesClusterReadyNodesCount(kubernetesClusterVO, publicIpAddress, sshPort, getControlNodeLoginUser(), sshKeyFile, scaleTimeoutTime, 15000); detachIsoKubernetesVMs(clusterVMs); + deleteJoinToken(); deleteTemplateLaunchPermission(); if (!readyNodesCountValid) { // Scaling failed logTransitStateToFailedIfNeededAndThrow(Level.ERROR, String.format("Scaling unsuccessful for Kubernetes cluster : %s as it does not have desired number of nodes in ready state", kubernetesCluster.getName())); diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java index 4b7f3c672258..9b5818522e72 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorker.java @@ -22,6 +22,8 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; +import java.security.KeyPair; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -78,6 +80,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; +import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.ReservationContext; import com.cloud.vm.ReservationContextImpl; import com.cloud.vm.UserVmManager; @@ -92,6 +95,9 @@ public class KubernetesClusterStartWorker extends KubernetesClusterResourceModifierActionWorker { private KubernetesSupportedVersion kubernetesClusterVersion; + private KeyPair clusterCaKeyPair; + private X509Certificate clusterCaCert; + private String certificateKey; public KubernetesClusterStartWorker(final KubernetesCluster kubernetesCluster, final KubernetesClusterManagerImpl clusterManager) { super(kubernetesCluster, clusterManager); @@ -176,24 +182,19 @@ private Pair getKubernetesControlNodeConfig(final String control final String caCert = "{{ k8s_control_node.ca.crt }}"; final String sshPubKey = "{{ k8s.ssh.pub.key }}"; final String clusterToken = "{{ k8s_control_node.cluster.token }}"; + final String clusterTokenTtl = "{{ k8s_control_node.cluster.token.ttl }}"; final String clusterInitArgsKey = "{{ k8s_control_node.cluster.initargs }}"; final String ejectIsoKey = "{{ k8s.eject.iso }}"; final String installWaitTime = "{{ k8s.install.wait.time }}"; final String installReattemptsCount = "{{ k8s.install.reattempts.count }}"; final String externalEtcdNodes = "{{ etcd.unstacked_etcd }}"; final String etcdEndpointList = "{{ etcd.etcd_endpoint_list }}"; - final String k8sServerIp = "{{ k8s_control.server_ip }}"; final String k8sApiPort = "{{ k8s.api_server_port }}"; - final String certSans = "{{ k8s_control.server_ips }}"; final String k8sCertificate = "{{ k8s_control.certificate_key }}"; final String externalCniPlugin = "{{ k8s.external.cni.plugin }}"; final String setupCsiDriver = "{{ k8s.setup.csi.driver }}"; - final List addresses = new ArrayList<>(); - addresses.add(controlNodeIp); - if (!serverIp.equals(controlNodeIp)) { - addresses.add(serverIp); - } + final List addresses = getApiServerAddresses(controlNodeIp, serverIp); boolean externalEtcd = !etcdIps.isEmpty(); final Certificate certificate = caManager.issueCertificate(null, Arrays.asList(hostName, "kubernetes", @@ -220,24 +221,24 @@ private Pair getKubernetesControlNodeConfig(final String control k8sControlNodeConfig = k8sControlNodeConfig.replace(installWaitTime, String.valueOf(waitTime)); k8sControlNodeConfig = k8sControlNodeConfig.replace(installReattemptsCount, String.valueOf(reattempts)); k8sControlNodeConfig = k8sControlNodeConfig.replace(sshPubKey, pubKey); - k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterToken, KubernetesClusterUtil.generateClusterToken(kubernetesCluster)); + k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterToken, joinToken); + k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterTokenTtl, KubernetesClusterUtil.getJoinTokenTtl(KubernetesClusterService.KubernetesClusterStartTimeout.value())); k8sControlNodeConfig = k8sControlNodeConfig.replace(externalEtcdNodes, String.valueOf(externalEtcd)); String initArgs = ""; if (haSupported) { initArgs = String.format("--control-plane-endpoint %s:%d --upload-certs --certificate-key %s ", serverIp, CLUSTER_API_PORT, - KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); + certificateKey); } - initArgs += String.format("--apiserver-cert-extra-sans=%s", serverIp); + initArgs += String.format("--apiserver-cert-extra-sans=%s", String.join(",", addresses)); initArgs += String.format(" --kubernetes-version=%s", getKubernetesClusterVersion().getSemanticVersion()); k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterInitArgsKey, initArgs); k8sControlNodeConfig = k8sControlNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso)); k8sControlNodeConfig = k8sControlNodeConfig.replace(etcdEndpointList, endpointList); - k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sServerIp, serverIp); + k8sControlNodeConfig = setKubeadmApiServerAddresses(k8sControlNodeConfig, controlNodeIp, serverIp); k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sApiPort, String.valueOf(CLUSTER_API_PORT)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(certSans, String.format("- %s", serverIp)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sCertificate, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); + k8sControlNodeConfig = k8sControlNodeConfig.replace(k8sCertificate, certificateKey); k8sControlNodeConfig = k8sControlNodeConfig.replace(externalCniPlugin, String.valueOf(externalCni)); k8sControlNodeConfig = k8sControlNodeConfig.replace(setupCsiDriver, String.valueOf(setupCsi)); @@ -246,6 +247,28 @@ private Pair getKubernetesControlNodeConfig(final String control return new Pair<>(k8sControlNodeConfig, controlNodeIp); } + static List getApiServerAddresses(final String controlNodeIp, final String serverIp) { + final List addresses = new ArrayList<>(); + addresses.add(controlNodeIp); + if (!serverIp.equals(controlNodeIp)) { + addresses.add(serverIp); + } + return addresses; + } + + /** + * Clients reach the API on serverIp (the public IP or load balancer), which stays the + * controlPlaneEndpoint. Nodes join on controlNodeIp, so the certificate covers both. With + * external etcd the API server advertises controlNodeIp, as kubeadm does by default in the + * stacked case, so the kubernetes Service does not point pods at the public IP. + */ + static String setKubeadmApiServerAddresses(String config, final String controlNodeIp, final String serverIp) { + config = config.replace("{{ k8s_control.server_ip }}", serverIp); + config = config.replace("{{ k8s_control.node_ip }}", controlNodeIp); + return config.replace("{{ k8s_control.server_ips }}", getApiServerAddresses(controlNodeIp, serverIp).stream() + .map(ip -> "\"" + ip + "\"").collect(Collectors.joining(", ", "[", "]"))); + } + private Pair createKubernetesControlNode(final Network network, String serverIp, List etcdIps, Long domainId, Long accountId, Long asNumber) throws ManagementServerException, ResourceUnavailableException, InsufficientCapacityException { UserVm controlVm = null; @@ -334,6 +357,7 @@ private String getKubernetesAdditionalControlNodeConfig(final String joinIp, fin final String clusterTokenKey = "{{ k8s_control_node.cluster.token }}"; final String sshPubKey = "{{ k8s.ssh.pub.key }}"; final String clusterHACertificateKey = "{{ k8s_control_node.cluster.ha.certificate.key }}"; + final String caCertHashKey = "{{ k8s_control_node.cluster.ca_cert_hash }}"; final String ejectIsoKey = "{{ k8s.eject.iso }}"; final String installWaitTime = "{{ k8s.install.wait.time }}"; final String installReattemptsCount = "{{ k8s.install.reattempts.count }}"; @@ -353,8 +377,9 @@ private String getKubernetesAdditionalControlNodeConfig(final String joinIp, fin k8sControlNodeConfig = k8sControlNodeConfig.replace(installReattemptsCount, String.valueOf(reattempts)); k8sControlNodeConfig = k8sControlNodeConfig.replace(sshPubKey, pubKey); k8sControlNodeConfig = k8sControlNodeConfig.replace(joinIpKey, joinIp); - k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterTokenKey, KubernetesClusterUtil.generateClusterToken(kubernetesCluster)); - k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterHACertificateKey, KubernetesClusterUtil.generateClusterHACertificateKey(kubernetesCluster)); + k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterTokenKey, joinToken); + k8sControlNodeConfig = k8sControlNodeConfig.replace(clusterHACertificateKey, certificateKey); + k8sControlNodeConfig = k8sControlNodeConfig.replace(caCertHashKey, joinCaCertHash); k8sControlNodeConfig = k8sControlNodeConfig.replace(ejectIsoKey, String.valueOf(ejectIso)); k8sControlNodeConfig = updateKubeConfigWithRegistryDetails(k8sControlNodeConfig); @@ -768,6 +793,78 @@ private void updateKubernetesClusterEntryEndpoint() { kubernetesClusterDao.update(kubernetesCluster.getId(), kubernetesClusterVO); } + /** + * The cluster CA is created here rather than by kubeadm init so that nodes created alongside + * the first control node can pin its hash. Its key is copied to the control node over SSH + * and never goes into userdata. + */ + private void generateClusterJoinSecrets() throws Exception { + clusterCaKeyPair = CertUtils.generateRandomKeyPair(2048); + clusterCaCert = CertUtils.generateV3Certificate(null, clusterCaKeyPair, clusterCaKeyPair.getPublic(), + "CN=kubernetes", "SHA256WithRSA", 3650, null, null); + joinToken = KubernetesClusterUtil.generateBootstrapToken(); + joinCaCertHash = KubernetesClusterUtil.getCaCertHash(clusterCaKeyPair.getPublic()); + certificateKey = KubernetesClusterUtil.generateCertificateKey(); + } + + private boolean copyClusterCaToControlNode(final String ipAddress, final int port, final long timeoutTime) { + final byte[] caCert; + final byte[] caKey; + try { + caCert = CertUtils.x509CertificateToPem(clusterCaCert).getBytes(com.cloud.utils.StringUtils.getPreferredCharset()); + caKey = CertUtils.privateKeyToPem(clusterCaKeyPair.getPrivate()).getBytes(com.cloud.utils.StringUtils.getPreferredCharset()); + } catch (IOException e) { + logger.error("Failed to encode the CA for Kubernetes cluster {}", kubernetesCluster, e); + return false; + } + // kubeadm init starts once both files exist, so each is renamed into place whole + String command = "sudo mkdir -p /etc/kubernetes/pki && " + + "sudo install -m 0644 -o root -g root ca.crt /etc/kubernetes/pki/ca.crt.tmp && " + + "sudo install -m 0600 -o root -g root ca.key /etc/kubernetes/pki/ca.key.tmp && " + + "sudo mv /etc/kubernetes/pki/ca.crt.tmp /etc/kubernetes/pki/ca.crt && " + + "sudo mv /etc/kubernetes/pki/ca.key.tmp /etc/kubernetes/pki/ca.key; " + + "rc=$?; rm -f ca.crt ca.key; exit $rc"; + while (System.currentTimeMillis() < timeoutTime) { + try { + SshHelper.scpTo(ipAddress, port, getControlNodeLoginUser(), sshKeyFile, null, ".", caCert, "ca.crt", "0600"); + SshHelper.scpTo(ipAddress, port, getControlNodeLoginUser(), sshKeyFile, null, ".", caKey, "ca.key", "0600"); + Pair result = SshHelper.sshExecute(ipAddress, port, getControlNodeLoginUser(), sshKeyFile, null, + command, 10000, 10000, 60000); + if (result.first()) { + clusterCaKeyPair = null; + return true; + } + logger.warn("Failed to install the CA on Kubernetes cluster {} control node, retrying: {}", kubernetesCluster, result.second()); + } catch (Exception e) { + logger.info("Waiting for Kubernetes cluster {} control node to accept SSH: {}", kubernetesCluster, e.getMessage()); + } + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + return false; + } + + /** + * Every node has joined. The uploaded control plane certificates can be read with the create + * token, which is in node userdata, so remove both rather than wait for them to expire. + */ + private void deleteCreateJoinSecrets() { + deleteJoinToken(); + try { + Pair result = SshHelper.sshExecute(publicIpAddress, sshPort, getControlNodeLoginUser(), sshKeyFile, null, + "sudo /opt/bin/kubectl -n kube-system delete secret kubeadm-certs --ignore-not-found", 10000, 10000, 60000); + if (!result.first()) { + logger.warn("Failed to delete the kubeadm-certs secret on Kubernetes cluster {}, it expires on its own: {}", kubernetesCluster, result.second()); + } + } catch (Exception e) { + logger.warn("Failed to delete the kubeadm-certs secret on Kubernetes cluster {}, it expires on its own", kubernetesCluster, e); + } + } + public boolean startKubernetesClusterOnCreate(Long domainId, Long accountId, Long asNumber) throws ManagementServerException, ResourceUnavailableException, InsufficientCapacityException { init(); if (logger.isInfoEnabled()) { @@ -775,6 +872,11 @@ public boolean startKubernetesClusterOnCreate(Long domainId, Long accountId, Lon } final long startTimeoutTime = System.currentTimeMillis() + KubernetesClusterService.KubernetesClusterStartTimeout.value() * 1000; stateTransitTo(kubernetesCluster.getId(), KubernetesCluster.Event.StartRequested); + try { + generateClusterJoinSecrets(); + } catch (Exception e) { + logTransitStateAndThrow(Level.ERROR, String.format("Failed to generate the CA for Kubernetes cluster : %s", kubernetesCluster.getName()), kubernetesCluster.getId(), KubernetesCluster.Event.CreateFailed, e); + } DeployDestination dest = null; try { VMTemplateVO clusterTemplate = templateDao.findById(kubernetesCluster.getTemplateId()); @@ -871,6 +973,9 @@ public boolean startKubernetesClusterOnCreate(Long domainId, Long accountId, Lon } logTransitStateDetachIsoAndThrow(Level.ERROR, msg, kubernetesCluster, clusterVMs, KubernetesCluster.Event.CreateFailed, null); } + if (!copyClusterCaToControlNode(publicIpAddress, publicIpSshPort.second(), startTimeoutTime)) { + logTransitStateDetachIsoAndThrow(Level.ERROR, String.format("Failed to setup Kubernetes cluster : %s, unable to copy the cluster CA to the control node", kubernetesCluster.getName()), kubernetesCluster, clusterVMs, KubernetesCluster.Event.CreateFailed, null); + } boolean k8sApiServerSetup = KubernetesClusterUtil.isKubernetesClusterServerRunning(kubernetesCluster, apiPublicIpAddress, CLUSTER_API_PORT, startTimeoutTime, 15000); if (!k8sApiServerSetup) { logTransitStateDetachIsoAndThrow(Level.ERROR, String.format("Failed to setup Kubernetes cluster : %s in usable state as unable to provision API endpoint for the cluster", kubernetesCluster.getName()), kubernetesCluster, clusterVMs, KubernetesCluster.Event.CreateFailed, null); @@ -883,6 +988,7 @@ public boolean startKubernetesClusterOnCreate(Long domainId, Long accountId, Lon if (!readyNodesCountValid) { logTransitStateAndThrow(Level.ERROR, String.format("Failed to setup Kubernetes cluster : %s as it does not have desired number of nodes in ready state", kubernetesCluster.getName()), kubernetesCluster.getId(), KubernetesCluster.Event.CreateFailed); } + deleteCreateJoinSecrets(); if (!isKubernetesClusterKubeConfigAvailable(startTimeoutTime)) { logTransitStateAndThrow(Level.ERROR, String.format("Failed to setup Kubernetes cluster : %s in usable state as unable to retrieve kube-config for the cluster", kubernetesCluster.getName()), kubernetesCluster.getId(), KubernetesCluster.Event.OperationFailed); } diff --git a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtil.java b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtil.java index 00625f6e076d..5125080b567a 100644 --- a/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtil.java +++ b/plugins/integrations/kubernetes-service/src/main/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtil.java @@ -24,7 +24,10 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.net.URL; +import java.security.PublicKey; import java.security.SecureRandom; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.net.ssl.HttpsURLConnection; @@ -34,6 +37,9 @@ import com.cloud.kubernetes.cluster.KubernetesClusterVmMapVO; import com.cloud.kubernetes.cluster.dao.KubernetesClusterVmMapDao; import org.apache.cloudstack.utils.security.SSLUtils; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; @@ -41,6 +47,7 @@ import com.cloud.kubernetes.cluster.KubernetesCluster; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; +import com.cloud.utils.net.NetUtils; import com.cloud.utils.nio.TrustAllManager; import com.cloud.utils.ssh.SshHelper; @@ -50,6 +57,11 @@ public class KubernetesClusterUtil { public static final String CLUSTER_NODE_READY_COMMAND = "sudo /opt/bin/kubectl get nodes | awk '{if ($1 == \"%s\" && $2 == \"Ready\") print $1}'"; public static final String CLUSTER_NODE_VERSION_COMMAND = "sudo /opt/bin/kubectl get nodes | awk '{if ($1 == \"%s\") print $5}'"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static final char[] BOOTSTRAP_TOKEN_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); + private static final Pattern JOIN_TOKEN = Pattern.compile("--token\\s+([a-z0-9]{6}\\.[a-z0-9]{16})(?!\\S)"); + private static final Pattern JOIN_ENDPOINT = Pattern.compile("kubeadm join ([0-9.]+):[0-9]+(?!\\S)"); + private static final Pattern JOIN_CA_CERT_HASH = Pattern.compile("--discovery-token-ca-cert-hash\\s+(sha256:[0-9a-f]{64})(?!\\S)"); public static boolean isKubernetesClusterNodeReady(final KubernetesCluster kubernetesCluster, String ipAddress, int port, String user, File sshKeyFile, String nodeName) throws Exception { @@ -312,21 +324,73 @@ public static boolean validateKubernetesClusterReadyNodesCount(final KubernetesC return false; } - public static String generateClusterToken(final KubernetesCluster kubernetesCluster) { - String token = kubernetesCluster.getUuid(); - token = token.replaceAll("-", ""); - token = token.substring(0, 22); - token = token.substring(0, 6) + "." + token.substring(6); - return token; + public static String generateBootstrapToken() { + return RandomStringUtils.random(6, 0, 0, false, false, BOOTSTRAP_TOKEN_CHARS, RANDOM) + "." + + RandomStringUtils.random(16, 0, 0, false, false, BOOTSTRAP_TOKEN_CHARS, RANDOM); } - public static String generateClusterHACertificateKey(final KubernetesCluster kubernetesCluster) { - String uuid = kubernetesCluster.getUuid(); - StringBuilder token = new StringBuilder(uuid.replaceAll("-", "")); - while (token.length() < 64) { - token.append(token); + /** + * kubeadm treats a TTL of 0 as never expiring, so never pass it one. + */ + public static String getJoinTokenTtl(final long ttlSeconds) { + return Math.max(ttlSeconds, 1) + "s"; + } + + public static String generateCertificateKey() { + byte[] key = new byte[32]; + RANDOM.nextBytes(key); + return Hex.encodeHexString(key); + } + + public static String getCaCertHash(final PublicKey caPublicKey) { + return "sha256:" + DigestUtils.sha256Hex(caPublicKey.getEncoded()); + } + + /** + * Parses the API server address from the output of kubeadm token create --print-join-command. + * kubeadm prints the controlPlaneEndpoint if the cluster has one, else the advertise address, + * so the API server certificate is valid for it. + * @return the IPv4 address, or null if there is none + */ + public static String parseJoinEndpointIp(final String joinCommand) { + if (StringUtils.isBlank(joinCommand)) { + return null; + } + Matcher endpoint = JOIN_ENDPOINT.matcher(joinCommand); + if (!endpoint.find() || !NetUtils.isValidIp4(endpoint.group(1))) { + return null; + } + return endpoint.group(1); + } + + /** + * Parses the output of openssl x509 -checkip. + * @return whether the certificate is valid for the IP, or null if the output does not say + */ + public static Boolean parseCertificateCheckIp(final String output, final String ip) { + if (StringUtils.isBlank(output)) { + return null; + } + if (output.contains(String.format("IP %s does NOT match certificate", ip))) { + return false; + } + return output.contains(String.format("IP %s does match certificate", ip)) ? true : null; + } + + /** + * Parses the output of kubeadm token create --print-join-command. + * @return the token and the CA certificate hash, or null if either is missing + */ + public static Pair parseJoinCommand(final String joinCommand) { + if (StringUtils.isBlank(joinCommand)) { + return null; + } + Matcher token = JOIN_TOKEN.matcher(joinCommand); + Matcher hash = JOIN_CA_CERT_HASH.matcher(joinCommand); + if (!token.find() || !hash.find()) { + return null; } - return token.toString().substring(0, 64); + return new Pair<>(token.group(1), hash.group(1)); } public static boolean clusterNodeVersionMatches(final String version, diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml index 38f217f403c4..d2c73b835605 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node-add.yml @@ -236,7 +236,7 @@ write_files: if [[ "$PATH" != *:/opt/bin && "$PATH" != *:/opt/bin:* ]]; then export PATH=$PATH:/opt/bin fi - kubeadm join {{ k8s_control_node.join_ip }}:6443 --token {{ k8s_control_node.cluster.token }} --control-plane --certificate-key {{ k8s_control_node.cluster.ha.certificate.key }} --discovery-token-unsafe-skip-ca-verification + kubeadm join {{ k8s_control_node.join_ip }}:6443 --token {{ k8s_control_node.cluster.token }} --control-plane --certificate-key {{ k8s_control_node.cluster.ha.certificate.key }} --discovery-token-ca-cert-hash {{ k8s_control_node.cluster.ca_cert_hash }} mkdir -p /root/.kube cp -i /etc/kubernetes/admin.conf /root/.kube/config diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml index 70291dd1c35a..31f743ce1b6d 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-control-node.yml @@ -249,8 +249,7 @@ write_files: apiVersion: kubeadm.k8s.io/v1beta3 kind: ClusterConfiguration apiServer: - certSANs: - {{ k8s_control.server_ips }} + certSANs: {{ k8s_control.server_ips }} controlPlaneEndpoint: {{ k8s_control.server_ip }}:{{ k8s.api_server_port }} etcd: external: @@ -261,11 +260,11 @@ write_files: kind: InitConfiguration bootstrapTokens: - token: "{{ k8s_control_node.cluster.token }}" - ttl: "0" + ttl: "{{ k8s_control_node.cluster.token.ttl }}" nodeRegistration: criSocket: /run/containerd/containerd.sock localAPIEndpoint: - advertiseAddress: {{ k8s_control.server_ip }} + advertiseAddress: {{ k8s_control.node_ip }} bindPort: {{ k8s.api_server_port }} certificateKey: {{ k8s_control.certificate_key }} @@ -288,6 +287,10 @@ write_files: EXTERNAL_ETCD_NODES={{ etcd.unstacked_etcd }} EXTERNAL_CNI_PLUGIN={{ k8s.external.cni.plugin }} MAX_SETUP_CRUCIAL_CMD_ATTEMPTS=3 + until [[ -f /etc/kubernetes/pki/ca.crt && -f /etc/kubernetes/pki/ca.key ]]; do + echo "Waiting for the cluster CA" + sleep 5 + done crucial_cmd_attempts=1 while true; do if (( "$crucial_cmd_attempts" > "$MAX_SETUP_CRUCIAL_CMD_ATTEMPTS" )); then @@ -299,7 +302,7 @@ write_files: if [[ ${EXTERNAL_ETCD_NODES} == true ]]; then kubeadm init --config /etc/kubernetes/kubeadm-config.yaml --upload-certs else - kubeadm init --token {{ k8s_control_node.cluster.token }} --token-ttl 0 {{ k8s_control_node.cluster.initargs }} --cri-socket /run/containerd/containerd.sock + kubeadm init --token {{ k8s_control_node.cluster.token }} --token-ttl {{ k8s_control_node.cluster.token.ttl }} {{ k8s_control_node.cluster.initargs }} --cri-socket /run/containerd/containerd.sock fi retval=$? set -e diff --git a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-node.yml b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-node.yml index fd9617e69dec..1751a874242d 100644 --- a/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-node.yml +++ b/plugins/integrations/kubernetes-service/src/main/resources/conf/k8s-node.yml @@ -251,7 +251,7 @@ write_files: if [[ "$PATH" != *:/opt/bin && "$PATH" != *:/opt/bin:* ]]; then export PATH=$PATH:/opt/bin fi - kubeadm join {{ k8s_control_node.join_ip }}:6443 --token {{ k8s_control_node.cluster.token }} --discovery-token-unsafe-skip-ca-verification + kubeadm join {{ k8s_control_node.join_ip }}:6443 --token {{ k8s_control_node.cluster.token }} --discovery-token-ca-cert-hash {{ k8s_control_node.cluster.ca_cert_hash }} sudo touch /home/cloud/success echo "true" > /home/cloud/success diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java index 1eb55808e09d..85b078f32f19 100644 --- a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterActionWorkerTest.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.kubernetes.cluster.actionworkers; +import java.io.File; import java.util.UUID; import org.apache.cloudstack.api.ApiConstants; @@ -24,6 +25,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @@ -38,6 +40,10 @@ import com.cloud.network.Network; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressVO; +import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; +import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.ssh.SshHelper; @RunWith(MockitoJUnitRunner.class) public class KubernetesClusterActionWorkerTest { @@ -76,6 +82,81 @@ public void setUp() throws Exception { actionWorker.ipAddressDao = ipAddressDao; } + private KubernetesClusterActionWorker joinIpWorker(String printedIp) { + KubernetesClusterActionWorker worker = Mockito.spy(actionWorker); + Mockito.doReturn(new Pair<>("203.0.113.5", 2222)).when(worker).getKubernetesClusterServerIpSshPort(Mockito.nullable(UserVm.class)); + Mockito.doReturn("cloud").when(worker).getControlNodeLoginUser(); + Mockito.doReturn(new File("id_rsa")).when(worker).getManagementServerSshPublicKeyFile(); + Mockito.doReturn("10.1.1.10").when(worker).getControlVmPrivateIp(); + worker.joinEndpointIp = printedIp; + return worker; + } + + private String getNodeJoinIp(KubernetesClusterActionWorker worker, Pair checkResult) { + try (MockedStatic sshHelper = Mockito.mockStatic(SshHelper.class)) { + sshHelper.when(() -> SshHelper.sshExecute(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.any(), + Mockito.any(), Mockito.contains("-checkip 10.1.1.10"), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(checkResult); + String joinIp = worker.getNodeJoinIp(); + sshHelper.verify(() -> SshHelper.sshExecute(Mockito.eq("203.0.113.5"), Mockito.eq(2222), Mockito.eq("cloud"), Mockito.any(), + Mockito.any(), Mockito.contains("-checkip 10.1.1.10"), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())); + return joinIp; + } + } + + @Test + public void testNodeJoinIpIsTheControlNodeIpWhenTheCertificateCoversIt() { + Assert.assertEquals("10.1.1.10", getNodeJoinIp(joinIpWorker("203.0.113.5"), new Pair<>(true, "IP 10.1.1.10 does match certificate\n"))); + } + + @Test + public void testNodeJoinIpIsThePrintedEndpointWhenTheCertificateDoesNotCoverTheControlNodeIp() { + Assert.assertEquals("203.0.113.5", getNodeJoinIp(joinIpWorker("203.0.113.5"), new Pair<>(true, "IP 10.1.1.10 does NOT match certificate\n"))); + } + + @Test + public void testNodeJoinIpIsTheControlNodeIpWhenTheCertificateCanNotBeChecked() { + Assert.assertEquals("10.1.1.10", getNodeJoinIp(joinIpWorker("203.0.113.5"), new Pair<>(true, "Could not read certificate from \nUnable to load certificate\n"))); + } + + @Test + public void testNodeJoinIpIsTheControlNodeIpWithoutAPrintedEndpoint() { + KubernetesClusterActionWorker worker = joinIpWorker(null); + Assert.assertEquals("10.1.1.10", worker.getNodeJoinIp()); + Mockito.verify(worker, Mockito.never()).isApiServerCertificateValidFor(Mockito.anyString()); + } + + @Test + public void testDeleteJoinTokenOnlyOnce() { + KubernetesClusterActionWorker worker = Mockito.spy(actionWorker); + Mockito.doReturn(new Pair<>("10.1.1.1", 2222)).when(worker).getKubernetesClusterServerIpSshPort(Mockito.nullable(UserVm.class)); + Mockito.doReturn("cloud").when(worker).getControlNodeLoginUser(); + Mockito.doReturn(new File("id_rsa")).when(worker).getManagementServerSshPublicKeyFile(); + worker.joinToken = "abcdef.0123456789abcdef"; + worker.joinCaCertHash = "sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f"; + try (MockedStatic sshHelper = Mockito.mockStatic(SshHelper.class)) { + sshHelper.when(() -> SshHelper.sshExecute(Mockito.anyString(), Mockito.anyInt(), Mockito.anyString(), Mockito.any(), + Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(new Pair<>(true, "")); + worker.deleteJoinToken(); + worker.deleteJoinToken(); + sshHelper.verify(() -> SshHelper.sshExecute(Mockito.eq("10.1.1.1"), Mockito.eq(2222), Mockito.eq("cloud"), Mockito.any(), + Mockito.any(), Mockito.eq("sudo /opt/bin/kubeadm token delete abcdef"), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())); + sshHelper.verifyNoMoreInteractions(); + } + Assert.assertNull(worker.joinToken); + Assert.assertNull(worker.joinCaCertHash); + } + + @Test + public void testDeleteJoinTokenControlNodeUnreachable() { + KubernetesClusterActionWorker worker = Mockito.spy(actionWorker); + Mockito.doThrow(new CloudRuntimeException("no control node")).when(worker).getKubernetesClusterServerIpSshPort(Mockito.nullable(UserVm.class)); + worker.joinToken = "abcdef.0123456789abcdef"; + worker.deleteJoinToken(); + Assert.assertNull(worker.joinToken); + } + @Test public void testGetVpcTierKubernetesPublicIpNullDetail() { IpAddress result = actionWorker.getVpcTierKubernetesPublicIp(Mockito.mock(Network.class)); diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorkerTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorkerTest.java new file mode 100644 index 000000000000..65e7196bd47e --- /dev/null +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/actionworkers/KubernetesClusterStartWorkerTest.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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 com.cloud.kubernetes.cluster.actionworkers; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; + +import org.junit.Assert; +import org.junit.Test; + +public class KubernetesClusterStartWorkerTest { + + private static final String CONTROL_NODE_IP = "10.1.1.10"; + private static final String SERVER_IP = "203.0.113.5"; + + private static String kubeadmConfig(String controlNodeIp, String serverIp) throws IOException { + String template; + try (InputStream in = Objects.requireNonNull(KubernetesClusterStartWorkerTest.class.getResourceAsStream("/conf/k8s-control-node.yml"))) { + template = new String(in.readAllBytes(), StandardCharsets.UTF_8); + } + String config = KubernetesClusterStartWorker.setKubeadmApiServerAddresses(template, controlNodeIp, serverIp) + .replace("{{ k8s.api_server_port }}", "6443"); + int start = config.indexOf("path: /etc/kubernetes/kubeadm-config.yaml"); + Assert.assertTrue(start >= 0); + int end = config.indexOf("- path:", start); + Assert.assertTrue(end > start); + return config.substring(start, end); + } + + @Test + public void testGetApiServerAddresses() { + Assert.assertEquals(List.of(CONTROL_NODE_IP, SERVER_IP), KubernetesClusterStartWorker.getApiServerAddresses(CONTROL_NODE_IP, SERVER_IP)); + Assert.assertEquals(List.of(CONTROL_NODE_IP), KubernetesClusterStartWorker.getApiServerAddresses(CONTROL_NODE_IP, CONTROL_NODE_IP)); + } + + @Test + public void testExternalEtcdKubeadmConfigCertCoversControlNodeIp() throws IOException { + String config = kubeadmConfig(CONTROL_NODE_IP, SERVER_IP); + Assert.assertFalse(config.contains("{{ k8s_control.server_ip") || config.contains("{{ k8s_control.node_ip")); + Assert.assertTrue(config.contains(" certSANs: [\"" + CONTROL_NODE_IP + "\", \"" + SERVER_IP + "\"]\n")); + Assert.assertTrue(config.contains(" controlPlaneEndpoint: " + SERVER_IP + ":6443\n")); + Assert.assertTrue(config.contains(" advertiseAddress: " + CONTROL_NODE_IP + "\n")); + } + + @Test + public void testExternalEtcdKubeadmConfigSameIp() throws IOException { + String config = kubeadmConfig(CONTROL_NODE_IP, CONTROL_NODE_IP); + Assert.assertTrue(config.contains(" certSANs: [\"" + CONTROL_NODE_IP + "\"]\n controlPlaneEndpoint: " + CONTROL_NODE_IP + ":6443\n")); + Assert.assertTrue(config.contains(" advertiseAddress: " + CONTROL_NODE_IP + "\n")); + } +} diff --git a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtilTest.java b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtilTest.java index 329f9b0e42ad..ded51633ca32 100644 --- a/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtilTest.java +++ b/plugins/integrations/kubernetes-service/src/test/java/com/cloud/kubernetes/cluster/utils/KubernetesClusterUtilTest.java @@ -16,6 +16,11 @@ // under the License. package com.cloud.kubernetes.cluster.utils; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + import com.cloud.utils.Pair; import org.junit.Assert; import org.junit.Test; @@ -52,4 +57,72 @@ public void testClusterNodeVersionMatches() { executeThrowAndTestVersionMatch(); } + + @Test + public void testGenerateBootstrapToken() { + String token = KubernetesClusterUtil.generateBootstrapToken(); + Assert.assertTrue(token.matches("[a-z0-9]{6}\\.[a-z0-9]{16}")); + Assert.assertNotEquals(token, KubernetesClusterUtil.generateBootstrapToken()); + } + + @Test + public void testGenerateCertificateKey() { + String key = KubernetesClusterUtil.generateCertificateKey(); + Assert.assertTrue(key.matches("[0-9a-f]{64}")); + Assert.assertNotEquals(key, KubernetesClusterUtil.generateCertificateKey()); + } + + @Test + public void testGetCaCertHash() throws Exception { + byte[] der = Base64.getDecoder().decode("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAET4KHpN8Rsx35juCq20Wi0WJyBRRF" + + "Yl0p4YCFF6xxCY02Gelg7EYwHdPA/dbs+HrNwBBb/wuUNnEZiw1OQJXIRg=="); + PublicKey key = KeyFactory.getInstance("EC").generatePublic(new X509EncodedKeySpec(der)); + Assert.assertEquals("sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f", + KubernetesClusterUtil.getCaCertHash(key)); + } + + @Test + public void testParseJoinCommand() { + String hash = "sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f"; + Pair result = KubernetesClusterUtil.parseJoinCommand( + "kubeadm join 10.1.1.10:6443 --token abcdef.0123456789abcdef --discovery-token-ca-cert-hash " + hash + " \n"); + Assert.assertEquals("abcdef.0123456789abcdef", result.first()); + Assert.assertEquals(hash, result.second()); + } + + @Test + public void testParseJoinEndpointIp() { + String joinArgs = " --token abcdef.0123456789abcdef --discovery-token-ca-cert-hash sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f \n"; + Assert.assertEquals("203.0.113.5", KubernetesClusterUtil.parseJoinEndpointIp("kubeadm join 203.0.113.5:6443" + joinArgs)); + Assert.assertNull(KubernetesClusterUtil.parseJoinEndpointIp(null)); + Assert.assertNull(KubernetesClusterUtil.parseJoinEndpointIp("kubeadm join api.example.com:6443" + joinArgs)); + Assert.assertNull(KubernetesClusterUtil.parseJoinEndpointIp("kubeadm join 999.1.1.1:6443" + joinArgs)); + Assert.assertNull(KubernetesClusterUtil.parseJoinEndpointIp("kubeadm join 10.1.1.10:6443;id" + joinArgs)); + } + + @Test + public void testParseCertificateCheckIp() { + Assert.assertEquals(Boolean.TRUE, KubernetesClusterUtil.parseCertificateCheckIp("IP 10.1.1.10 does match certificate\n", "10.1.1.10")); + Assert.assertEquals(Boolean.FALSE, KubernetesClusterUtil.parseCertificateCheckIp("IP 10.1.1.10 does NOT match certificate\n", "10.1.1.10")); + Assert.assertNull(KubernetesClusterUtil.parseCertificateCheckIp("IP 10.1.1.100 does match certificate\n", "10.1.1.10")); + Assert.assertNull(KubernetesClusterUtil.parseCertificateCheckIp("Could not read certificate from \nUnable to load certificate\n", "10.1.1.10")); + Assert.assertNull(KubernetesClusterUtil.parseCertificateCheckIp(null, "10.1.1.10")); + } + + @Test + public void testParseJoinCommandInvalid() { + Assert.assertNull(KubernetesClusterUtil.parseJoinCommand(null)); + Assert.assertNull(KubernetesClusterUtil.parseJoinCommand("failed to load admin kubeconfig")); + Assert.assertNull(KubernetesClusterUtil.parseJoinCommand("kubeadm join 10.1.1.10:6443 --token abcdef.0123456789abcdef")); + Assert.assertNull(KubernetesClusterUtil.parseJoinCommand( + "kubeadm join 10.1.1.10:6443 --token $(reboot) --discovery-token-ca-cert-hash sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f")); + Assert.assertNull(KubernetesClusterUtil.parseJoinCommand( + "kubeadm join 10.1.1.10:6443 --token abcdef.0123456789abcdef;id --discovery-token-ca-cert-hash sha256:9826a516d7c2f8974dd0a09a64048c5cba6ff67780b01568b13cd3acf92a409f")); + } + + @Test + public void testGetJoinTokenTtl() { + Assert.assertEquals("3600s", KubernetesClusterUtil.getJoinTokenTtl(3600)); + Assert.assertEquals("1s", KubernetesClusterUtil.getJoinTokenTtl(0)); + } }