Skip to content

fix(docker): the Docker endpoint check covers the endpoint the SDK dials, including contexts and the TUI, and pushes accept registry ports #1108

Closed

Description

@dan-petty

Problem

Lines cited at dcafadf. Paths are under src/devops_cli/ unless they start with tests/. These paths are inside the locked docker-py 7.2.0 (pyproject.toml:24, uv.lock:797), not devops-cli: docker/__init__.py, docker/auth.py, docker/client.py, docker/api/…, docker/context/…, docker/transport/… and docker/utils/….

Before the Docker SDK dials a TCP daemon, DockerEngineService.resolve_host (docker/engine.py:229-246) runs the egress check (validate_service_url). It reads DOCKER_HOST itself and decides with a hand-written scheme test, so it checks a different endpoint than the one docker.from_env() then dials. Offline probes (no network namespace, an isolated DOCKER_CONFIG, private networks disallowed) confirmed each point below.

Hand-rolled code:

  • A case-sensitive startswith against the tuple ("tcp://", "http://", "https://") (docker/engine.py:234, config/constants.py:2015-2018).
  • A string rewrite, docker_host.replace("tcp://", "http://", 1) (docker/engine.py:245).
  • A push-name regex, ^[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_.-]+)*(?::[a-zA-Z0-9_.-]+)?$ (commands/docker.py:161-163).
  • The comment at constants.py:2015-2017 calls the tuple a "closed, exhaustive set" defined by dockerd -H. It is neither. docker-py also accepts uppercase schemes, ssh://, http+unix://, and a bare host:port whose host is not made only of letters.

Confirmed defects:

  • Spellings that skip the check. docker-py's own parser, docker.utils.parse_host, reads the scheme case-insensitively. It reads a bare host:port as tcp unless the host is letters only: 192.0.2.1:2375, [::1]:2375 and example.com:2375 become http://…, while localhost:2375 raises DockerException: Invalid bind address protocol. APIClient runs parse_host on every endpoint (docker/api/client.py:146-148). These are dialled with no check: TCP://, Tcp://, HTTP://, HTTPS://, a bare 192.0.2.1:2375 and [::1]:2375. Lowercase tcp://192.0.2.1:2375 is refused.
  • Docker contexts are never checked. With DOCKER_HOST unset, from_env() in docker 7.2.0 falls back to the Docker CLI context: DOCKER_CONTEXT, or currentContext in config.json (docker/client.py:84-87, :104-108). resolve_host ignores the context and returns the default unix socket. A context with endpoint tcp://192.0.2.10:2376, selected either way, was dialled with no check. docker 7.2.0 has been pinned since v0.2.4, so this gap has existed since the check was added in v0.2.22.
    • For a context name that does not exist, ContextAPI.kwargs_from_context returns {} (docker/context/api.py:150-152), so from_env silently dials the default socket. The Docker CLI refuses the same setting (context "nope": context not found), whether the name comes from DOCKER_CONTEXT or from currentContext (measured).
  • The TUI skips the check. _get_docker_client (ui/data_providers.py:217-221), used by fetch_docker_status (:400), calls docker.from_env() directly.
  • A refusal ends in a traceback. resolve_host runs outside the try (docker/engine.py:253), and _engine() (commands/docker.py:53-60) catches only DockerError. So the SSRFBlockedError for tcp://192.0.2.1:2375 ends devops docker images in a full Rich traceback. validate_service_url can also raise InvalidURLError (core/validation.py:286-295), and parse_host raises DockerException, or ValueError for a bad port. Each would escape the same way.
  • The push regex is wrong both ways.
    • It rejects valid names with a registry port: localhost:5000/app:1.0, example.com:443/a/b:c and [::1]:5000/app:1.
    • It accepts invalid names: UPPER/Case and -lead/app.
    • The progress line MESSAGES.docker.pushing_image is Rich markup (Pushing [dim]{image}[/dim]...), and the name is not escaped (commands/docker.py:165). Without the regex, app:1[/x] raises MarkupError.
  • The knowledge base teaches the bypass. ai/knowledge_base/devops_cli/libraries/docker.md:37-42, :61 (the metrics example) and :94 tell agents to create clients with docker.from_env().

