Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #4355: adding logic to set/validate the container name #4505

Merged
merged 3 commits into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* Fix #4547: preventing timing issues with leader election cancel

#### Improvements
* Fix #4355: for exec, attach, upload, and copy operations the container id/name will be validated or chosen prior to the remote call. You may also use the kubectl.kubernetes.io/default-container annotation to specify the default container.

#### Dependency Upgrade

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.fabric8.kubernetes.client.dsl.internal.core.v1;

import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.DeleteOptions;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Pod;
Expand Down Expand Up @@ -59,6 +60,8 @@
import io.fabric8.kubernetes.client.utils.Utils;
import io.fabric8.kubernetes.client.utils.internal.Base64;
import io.fabric8.kubernetes.client.utils.internal.PodOperationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
Expand All @@ -78,6 +81,7 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
Expand All @@ -90,6 +94,9 @@ public class PodOperationsImpl extends HasMetadataOperation<Pod, PodList, PodRes
public static final int HTTP_TOO_MANY_REQUESTS = 429;
private static final Integer DEFAULT_POD_LOG_WAIT_TIMEOUT = 5;
private static final String[] EMPTY_COMMAND = { "/bin/sh", "-i" };
public static final String DEFAULT_CONTAINER_ANNOTATION_NAME = "kubectl.kubernetes.io/default-container";

static final transient Logger LOG = LoggerFactory.getLogger(PodOperationsImpl.class);

private final PodOperationContext podOperationContext;

Expand Down Expand Up @@ -272,7 +279,7 @@ public PodOperationsImpl inContainer(
public ExecWatch exec(String... command) {
String[] actualCommands = command.length >= 1 ? command : EMPTY_COMMAND;
try {
URL url = getExecURLWithCommandParams(actualCommands);
URL url = getURL("exec", actualCommands);
return setupConnectionToPod(url.toURI());
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(forOperationType("exec"), e);
Expand All @@ -282,28 +289,56 @@ public ExecWatch exec(String... command) {
@Override
public ExecWatch attach() {
try {
URL url = getAttachURL();
URL url = getURL("attach", null);
return setupConnectionToPod(url.toURI());
} catch (Exception e) {
throw KubernetesClientException.launderThrowable(forOperationType("attach"), e);
}
}

private URL getExecURLWithCommandParams(String[] commands) throws MalformedURLException {
String url = URLUtils.join(getResourceUrl().toString(), "exec");
private URL getURL(String operation, String[] commands) throws MalformedURLException {
String url = URLUtils.join(getResourceUrl().toString(), operation);
URLBuilder httpUrlBuilder = new URLBuilder(url);
for (String cmd : commands) {
httpUrlBuilder.addQueryParameter("command", cmd);
if (commands != null) {
for (String cmd : commands) {
httpUrlBuilder.addQueryParameter("command", cmd);
}
}
getContext().addQueryParameters(httpUrlBuilder);
PodOperationContext contextToUse = getContext();
contextToUse = contextToUse.withContainerId(validateOrDefaultContainerId(contextToUse.getContainerId()));
contextToUse.addQueryParameters(httpUrlBuilder);
return httpUrlBuilder.build();
}

private URL getAttachURL() throws MalformedURLException {
String url = URLUtils.join(getResourceUrl().toString(), "attach");
URLBuilder httpUrlBuilder = new URLBuilder(url);
getContext().addQueryParameters(httpUrlBuilder);
return httpUrlBuilder.build();
/**
* If not specified, choose an appropriate default container id
*/
String validateOrDefaultContainerId(String name) {
Pod pod = this.require();
// spec and container null-checks are not necessary for real k8s clusters, added them to simplify some tests running in the mockserver
if (pod.getSpec() == null || pod.getSpec().getContainers() == null || pod.getSpec().getContainers().isEmpty()) {
throw new KubernetesClientException("Pod has no containers!");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@manusa see also

if you want to guard against invalid Pods/specs, all of that logic makes the same assumptions.

Copy link
Member

@manusa manusa Nov 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure that this is possible, I added this after implementing a test that failed (using the mockserver).
If it is possible to create a Pod without spec or containers (in real k8s -which I doubt), then we should definitely handle this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I don't believe it was possible. But I wasn't sure how pervasive you were trying to cover those cases.

Copy link
Member

@manusa manusa Nov 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So my thoughts:

  • I don't think this resource can exist in a real cluster (Pod | PodTemplate) -I did a very quick test-
  • I added this here because in the MockServer this resource can exist.
  • I don't think it hurts having these guards here, although the most correct approach would be to create a valid resource in the test and remove these.
  • I think it's fine leaving this here, but I can remove if you think it's inconsistent or that this might be confusing.

Please let me know what do you prefer

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about a comment explaining that it's for making testing easier. There's less danger it will be unnecessarily copied later that way.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good

}
final List<Container> containers = pod.getSpec().getContainers();
if (name == null) {
name = pod.getMetadata().getAnnotations().get(DEFAULT_CONTAINER_ANNOTATION_NAME);
if (name != null && !hasContainer(containers, name)) {
LOG.warn("Default container {} from annotation not found in pod {}", name, pod.getMetadata().getName());
name = null;
}
if (name == null) {
name = containers.get(0).getName();
LOG.debug("using first container {} in pod {}", name, pod.getMetadata().getName());
}
} else if (!hasContainer(containers, name)) {
throw new KubernetesClientException(
String.format("container %s not found in pod %s", name, pod.getMetadata().getName()));
}
return name;
}

private boolean hasContainer(List<Container> containers, String toFind) {
return containers.stream().map(Container::getName).anyMatch(s -> s.equals(toFind));
}

private ExecWebSocketListener setupConnectionToPod(URI uri) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,18 +55,14 @@ public static boolean upload(PodOperationsImpl operation, Path pathToUpload)
throw new IllegalArgumentException("Provided arguments are not valid (file, directory, path)");
}

private static interface UploadProcessor {
private interface UploadProcessor {

void process(OutputStream out) throws IOException;

}

private static boolean upload(PodOperationsImpl operation, String command, UploadProcessor processor) throws IOException {
operation = operation.redirectingInput().terminateOnError();
String containerId = operation.getContext().getContainerId();
if (Utils.isNotNullOrEmpty(containerId)) {
operation = operation.inContainer(containerId);
}
CompletableFuture<Integer> exitFuture;
try (ExecWatch execWatch = operation.exec("sh", "-c", command)) {
OutputStream out = execWatch.getInput();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ void setUp() {
}

@Test
void testWithForgedTar(@TempDir Path targetDirParent) throws Exception {
void testWithForgedTar(@TempDir Path targetDirParent) {
// Given
final Path targetDir = targetDirParent.resolve("target");
final PodOperationsImpl poi = spy(new PodOperationsImpl(baseContext.withDir("/var/source-dir"), new OperationContext()));
doReturn(PodOperationsImpl_CVE2021_20218_Test.class.getResourceAsStream("/2021_20218/tar-with-parent-traversal.tar"))
.when(poi).readTar("/var/source-dir");
.when(poi).readTar("/var/source-dir");
// When
final KubernetesClientException exception = assertThrows(KubernetesClientException.class, () -> poi.copy(targetDir));
// Then
assertThat(exception).getCause()
.hasMessage("Tar entry '../youve-been-hacked' has an invalid name");
.hasMessage("Tar entry '../youve-been-hacked' has an invalid name");
assertThat(targetDirParent).isDirectoryNotContaining("glob:**/youve-been-hacked");
}

Expand All @@ -59,13 +59,13 @@ void testWithValidTar(@TempDir Path targetDirParent) throws Exception {
final Path targetDir = targetDirParent.resolve("target");
final PodOperationsImpl poi = spy(new PodOperationsImpl(baseContext.withDir("/var/source-dir"), new OperationContext()));
doReturn(PodOperationsImpl_CVE2021_20218_Test.class.getResourceAsStream("/2021_20218/valid.tar"))
.when(poi).readTar("/var/source-dir");
.when(poi).readTar("/var/source-dir");
// When
final boolean result = poi.copy(targetDir);
// Then
assertThat(result).isTrue();
assertThat(targetDir)
.isDirectoryContaining("glob:**/hello.txt")
.isDirectoryRecursivelyContaining("glob:**/very/nested/dir/answer.txt");
.isDirectoryContaining("glob:**/hello.txt")
.isDirectoryRecursivelyContaining("glob:**/very/nested/dir/answer.txt");
}
}
Loading