From 44d1e246c7536c3a7a46554d75aabea97706c6e5 Mon Sep 17 00:00:00 2001 From: andweng Date: Sat, 21 Nov 2026 22:29:23 +0000 Subject: [PATCH 1/2] Kubernetes: add proxy_jump.image The jump pod always ran testcontainers/sshd:1.3.0. proxy_jump.image sets another image, e.g., one built on an approved base, from an internal registry, or with a mandated SSH crypto policy. It defaults to the current image and, like the other proxy_jump fields, is excluded from requests when unset so new clients keep working with older servers. Closes #4508 --- mkdocs/docs/concepts/backends.md | 16 +++++++++++- .../core/backends/kubernetes/compute.py | 6 +++-- .../core/backends/kubernetes/models.py | 13 ++++++++++ .../_internal/core/compatibility/backends.py | 2 ++ .../core/backends/kubernetes/test_compute.py | 25 +++++++++++++++++-- .../core/compatibility/test_backends.py | 12 +++++++++ 6 files changed, 69 insertions(+), 5 deletions(-) diff --git a/mkdocs/docs/concepts/backends.md b/mkdocs/docs/concepts/backends.md index df1d4820b..c22bb2b2b 100644 --- a/mkdocs/docs/concepts/backends.md +++ b/mkdocs/docs/concepts/backends.md @@ -1296,13 +1296,27 @@ projects: Each `tolerations` item is `key[=value][:effect]`, the `kubectl taint` format, so a taint added with `kubectl taint` can be copied as is. Without `=value`, any value is tolerated; without `:effect`, any effect. If `tolerations` isn't set, `dstack` tolerates the GPU node taints when every node is tainted, but not if `node_selector` is set. - !!! warning "Changing `cpu`, `memory`, `node_selector`, and `tolerations`" + By default, the jump pod runs `testcontainers/sshd`. To run your own image instead, e.g., one built on your organization's base image, scanned by your registry, or with your SSH policy, set `proxy_jump.image`: + + ```yaml + contexts: + - name: gpu-cluster-a + proxy_jump: + image: registry.example.com/sshd:1.0@sha256:... + ``` + + The image must run OpenSSH `sshd` at `/usr/sbin/sshd` as root and provide `/bin/sh` and `ssh-keygen`: `dstack` writes the authorized keys, regenerates the host keys with `ssh-keygen -A`, and starts `sshd`. Pin the image by digest. + + !!! warning "Changing `image`, `cpu`, `memory`, `node_selector`, and `tolerations`" New values don't apply to an existing jump pod. To apply them, update the jump pod's ReplicaSet in the context's namespace and delete the pod so that Kubernetes recreates it: ```shell # cpu and memory kubectl -n set resources replicaset dstack--ssh-jump-pod \ --requests=cpu=1,memory=2Gi --limits=cpu=1,memory=2Gi + # image + kubectl -n set image replicaset dstack--ssh-jump-pod \ + dstack--ssh-jump-pod-container=registry.example.com/sshd:1.0@sha256:... # node_selector and tolerations: edit spec.template.spec.affinity and .tolerations kubectl -n edit replicaset dstack--ssh-jump-pod # Recreate the pod diff --git a/src/dstack/_internal/core/backends/kubernetes/compute.py b/src/dstack/_internal/core/backends/kubernetes/compute.py index a0105291d..d9d125505 100644 --- a/src/dstack/_internal/core/backends/kubernetes/compute.py +++ b/src/dstack/_internal/core/backends/kubernetes/compute.py @@ -46,6 +46,7 @@ from dstack._internal.core.backends.kubernetes.features import resource_groups from dstack._internal.core.backends.kubernetes.models import ( JUMP_POD_DEFAULT_CPU, + JUMP_POD_DEFAULT_IMAGE, JUMP_POD_DEFAULT_MEMORY, KubernetesConfig, ) @@ -137,7 +138,6 @@ logger = get_logger(__name__) -JUMP_POD_IMAGE = "testcontainers/sshd:1.3.0@sha256:c50c0f59554dcdb2d9e5e705112144428ae9d04ac0af6322b365a18e24213a6a" JUMP_POD_SSH_PORT = 22 JUMP_POD_USER = "root" # Under disk pressure, the kubelet first evicts pods whose disk usage exceeds their @@ -271,6 +271,7 @@ def run_job( jump_pod_service_name=jump_pod_service_name, jump_pod_port=cluster.proxy_jump.port, authorized_keys=project_authorized_keys, + image=cluster.proxy_jump.image or JUMP_POD_DEFAULT_IMAGE, cpu_request_limit=cluster.proxy_jump.cpu or JUMP_POD_DEFAULT_CPU, memory_request_limit=cluster.proxy_jump.memory or JUMP_POD_DEFAULT_MEMORY, node_selector=cluster.proxy_jump.node_selector, @@ -949,6 +950,7 @@ def _create_jump_pod_service_if_not_exists( jump_pod_service_name: str, jump_pod_port: Optional[int], authorized_keys: list[str], + image: str, cpu_request_limit: str, memory_request_limit: str, node_selector: Optional[list[str]], @@ -1064,7 +1066,7 @@ def _create_jump_pod_service_if_not_exists( containers=[ client.V1Container( name=f"{jump_pod_name}-container", - image=JUMP_POD_IMAGE, + image=image, command=["/bin/sh"], args=["-c", " && ".join(commands)], ports=[ diff --git a/src/dstack/_internal/core/backends/kubernetes/models.py b/src/dstack/_internal/core/backends/kubernetes/models.py index 15603c24e..8783d8675 100644 --- a/src/dstack/_internal/core/backends/kubernetes/models.py +++ b/src/dstack/_internal/core/backends/kubernetes/models.py @@ -8,6 +8,9 @@ # Measured with the jump pod image (OpenSSH 9.9). The container takes ~9 MiB plus ~1.6 MiB per # tunneled SSH session (two sshd-session processes), so 1Gi fits ~600 sessions. Each running job # holds one or more sessions per server replica. At 500m, it tunnels ~130-180 MiB/s. +# The image must provide `/bin/sh`, `ssh-keygen`, and OpenSSH `sshd` at `/usr/sbin/sshd`, run as +# root, and generate host keys with `ssh-keygen -A` (see `_get_jump_pod_commands()`). +JUMP_POD_DEFAULT_IMAGE = "testcontainers/sshd:1.3.0@sha256:c50c0f59554dcdb2d9e5e705112144428ae9d04ac0af6322b365a18e24213a6a" JUMP_POD_DEFAULT_CPU = "500m" JUMP_POD_DEFAULT_MEMORY = "1Gi" @@ -19,6 +22,16 @@ class KubernetesProxyJumpConfig(CoreModel): port: Annotated[ Optional[int], Field(description="Any port accessible outside of the cluster") ] = None + image: Annotated[ + Optional[str], + Field( + description=( + "The jump pod's image. It must run OpenSSH `sshd` at `/usr/sbin/sshd` as root" + " and provide `/bin/sh` and `ssh-keygen`." + f" Defaults to `{JUMP_POD_DEFAULT_IMAGE}`" + ) + ), + ] = None cpu: Annotated[ Optional[str], Field( diff --git a/src/dstack/_internal/core/compatibility/backends.py b/src/dstack/_internal/core/compatibility/backends.py index 72e58d8e5..9d7eb6302 100644 --- a/src/dstack/_internal/core/compatibility/backends.py +++ b/src/dstack/_internal/core/compatibility/backends.py @@ -39,6 +39,8 @@ def _get_kubernetes_proxy_jump_excludes( ) -> IncludeExcludeStrDictType: # A field is excluded only if it's unset in all `proxy_jumps` excludes: IncludeExcludeStrDictType = {} + if all(proxy_jump.image is None for proxy_jump in proxy_jumps): + excludes["image"] = True if all(proxy_jump.cpu is None for proxy_jump in proxy_jumps): excludes["cpu"] = True if all(proxy_jump.memory is None for proxy_jump in proxy_jumps): diff --git a/src/tests/_internal/core/backends/kubernetes/test_compute.py b/src/tests/_internal/core/backends/kubernetes/test_compute.py index 071eeff95..7973803a7 100644 --- a/src/tests/_internal/core/backends/kubernetes/test_compute.py +++ b/src/tests/_internal/core/backends/kubernetes/test_compute.py @@ -18,7 +18,11 @@ _get_pod_spec_parameters_for_gpu, _KubernetesSkipOfferCache, ) -from dstack._internal.core.backends.kubernetes.models import KubeconfigConfig, KubernetesConfig +from dstack._internal.core.backends.kubernetes.models import ( + JUMP_POD_DEFAULT_IMAGE, + KubeconfigConfig, + KubernetesConfig, +) from dstack._internal.core.backends.kubernetes.resources import ( KubernetesOfferBackendData, build_base_labels, @@ -231,6 +235,7 @@ def call( api: Mock, apps_api: Mock, jump_pod_port: Optional[int] = None, + image: str = JUMP_POD_DEFAULT_IMAGE, cpu: str = "500m", memory: str = "1Gi", node_selector: Optional[list[str]] = None, @@ -245,6 +250,7 @@ def call( jump_pod_service_name=JUMP_POD_SERVICE_NAME, jump_pod_port=jump_pod_port, authorized_keys=["ssh-ed25519 AAAA project"], + image=image, cpu_request_limit=cpu, memory_request_limit=memory, node_selector=node_selector, @@ -257,7 +263,12 @@ def get_pod_spec(self, apps_api: Mock) -> client.V1PodSpec: return replica_set.spec.template.spec def assert_replica_set_created( - self, apps_api: Mock, *, cpu: str = "500m", memory: str = "1Gi" + self, + apps_api: Mock, + *, + image: str = JUMP_POD_DEFAULT_IMAGE, + cpu: str = "500m", + memory: str = "1Gi", ) -> None: apps_api.create_namespaced_replica_set.assert_called_once() replica_set = apps_api.create_namespaced_replica_set.call_args.kwargs["body"] @@ -265,6 +276,7 @@ def assert_replica_set_created( assert replica_set.spec.replicas == 1 assert replica_set.spec.selector.match_labels == JUMP_POD_SELECTOR assert replica_set.spec.template.metadata.labels == JUMP_POD_LABELS + assert replica_set.spec.template.spec.containers[0].image == image resources = replica_set.spec.template.spec.containers[0].resources # Equal CPU and memory requests and limits for the Guaranteed QoS class, and # an ephemeral-storage request without a limit @@ -303,6 +315,15 @@ def test_creates_replica_set_and_service_if_not_found(self): self.assert_replica_set_created(apps_api) self.assert_service_created(api, selector=JUMP_POD_SELECTOR, node_port=None) + def test_sets_jump_pod_image(self): + api, apps_api = self.make_apis() + + self.call(api, apps_api, image="registry.example.com/sshd:1@sha256:" + "0" * 64) + + self.assert_replica_set_created( + apps_api, image="registry.example.com/sshd:1@sha256:" + "0" * 64 + ) + def test_sets_jump_pod_resources(self): api, apps_api = self.make_apis() diff --git a/src/tests/_internal/core/compatibility/test_backends.py b/src/tests/_internal/core/compatibility/test_backends.py index 5ce7038ee..b33614336 100644 --- a/src/tests/_internal/core/compatibility/test_backends.py +++ b/src/tests/_internal/core/compatibility/test_backends.py @@ -65,6 +65,18 @@ def test_keeps_set_kubernetes_proxy_jump_resources(self): assert _request_body(config)["proxy_jump"] == {"hostname": None, "port": None, "cpu": "1"} + def test_keeps_set_kubernetes_proxy_jump_image(self): + config = KubernetesBackendConfigWithCreds( + kubeconfig=KubeconfigConfig(data="mocked"), + proxy_jump=KubernetesProxyJumpConfig(image="registry.example.com/sshd:1"), + ) + + assert _request_body(config)["proxy_jump"] == { + "hostname": None, + "port": None, + "image": "registry.example.com/sshd:1", + } + def test_keeps_set_kubernetes_proxy_jump_placement(self): config = KubernetesBackendConfigWithCreds( kubeconfig=KubeconfigConfig(data="mocked"), From fdf0ff70cd2e7d05d7f4cf1435de28a81cfebc82 Mon Sep 17 00:00:00 2001 From: Dmitry Meyer Date: Fri, 27 Nov 2026 11:27:37 +0000 Subject: [PATCH 2/2] Relax jump pod image requirements, validate image Run the jump pod container as root and write the keys to ~root, so the image's USER and HOME don't matter, and force PermitRootLogin, so a hardened sshd_config doesn't lock the server out. Validate proxy_jump.image against the distribution/reference grammar, so an invalid reference fails the backend config instead of runs hitting the provisioning timeout. Document the full image requirements and how a private image is pulled. Assisted-by: Claude Opus 5.5 --- mkdocs/docs/concepts/backends.md | 10 ++- .../core/backends/kubernetes/compute.py | 17 +++-- .../core/backends/kubernetes/configurator.py | 14 +++- .../core/backends/kubernetes/models.py | 12 ++-- src/dstack/_internal/utils/docker.py | 45 ++++++++++++ .../core/backends/kubernetes/test_compute.py | 16 +++-- .../backends/kubernetes/test_configurator.py | 68 +++++++++++++++++++ src/tests/_internal/utils/test_docker.py | 51 +++++++++++++- 8 files changed, 210 insertions(+), 23 deletions(-) diff --git a/mkdocs/docs/concepts/backends.md b/mkdocs/docs/concepts/backends.md index c22bb2b2b..ca2c6b8ef 100644 --- a/mkdocs/docs/concepts/backends.md +++ b/mkdocs/docs/concepts/backends.md @@ -1276,7 +1276,7 @@ projects: memory: 2Gi ``` - Each SSH session through the jump pod takes about 2 MiB of memory. Each `dstack` server replica keeps at least one session open per running job, and each `dstack attach` adds one more. If the jump pod exceeds its memory limit, Kubernetes restarts it. + With the default image, each SSH session through the jump pod takes about 2 MiB of memory. Each `dstack` server replica keeps at least one session open per running job, and each `dstack attach` adds one more. If the jump pod exceeds its memory limit, Kubernetes restarts it. When the jump pod restarts or is recreated, its SSH sessions drop. The `dstack` server reconnects automatically, but `dstack attach` may fail for runs submitted before that. If reliable SSH access to runs is important, deploy [`dstack-sshproxy`](../guides/server-deployment.md#ssh-proxy). @@ -1305,7 +1305,13 @@ projects: image: registry.example.com/sshd:1.0@sha256:... ``` - The image must run OpenSSH `sshd` at `/usr/sbin/sshd` as root and provide `/bin/sh` and `ssh-keygen`: `dstack` writes the authorized keys, regenerates the host keys with `ssh-keygen -A`, and starts `sshd`. Pin the image by digest. + `dstack` runs the jump pod's container as root, writes root's authorized keys, regenerates the host keys with `ssh-keygen -A`, and starts `sshd` with `PermitRootLogin`, `PasswordAuthentication`, and `AllowTcpForwarding` overridden. The server then connects as root and runs a shell script that adds users' keys. Other `sshd_config` settings, e.g., ciphers and MACs, apply as set in the image. The image must provide: + + - a `root` user with a POSIX login shell, e.g., `sh` or `bash` + - OpenSSH `sshd` at `/usr/sbin/sshd` + - `/bin/sh`, `ssh-keygen`, `mkdir`, `chmod`, `rm`, `touch`, `tail`, and `grep` + + `dstack` doesn't pass registry credentials for the jump pod's image, so a private image can be pulled only if the nodes have credentials for the registry or the namespace's `default` service account has `imagePullSecrets`. !!! warning "Changing `image`, `cpu`, `memory`, `node_selector`, and `tolerations`" New values don't apply to an existing jump pod. To apply them, update the jump pod's ReplicaSet in the context's namespace and delete the pod so that Kubernetes recreates it: diff --git a/src/dstack/_internal/core/backends/kubernetes/compute.py b/src/dstack/_internal/core/backends/kubernetes/compute.py index d9d125505..a9c947e12 100644 --- a/src/dstack/_internal/core/backends/kubernetes/compute.py +++ b/src/dstack/_internal/core/backends/kubernetes/compute.py @@ -1078,6 +1078,11 @@ def _create_jump_pod_service_if_not_exists( requests=requests, limits=limits, ), + # sshd must run as root, whatever the image's USER is + security_context=client.V1SecurityContext( + run_as_user=0, + run_as_group=0, + ), ) ], restart_policy=RestartPolicy.ALWAYS, @@ -1329,10 +1334,12 @@ def _get_jump_pod_tolerations_from_node_taints( def _get_jump_pod_commands(authorized_keys: list[str]) -> list[str]: authorized_keys_content = "\n".join(authorized_keys) commands = [ - "mkdir -p ~/.ssh", - "chmod 700 ~/.ssh", - f"echo {shlex.quote(authorized_keys_content)} > ~/.ssh/authorized_keys", - "chmod 600 ~/.ssh/authorized_keys", + # Not ~, which follows HOME, and the image may set HOME for its own user. sshd looks up + # authorized_keys in root's home directory from the user database, as ~root does + "mkdir -p ~root/.ssh", + "chmod 700 ~root/.ssh", + f"echo {shlex.quote(authorized_keys_content)} > ~root/.ssh/authorized_keys", + "chmod 600 ~root/.ssh/authorized_keys", # regenerate host keys "rm -rf /etc/ssh/ssh_host_*", "ssh-keygen -A > /dev/null", @@ -1340,6 +1347,8 @@ def _get_jump_pod_commands(authorized_keys: list[str]) -> list[str]: ( f"/usr/sbin/sshd -D -e -p {JUMP_POD_SSH_PORT}" " -o LogLevel=ERROR" + # The image's sshd_config may forbid root login, and clients log in as root + " -o PermitRootLogin=prohibit-password" " -o PasswordAuthentication=no" " -o AllowTcpForwarding=local" ), diff --git a/src/dstack/_internal/core/backends/kubernetes/configurator.py b/src/dstack/_internal/core/backends/kubernetes/configurator.py index 55e75f8ff..3a0b25dd0 100644 --- a/src/dstack/_internal/core/backends/kubernetes/configurator.py +++ b/src/dstack/_internal/core/backends/kubernetes/configurator.py @@ -26,13 +26,14 @@ from dstack._internal.core.errors import ServerClientError from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.common import validate_extra_ignore, validate_json_extra_ignore +from dstack._internal.utils.docker import validate_image_name from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) -# Sanity floors that catch unit mistakes, e.g., `memory: 512` (bytes). Measured with the jump pod -# image: below 100m, SSH handshakes through the jump pod slow down sharply (~0.5s at 50m, ~2s at -# 10m); 32Mi fits the container (~9Mi) and a few sessions (~1.6Mi each). +# Sanity floors that catch unit mistakes, e.g., `memory: 512` (bytes). Measured with the default +# jump pod image: below 100m, SSH handshakes through the jump pod slow down sharply (~0.5s at 50m, +# ~2s at 10m); 32Mi fits the container (~9Mi) and a few sessions (~1.6Mi each). _JUMP_POD_MIN_CPU = "100m" _JUMP_POD_MIN_MEMORY = "32Mi" @@ -118,6 +119,13 @@ def _check_proxy_jump( self, proxy_jump: KubernetesProxyJumpConfig, *, context_name: Optional[str] = None ): in_context = f" in context {context_name!r}" if context_name is not None else "" + if proxy_jump.image is not None: + try: + validate_image_name(proxy_jump.image) + except ValueError as e: + raise ServerClientError( + f"invalid proxy_jump.image value {proxy_jump.image!r}{in_context}: {e}" + ) for field, quantity, min_quantity in [ ("cpu", proxy_jump.cpu, _JUMP_POD_MIN_CPU), ("memory", proxy_jump.memory, _JUMP_POD_MIN_MEMORY), diff --git a/src/dstack/_internal/core/backends/kubernetes/models.py b/src/dstack/_internal/core/backends/kubernetes/models.py index 8783d8675..5a73e524b 100644 --- a/src/dstack/_internal/core/backends/kubernetes/models.py +++ b/src/dstack/_internal/core/backends/kubernetes/models.py @@ -5,12 +5,11 @@ from dstack._internal.core.backends.base.models import fill_data from dstack._internal.core.models.common import CoreModel -# Measured with the jump pod image (OpenSSH 9.9). The container takes ~9 MiB plus ~1.6 MiB per -# tunneled SSH session (two sshd-session processes), so 1Gi fits ~600 sessions. Each running job -# holds one or more sessions per server replica. At 500m, it tunnels ~130-180 MiB/s. -# The image must provide `/bin/sh`, `ssh-keygen`, and OpenSSH `sshd` at `/usr/sbin/sshd`, run as -# root, and generate host keys with `ssh-keygen -A` (see `_get_jump_pod_commands()`). JUMP_POD_DEFAULT_IMAGE = "testcontainers/sshd:1.3.0@sha256:c50c0f59554dcdb2d9e5e705112144428ae9d04ac0af6322b365a18e24213a6a" + +# Measured with the default jump pod image (OpenSSH 9.9). The container takes ~9 MiB plus ~1.6 MiB +# per tunneled SSH session (two sshd-session processes), so 1Gi fits ~600 sessions. Each running +# job holds one or more sessions per server replica. At 500m, it tunnels ~130-180 MiB/s. JUMP_POD_DEFAULT_CPU = "500m" JUMP_POD_DEFAULT_MEMORY = "1Gi" @@ -26,8 +25,7 @@ class KubernetesProxyJumpConfig(CoreModel): Optional[str], Field( description=( - "The jump pod's image. It must run OpenSSH `sshd` at `/usr/sbin/sshd` as root" - " and provide `/bin/sh` and `ssh-keygen`." + "The jump pod's image, with OpenSSH `sshd`." f" Defaults to `{JUMP_POD_DEFAULT_IMAGE}`" ) ), diff --git a/src/dstack/_internal/utils/docker.py b/src/dstack/_internal/utils/docker.py index 780f37e86..a47eabec8 100644 --- a/src/dstack/_internal/utils/docker.py +++ b/src/dstack/_internal/utils/docker.py @@ -1,3 +1,4 @@ +import re from dataclasses import dataclass from typing import Optional @@ -41,5 +42,49 @@ def is_default_registry(registry: str) -> bool: return registry in [DEFAULT_REGISTRY, LEGACY_DEFAULT_REGISTRY] +def validate_image_name(image: str) -> None: + """ + Validates an image reference, e.g., `ubuntu`, `ghcr.io/org/repo:tag`, `repo@sha256:...`, + as the kubelet and container runtimes parse it. + + Raises: + ValueError: The reference is invalid. + """ + match = _REFERENCE_REGEX.fullmatch(image) + if match is None: + raise ValueError("Invalid reference format") + digest = match.group("digest") + if digest is None: + return + algorithm, encoded = digest.split(":", maxsplit=1) + length = _DIGEST_ENCODED_LENGTHS.get(algorithm) + if length is None: + raise ValueError(f"Unsupported digest algorithm: {algorithm}") + if re.fullmatch(rf"[a-f0-9]{{{length}}}", encoded) is None: + raise ValueError(f"Invalid {algorithm} digest: must be {length} lowercase hex digits") + + +# The reference grammar of +# https://github.com/distribution/reference/blob/v0.6.0/regexp.go +_ALPHANUMERIC = r"[a-z0-9]+" +_SEPARATOR = r"(?:[._]|__|[-]+)" +_PATH_COMPONENT = rf"{_ALPHANUMERIC}(?:{_SEPARATOR}{_ALPHANUMERIC})*" +_DOMAIN_NAME_COMPONENT = r"(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])" +_DOMAIN_NAME = rf"{_DOMAIN_NAME_COMPONENT}(?:\.{_DOMAIN_NAME_COMPONENT})*" +_IPV6_ADDRESS = r"\[(?:[a-fA-F0-9:]+)\]" +_DOMAIN_AND_PORT = rf"(?:{_DOMAIN_NAME}|{_IPV6_ADDRESS})(?::[0-9]+)?" +_REMOTE_NAME = rf"{_PATH_COMPONENT}(?:/{_PATH_COMPONENT})*" +_NAME = rf"(?:{_DOMAIN_AND_PORT}/)?{_REMOTE_NAME}" +_TAG = r"[\w][\w.-]{0,127}" +_DIGEST = r"[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*:[0-9a-fA-F]{32,}" +_REFERENCE_REGEX = re.compile( + rf"{_NAME}(?::{_TAG})?(?:@(?P{_DIGEST}))?", + # \w is ASCII-only in Go + re.ASCII, +) +# The algorithms that https://github.com/opencontainers/go-digest supports +_DIGEST_ENCODED_LENGTHS = {"sha256": 64, "sha384": 96, "sha512": 128} + + def _is_host(s: str) -> bool: return s == "localhost" or ":" in s or "." in s diff --git a/src/tests/_internal/core/backends/kubernetes/test_compute.py b/src/tests/_internal/core/backends/kubernetes/test_compute.py index 7973803a7..76a3ee79d 100644 --- a/src/tests/_internal/core/backends/kubernetes/test_compute.py +++ b/src/tests/_internal/core/backends/kubernetes/test_compute.py @@ -276,8 +276,12 @@ def assert_replica_set_created( assert replica_set.spec.replicas == 1 assert replica_set.spec.selector.match_labels == JUMP_POD_SELECTOR assert replica_set.spec.template.metadata.labels == JUMP_POD_LABELS - assert replica_set.spec.template.spec.containers[0].image == image - resources = replica_set.spec.template.spec.containers[0].resources + container = replica_set.spec.template.spec.containers[0] + assert container.image == image + # Root regardless of the image's USER + assert container.security_context.run_as_user == 0 + assert container.security_context.run_as_group == 0 + resources = container.resources # Equal CPU and memory requests and limits for the Guaranteed QoS class, and # an ephemeral-storage request without a limit assert resources.limits == {"cpu": cpu, "memory": memory} @@ -318,11 +322,11 @@ def test_creates_replica_set_and_service_if_not_found(self): def test_sets_jump_pod_image(self): api, apps_api = self.make_apis() - self.call(api, apps_api, image="registry.example.com/sshd:1@sha256:" + "0" * 64) + image = "registry.example.com/sshd:1@sha256:" + "0" * 64 - self.assert_replica_set_created( - apps_api, image="registry.example.com/sshd:1@sha256:" + "0" * 64 - ) + self.call(api, apps_api, image=image) + + self.assert_replica_set_created(apps_api, image=image) def test_sets_jump_pod_resources(self): api, apps_api = self.make_apis() diff --git a/src/tests/_internal/core/backends/kubernetes/test_configurator.py b/src/tests/_internal/core/backends/kubernetes/test_configurator.py index 05f9be084..b67f6e9b7 100644 --- a/src/tests/_internal/core/backends/kubernetes/test_configurator.py +++ b/src/tests/_internal/core/backends/kubernetes/test_configurator.py @@ -156,6 +156,74 @@ def test_validate_config_invalid_context_proxy_jump_resources(self): ): KubernetesConfigurator().validate_config(config, default_creds_enabled=True) + @pytest.mark.usefixtures("get_clusters_mock") + def test_validate_config_valid_proxy_jump_image(self): + config = KubernetesBackendConfigWithCreds( + kubeconfig=KubeconfigConfig(data="mocked", filename="-"), + contexts=[ + KubernetesContextConfig( + name="ctx", + proxy_jump=KubernetesProxyJumpConfig( + image="registry.example.com:5000/sshd:1.0@sha256:" + "0" * 64 + ), + ), + ], + ) + KubernetesConfigurator().validate_config(config, default_creds_enabled=True) + + @pytest.mark.usefixtures("get_clusters_mock") + @pytest.mark.parametrize( + ["proxy_jump", "expected_error"], + [ + pytest.param( + KubernetesProxyJumpConfig(image=""), + "invalid proxy_jump.image value '': Invalid reference format", + id="empty", + ), + pytest.param( + KubernetesProxyJumpConfig(image="registry.example.com/SSHD:1.0"), + "invalid proxy_jump.image value 'registry.example.com/SSHD:1.0':" + " Invalid reference format", + id="uppercase-repository", + ), + pytest.param( + KubernetesProxyJumpConfig(image="sshd@sha256:" + "0" * 63), + f"invalid proxy_jump.image value 'sshd@sha256:{'0' * 63}':" + " Invalid sha256 digest: must be 64 lowercase hex digits", + id="short-digest", + ), + ], + ) + def test_validate_config_invalid_proxy_jump_image( + self, proxy_jump: KubernetesProxyJumpConfig, expected_error: str + ): + config = KubernetesBackendConfigWithCreds( + kubeconfig=KubeconfigConfig(data="mocked", filename="-"), + proxy_jump=proxy_jump, + namespace="ns", + ) + with pytest.raises(ServerClientError, match=re.escape(expected_error)): + KubernetesConfigurator().validate_config(config, default_creds_enabled=True) + + @pytest.mark.usefixtures("get_clusters_mock") + def test_validate_config_invalid_context_proxy_jump_image(self): + config = KubernetesBackendConfigWithCreds( + kubeconfig=KubeconfigConfig(data="mocked", filename="-"), + contexts=[ + KubernetesContextConfig( + name="ctx", + proxy_jump=KubernetesProxyJumpConfig(image=" sshd"), + ), + ], + ) + with pytest.raises( + ServerClientError, + match=re.escape( + "invalid proxy_jump.image value ' sshd' in context 'ctx': Invalid reference format" + ), + ): + KubernetesConfigurator().validate_config(config, default_creds_enabled=True) + @pytest.mark.usefixtures("get_clusters_mock") def test_validate_config_valid_proxy_jump_placement(self): config = KubernetesBackendConfigWithCreds( diff --git a/src/tests/_internal/utils/test_docker.py b/src/tests/_internal/utils/test_docker.py index b2a16e4dc..8bbae609a 100644 --- a/src/tests/_internal/utils/test_docker.py +++ b/src/tests/_internal/utils/test_docker.py @@ -1,6 +1,11 @@ import pytest -from dstack._internal.utils.docker import DockerImage, _is_host, parse_image_name +from dstack._internal.utils.docker import ( + DockerImage, + _is_host, + parse_image_name, + validate_image_name, +) class TestParseImageName: @@ -45,6 +50,50 @@ def test_parse(self, image: str, expected: DockerImage) -> None: assert parse_image_name(image) == expected +class TestValidateImageName: + @pytest.mark.parametrize( + "image", + [ + "ubuntu", + "ubuntu:22.04", + "dstackai/miniforge:py3.9-0.2", + "ghcr.io/dstackai/miniforge", + "localhost:5000/sshd:latest", + "Registry.Example.com/team/sshd", + "192.168.0.1:5000/sshd", + "[::1]:5000/sshd", + "my__org/ssh-d.server_1:v1.0_RC", + "sshd@sha256:" + "0" * 64, + "registry.example.com/sshd:1.0@sha512:" + "0" * 128, + ], + ) + def test_valid(self, image: str) -> None: + validate_image_name(image) + + @pytest.mark.parametrize( + ["image", "error"], + [ + ("", "Invalid reference format"), + (" ubuntu", "Invalid reference format"), + ("Ubuntu", "Invalid reference format"), + ("ghcr.io/dstackai/Miniforge", "Invalid reference format"), + ("ubuntu:", "Invalid reference format"), + ("ubuntu:.22.04", "Invalid reference format"), + ("ubuntu:" + "1" * 129, "Invalid reference format"), + ("-ubuntu", "Invalid reference format"), + ("ubuntu//sshd", "Invalid reference format"), + ("ubuntu@sha256", "Invalid reference format"), + ("ubuntu@sha256:" + "0" * 31, "Invalid reference format"), + ("ubuntu@md5:" + "0" * 32, "Unsupported digest algorithm: md5"), + ("ubuntu@sha256:" + "0" * 63, "Invalid sha256 digest"), + ("ubuntu@sha256:" + "A" * 64, "Invalid sha256 digest"), + ], + ) + def test_invalid(self, image: str, error: str) -> None: + with pytest.raises(ValueError, match=error): + validate_image_name(image) + + class TestIsHost: @pytest.mark.parametrize( ["value", "expected"],