Replacement: docker-py's own exported functions, in the order from_env uses them, split into steps that later endpoint sources can reuse:

  • Gather the endpoint from one ordered list of sources. The first source that gives an endpoint wins. Each source is one entry in the list, so a source can be added later without touching the normalise, check or build steps:

    1. DOCKER_HOST: the base_url from docker.utils.kwargs_from_env();
    2. DOCKER_CONTEXT: the context from docker.ContextAPI.get_context(name);
    3. currentContext in config.json, when it is not default: ContextAPI.get_current_context();
    4. the default context, ContextAPI.DEFAULT_CONTEXT (docker/context/api.py:20), whose host is unix:///var/run/docker.sock.

    This is the order from_env and kwargs_from_context follow (docker/client.py:104-108, docker/context/api.py:136-160), written as a list instead of one kwargs_from_env call plus a setdefault merge of kwargs_from_context.

    • The tls that kwargs_from_env builds from DOCKER_TLS_VERIFY and DOCKER_CERT_PATH applies whichever source wins. Without it, a context's TLSConfig applies. This is what from_env's setdefault merge does today.
    • A context name that does not exist (get_context returns None), from DOCKER_CONTEXT or from currentContext, is an error that names the context, as in the Docker CLI. No later source is tried. kwargs_from_context cannot be used for this, because it returns {} for a missing context.
  • Normalise it with the SDK's parser. base_url = docker.utils.parse_host(raw, docker.constants.IS_WINDOWS_PLATFORM, tls=bool(params.get("tls"))). This is the call APIClient makes.

  • Choose what to check with an allowlist. If urllib.parse.urlsplit(base_url).scheme in ("http", "https"), call validate_service_url(base_url, "Docker Host", allow=settings.ai.allow_private_network), as docker/engine.py:246 does today.

    • http+unix and npipe are local.
    • ssh is left out on purpose (key questions).
    • A denylist would send ssh:// into validate_service_url, which refuses every scheme except http and https (core/validation.py:286-291).
  • One public resolve step that does not connect. resolve_host() keeps its name and stays public. It gathers, normalises and checks, builds no client and opens no socket. It returns a frozen DockerEndpoint model (models/docker.py) with:

    • source: where the endpoint came from, which is DOCKER_HOST, the context's name, or the socket path for the default context;
    • raw: the endpoint as its source gave it (Go clients such as dive take this form, not http+unix://);
    • base_url: the parse_host URL that was checked;
    • params: the docker-py keyword arguments the client is built from: base_url set to the checked URL, and tls.

    Callers that need the endpoint without a client (a sandbox socket guard, a child process's DOCKER_HOST, error lines) reuse this step.

  • Say it is a pre-flight check. docker-py dials through requests and urllib3, not httpx2, so this check runs before the dial and cannot see the dialled address. resolve_host's docstring says so and names the gap: for an endpoint given by name, the address can change between the check's DNS lookup and the dial.

  • Dial what was checked. client() calls resolve_host() and builds docker.DockerClient(timeout=int(DEFAULT_DOCKER_TIMEOUT_SECONDS), **endpoint.params) instead of docker.from_env(...). If a later docker-py adds an endpoint source to from_env, this client does not use it, so the change fails closed. use_ssh_client stays unset.

  • One error type.

    • Gathering, parsing and the check move inside the try.
    • DockerException and ValueError from docker-py, SSRFBlockedError or InvalidURLError from validate_service_url, and a missing context all become DockerDaemonUnavailableError. Its message gives the source name and the reason, so _engine() prints one line.
    • _engine() prints it with print_error(..., prefix=False, safe=True). The reason now quotes text the user supplied: parse_host messages and the refusal both echo the endpoint. Measured: parse_host("abc://x/[/x]") raises DockerException: Invalid bind address protocol: abc://x/[/x], and Rich rejects that line with MarkupError unless it is escaped. ERRORS.docker.cannot_connect holds no markup, so safe=True loses nothing.
  • TUI. fetch_docker_status takes get_engine().client(), and _get_docker_client is deleted (no pass-through wrapper).

  • Push.

    • Delete the regex and let docker-py and the daemon judge the reference.
    • Around images.push:
      • docker.errors.InvalidRepository, which docker-py's resolve_repository_name raises before any request (docker/auth.py:15-27), and an APIError whose status_code is HTTPStatus.BAD_REQUEST print ERRORS.docker.invalid_image_name and the reason (the exception text, or the daemon's explanation);
      • any other APIError prints the daemon's explanation as text (safe=True);
      • both exit 1.
    • The name goes through escape_text (already imported, commands/docker.py:27) in the progress line, and the invalid-name message is printed with safe=True.
    • Do not add parse_repository_tag or resolve_repository_name calls. images.push already runs both (docker/api/image.py:474-476), and neither rejects Invalid Name! or app:1[/x].
  • Delete the constants at constants.py:2011-2018, with the false comment:

    • CONST_DOCKER_UNIX_SOCKET_PATH (already unused);
    • CONST_DOCKER_UNIX_SOCKET_URL;
    • CONST_DOCKER_HOST_ENV_VAR;
    • CONST_DOCKER_NETWORK_HOST_SCHEMES.
  • Knowledge base. docker.md (:37-42, :61 and :94) says that devops-cli code gets its client from get_engine().client(), which checks the endpoint, and its examples use that call.

Out of scope:

  • security/checkov.py:72-84 (_floats_on_latest). Rebuilding it on parse_repository_tag removes no construct: it still needs the $VAR substitution and the last-component split. Moving this check to hadolint's DL3006 and DL3007 rules (not yet filed) would delete the function instead.
  • commands/docker.py:87 (tag.rpartition(":")). It is correct for its input: Image.tags comes from the Engine's RepoTags, which are always name:tag. Switching to parse_repository_tag is optional.
  • Podman's endpoint variables and sockets. feat(docker): container commands find a Podman engine before Docker's default socket, and rootless sandboxes run as the host user #1117 adds them as sources in this item's list.

Acceptance criteria

  • One shared fixture for the endpoint environment. tests/conftest.py gains one fixture, used by every test below that resolves an endpoint (engine, CLI and TUI). It sets up:

    • DOCKER_HOST, DOCKER_CONTEXT, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH and DEVOPS_CLI_AI_ALLOW_PRIVATE_NETWORK unset (tests/conftest.py:408 sets the last one to true), and ai.allow_private_network: false;
    • DOCKER_CONFIG and HOME both pointed at tmp_path, with a config.json holding {} written there. docker-py looks for contexts in a contexts directory next to whichever config.json it finds (get_context_dir(), docker/context/config.py:53-54). It searches $DOCKER_CONFIG/config.json, then ~/.docker/config.json (docker/utils/config.py:13-19). With no config.json at all it looks in ./contexts under the current directory. Measured: with DOCKER_CONTEXT set and no config.json, ContextAPI.kwargs_from_context() returns {}; writing {} to config.json makes it return the tcp endpoint;
    • a helper that writes a context (contexts/meta/<sha256 of name>/meta.json) next to that config.json.

    A later item extends this one fixture with its own variables and socket paths, so the rows below keep their results on any host.

  • Endpoint table, parametrised and offline. Only TEST-NET and loopback literals are used, and docker.DockerClient is patched, except in the ssh:// row. Expected results, with each value set as DOCKER_HOST:

    • TCP://192.0.2.1:2376, Tcp://192.0.2.1:2376, HTTP://192.0.2.1:2375, HTTPS://192.0.2.1:2376, a bare 192.0.2.1:2375 and [::1]:2375 are refused, and no client is built. Today all six are dialled without a check.
    • tcp://192.0.2.1:2375 is still refused. With private networks allowed, it reaches DockerClient as http://192.0.2.1:2375, the URL that was checked.
    • unix:///run/user/1000/docker.sock and the unset default reach DockerClient without a check.
    • ssh://u@192.0.2.1 is not checked. With the real DockerClient, it raises DockerDaemonUnavailableError before any I/O, because paramiko is not installed.
    • fd://3, localhost:2375, tcp://192.0.2.1 (no port), tcp://192.0.2.1:99999 and tcp://192.0.2.1:abc raise DockerDaemonUnavailableError.
    • For every row that is not refused, resolve_host() builds no client and returns the source name (DOCKER_HOST, or /var/run/docker.sock for the unset default), the endpoint as given and the parse_host URL.
  • Contexts. A context with endpoint tcp://192.0.2.10:2376 is written with the fixture's helper.

    • Selected by currentContext in config.json, and separately by DOCKER_CONTEXT with config.json holding {}, it is refused before any client is built, and the error names the context.
    • With private networks allowed, it reaches DockerClient as http://192.0.2.10:2376. With DOCKER_TLS_VERIFY=1 and DOCKER_CERT_PATH at a directory under tmp_path holding empty ca.pem, cert.pem and key.pem, it reaches DockerClient as https://192.0.2.10:2376 with the environment's tls, as from_env does.
    • DOCKER_CONTEXT beats currentContext. currentContext: default gives the default socket.
    • DOCKER_CONTEXT=nope, and separately currentContext: gone, raise DockerDaemonUnavailableError naming the missing context, and no client is built.
    • With DOCKER_HOST set, the context is ignored, as in docker-py.
  • No traceback. devops docker images exits 1 and prints one error line that names the source and gives the reason as written, with no traceback, for each of: a refused endpoint (tcp://192.0.2.1:2375), an unparsable one (tcp://192.0.2.1:abc), and one whose text holds markup (abc://x/[/x], which prints literally).

  • Pre-flight docstring. resolve_host's docstring says the check runs before docker-py's own dial (requests and urllib3) and names the DNS window for an endpoint given by name.

  • TUI. fetch_docker_status gets its client from get_engine().client(). With a refused endpoint, it returns connected=False with the refusal as error_message, and no client is built.

  • Contract test. A test pins these docker.utils.parse_host outputs, measured with docker 7.2.0, so a docker-py bump that changes any of them fails:

    • TCP://192.0.2.1:2376 → http://192.0.2.1:2376;
    • 192.0.2.1:2375 → http://192.0.2.1:2375;
    • HTTPS://192.0.2.1:2376 → https://192.0.2.1:2376;
    • ssh://u@192.0.2.1 → ssh://u@192.0.2.1:22;
    • unix:///x → http+unix:///x;
    • unix:///run/user/1000/podman/podman.sock (Podman's rootless socket) → http+unix:///run/user/1000/podman/podman.sock;
    • None → http+unix:///var/run/docker.sock;
    • tcp://192.0.2.1 and localhost:2375 raise DockerException;
    • ssh://u@192.0.2.1:22/run/user/1000/podman/podman.sock, an ssh URI with a socket path as Podman writes them, raises DockerException ("no path allowed for this protocol", docker/utils/utils.py:280-283).
  • Push.

    • localhost:5000/app:1.0, example.com:443/a/b:c and [::1]:5000/app:1 reach images.push.
    • app:1[/x] prints literally in the progress line, with no MarkupError.
    • Invalid Name!, with images.push mocked to raise a 400 APIError, prints the invalid-name error and exits 1 with no traceback. A mocked 500 prints the daemon's text.
    • With images.push mocked to raise docker.errors.InvalidRepository (what docker-py raises for -reg.example.com/app:1), the invalid-name error prints and the command exits 1. The hyphen-led registry host is the point of that case: docker-py checks only the registry part, so the name needs a dotted registry host such as -reg.example.com.
    • These tests stay green: tests/test_docker.py:54, :209-215, :253 and :275.
  • No construct left.

  • Tests updated.

    • tests/test_docker_engine.py:
      • :35-40: the default resolves to http+unix:///var/run/docker.sock from source /var/run/docker.sock, and the CONST_DOCKER_UNIX_SOCKET_URL import (:14) goes;
      • :43-54: assert that the parse_host-normalised URL reaches the check;
      • :57-66: the unix socket case;
      • :69-76, :79-86 and :437-441: patch docker.DockerClient instead of docker.from_env.
    • tests/test_docker.py:
      • :177: the patch target;
      • :205-207: Invalid Name! now needs a mocked APIError, because the SDK accepts that name.
    • tests/test_ui_dashboard.py:234 and :246: drive the engine (the docker_engine fixture, tests/conftest.py:610-623, or a patched DockerEngineService.client) instead of patching _get_docker_client.
  • Docs and release.

    • The docker.md knowledge-base page is updated at :37-42, :61 and :94.
    • A changelog.d fragment says the checks are stricter. Uppercase schemes, a bare address-and-port endpoint such as 192.0.2.1:2375, and Docker-context TCP endpoints are now checked, so a daemon on a private range needs ai.allow_private_network. A context name that does not exist is now an error instead of a silent fall-back to the default socket. devops docker push now accepts registry ports.
    • The new tests are offline and take well under 1 s together, and uv run devops ci passes.
  • feat(cli): docker containers & multi-tier workload sandbox console (tab-docker) #687's docker tab (not yet built) consumes DockerEngineService and builds no third Docker client; a comment on feat(cli): docker containers & multi-tier workload sandbox console (tab-docker) #687 records it.

  • The tests reuse fix(cli): devops docker prune removes stopped containers, unused networks and dangling images instead of failing on every engine #1116's create_autospec docker_client fixture when it has landed (and feat(docker): container commands find a Podman engine before Docker's default socket, and rootless sandboxes run as the host user #1117 reuses it too), rather than adding another hand-built fake.

Key questions

Strategic alignment

Update 2026-10-08: refinement

#1316 leaves the dashboard bypass (ui/data_providers.py:217-221) to #1334, which takes Docker from #1316's seam. Whichever of this item and #1334 lands first deletes _get_docker_client; the other's tests drive the engine.

Activity

  1. added
    type/security
    scope/security
    scope/cli
    priority/p2-medium
    on Oct 3, 2026
  2. added this to the v0.2.31 milestone on Oct 8, 2026
  3. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.31 on 2026-10-08 at the owner's request ("Populate 10 security and ci issues into each v0.2.30, v0.2.31, and v0.2.32 milestone"). This is a person's placement. Release theme: finding identity v2, URL credential masking, tests that leave no state, the Docker endpoint check and the Argo CD/OTel perimeters. Position 7 of 10 in the release's planned merge order. Its board Status is set to Ready, so the release-start fill keeps it.

  4. dan-petty-bot commented on Oct 9, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1481, merged into release/v0.2.31 as f8ebd60.

    Description

    Resolves #1108.

    Refactor Docker daemon endpoint resolution and egress validation so that checks cover the exact endpoint the SDK dials:

    • Resolve endpoints in priority order: DOCKER_HOST > DOCKER_CONTEXT > currentContext in config.json > default socket.
    • Normalise raw endpoints via docker-py's parse_host.
    • Validate network endpoints (http, https) against SSRF egress policies using validate_service_url, requiring ai.allow_private_network for private network targets.
    • Provide a public resolve_host() -> DockerEndpoint pre-flight step and construct DockerClient with validated endpoint parameters rather than uncontrolled docker.from_env().
    • Eliminate brittle regex matching in devops docker push, allowing custom registry ports (e.g. localhost:5000/app:1.0, example.com:443/a/b:c, [::1]:5000/app:1), delegating repository validation directly to docker-py and the daemon while escaping progress output.
    • Delete obsolete constants (CONST_DOCKER_UNIX_SOCKET_PATH, CONST_DOCKER_UNIX_SOCKET_URL, CONST_DOCKER_HOST_ENV_VAR, CONST_DOCKER_NETWORK_HOST_SCHEMES).
    • Update TUI data provider and documentation examples to use get_engine().client().

    13 file(s) changed.

    How it was verified

    Check runs at 90aa318:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (actions): pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1108-docker-endpoint-check.md:

    • One shared fixture docker_endpoint_env in tests/conftest.py provides isolated test environment, unsets Docker environment variables, sets allow_private_network: false, and provides a write_context helper.
    • Parametrized endpoint table verifies uppercase schemes, bare address-and-port (192.0.2.1:2375), and loopback/TEST-NET endpoints are refused without building a client.
    • Permitted private network endpoints (ai.allow_private_network: true) normalise to http://... and reach DockerClient.
    • Context resolution respects precedence (DOCKER_HOST > DOCKER_CONTEXT > currentContext > default socket) and raises DockerDaemonUnavailableError on missing contexts.
    • Environment TLS configurations (DOCKER_TLS_VERIFY, DOCKER_CERT_PATH) upgrade context endpoints to https://....
    • CLI devops docker images prints single error line naming source and reason with no traceback on invalid endpoints.
    • Pre-flight docstring on resolve_host() documents the pre-flight check and the DNS window.
    • devops docker push accepts registry ports (localhost:5000/app:1.0, example.com:443/a/b:c, [::1]:5000/app:1), escapes progress markup, and handles InvalidRepository and APIError.
    • Zero construct remnants for deleted constants, replace("tcp://", ...), docker.from_env(, and re.match in commands/docker.py.
    • Changelog fragment changelog.d/1108.md is provided.
  5. added a commit that references this issue on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/cliscope/securitytype/security

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions