Skip to content

Allow container socket paths to be configured via config file - #4943

Merged
ChrisJBurns merged 4 commits into
mainfrom
issue-4612
Nov 25, 2026
Merged

ChrisJBurns merged 4 commits into
mainfrom
issue-4612

Conversation

@kantord

@kantord kantord commented Apr 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Users with non-standard container socket paths have to set TOOLHIVE_DOCKER_SOCKET, TOOLHIVE_PODMAN_SOCKET, or TOOLHIVE_COLIMA_SOCKET in every shell session or wrapper script. GUI and CLI processes can inherit environment variables differently depending on how they are launched, so it is easy to misconfigure and hard to debug (user report in #4612).

  • Add a container_runtime block to ~/.config/toolhive/config.yaml so socket paths can be set once and apply however ToolHive is launched.
  • Socket resolution order: env var → config file → auto-detection. Env vars keep their current precedence.
  • Each runtime only reads its own config field. A stale podman_socket rules out Podman but does not stop Docker or Colima detection in NewDockerClient's per-runtime loop. This applies on Unix and Windows.
  • A configured socket replaces auto-detection for its runtime (like the env vars), so it is the only candidate tried.
  • A Colima override reports runtime.TypeColima, the same as auto-detection and TOOLHIVE_COLIMA_SOCKET.
  • Add ContainerRuntime to config.Config so a config write (thv config set-*, UpdateConfig) keeps a hand-edited container_runtime block instead of dropping it.

Fixes #4612

Type of change

  • New feature

Test plan

  • Unit tests (task test). The only local failures were in pkg/plugins/pluginsvc SSRF tests. They also fail on clean main when TOOLHIVE_DEV is set in the shell, and pass with it unset.
  • Linting (golangci-lint on the touched packages, including GOOS=windows for pkg/container/docker/sdk. A full local task lint-fix hits an unrelated staticcheck panic with the go1.27 toolchain.)

New tests:

  • TestFindPlatformContainerSocket_ConfigOverride: Podman, Docker, and Colima overrides are used and report the right runtime type. A nonexistent path returns an error.
  • TestFindPlatformContainerSocket_ConfigOverrideOnlyAppliesToItsRuntime: a stale podman_socket fails the Podman probe, and Docker auto-detection still runs.
  • TestFindPlatformContainerSocket_ConfigOverrideReplacesAutoDetection: a configured socket is the only candidate.
  • TestFindPlatformContainerSocket_EnvOverridesConfig: the env var wins over the config file.
  • TestLoadSocketConfigFromPath: covers a missing file, an empty file, malformed YAML, a missing block, a block with the wrong shape, a partial block, and a full block.
  • TestUpdateConfigAtPath_PreservesContainerRuntime: container_runtime survives a config rewrite.

Does this introduce a user-facing change?

Yes.

Before: socket paths could only be overridden with TOOLHIVE_*_SOCKET environment variables.

After: they can also be set in ~/.config/toolhive/config.yaml:

container_runtime:
  docker_socket: /run/user/1000/docker.sock
  podman_socket: /run/user/1000/podman/podman.sock
  colima_socket: /home/user/.colima/custom/docker.sock

Environment variables still take precedence. On Windows, docker_socket and podman_socket take named pipe paths and colima_socket is ignored. This is documented in docs/arch/01-deployment-modes.md.

Special notes for reviewers

  • Deliberate deviation from the env vars: any TOOLHIVE_*_SOCKET variable applies to every runtime probe, which is existing behavior on main that this PR leaves unchanged. Config entries only apply to their own runtime, so a broken entry for one runtime cannot block the others.
  • Why not pkg/config's Provider: pkg/config imports pkg/container/docker/sdk transitively (through pkg/transport → pkg/container), so the SDK package reads the container_runtime block of the default XDG config file directly. As a result, providers injected through config.RegisterProviderFactory do not supply socket overrides. This is noted in the loadSocketConfig doc comment. SocketConfig lives in pkg/container/runtime so both packages share one type.
  • The read is best-effort and has no side effects. A missing, unreadable, or malformed file falls back to auto-detection, and the path is joined by hand rather than with xdg.ConfigFile so the probe does not create directories.
  • Windows: config pipes are checked by dialing them, the same as the env var path. CI does not run Windows tests, so that branch has been compiled and linted with GOOS=windows but not exercised at runtime.
  • Follow-ups (out of scope): thv config subcommands to set these values, and handling unix:// URLs for AF_UNIX sockets on Windows.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Apr 20, 2026
@kantord

kantord commented Apr 20, 2026

Copy link
Copy Markdown
Member Author

@claude deep review of branch please

@claude

claude Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @kantord's task in 2m 27s —— View job


Deep Code Review

  • Gather PR context
  • Read changed files
  • Read surrounding context
  • Analyze for correctness, security, style, and test coverage

Summary: This PR adds support for configuring container socket paths (Docker, Podman, Colima) via the ToolHive config file (~/.config/toolhive/config.yaml), with env vars taking precedence over config overrides, which take precedence over auto-detection. The intent is good and the approach is mostly sound, but there are a few bugs ranging from a build-breaking Windows issue to a behavioral runtime bug.


🔴 Critical — Build broken on Windows

client_windows.go:62 still has the old signature:

func findPlatformContainerSocket(rt runtime.Type) (string, runtime.Type, error) {

But factory.go:162 now calls it as:

return findPlatformContainerSocket(rt, overrides)

This is a compile error on Windows. The Windows implementation needs to be updated to accept overrides socketPathConfig even if it ignores the value (config file overrides don't apply to named pipes in the same way, but the signature must match what factory.go expects).

Fix this →


🔴 High — Config overrides ignore the rt parameter, blocking fallback

In client_unix.go around line 80–88, the config override checks fire unconditionally regardless of which runtime is being probed:

// This block is reached for EVERY iteration of the loop (TypePodman, TypeDocker, TypeColima)
if overrides.podmanSocket != "" {
    return resolveConfigSocket(overrides.podmanSocket, runtime.TypePodman, "Podman")
}
if overrides.dockerSocket != "" {
    return resolveConfigSocket(overrides.dockerSocket, runtime.TypeDocker, "Docker")
}

Scenario: user sets podman_socket to a path that doesn't exist yet (e.g., a path they plan to create). All three iterations of the outer loop in NewDockerClient hit the same podmanSocket != "" check, all return an error for that path, and Docker and Colima are never tried. The fallback logic is effectively dead.

The fix is to gate each override on the matching rt:

switch rt {
case runtime.TypePodman:
    if overrides.podmanSocket != "" {
        return resolveConfigSocket(overrides.podmanSocket, runtime.TypePodman, "Podman")
    }
case runtime.TypeDocker:
    if overrides.dockerSocket != "" {
        return resolveConfigSocket(overrides.dockerSocket, runtime.TypeDocker, "Docker")
    }
case runtime.TypeColima:
    if overrides.colimaSocket != "" {
        return resolveConfigSocket(overrides.colimaSocket, runtime.TypeColima, "Colima")
    }
}

Fix this →


🟡 High — New config fields aren't in pkg/config/Config

factory.go defines containerRuntimeOverrides as a parallel struct for parsing the container_runtime subtree of the config YAML. But pkg/config/config.go:Config has no ContainerRuntime field. As a result:

  • There's no way to write these values via thv config set or UpdateConfig
  • If the main config machinery re-serializes the config, container_runtime will be silently dropped
  • Users have to hand-edit the YAML with no documentation or validation

The comment acknowledges the import cycle (pkg/transport → pkg/container) prevents using pkg/config here, but that constraint only affects the reading side in this package. The main config struct in pkg/config should be extended:

// In pkg/config/config.go Config struct:
ContainerRuntime ContainerRuntimeConfig `yaml:"container_runtime,omitempty"`

This breaks no cycle (the pkg/config package doesn't import pkg/container), and it makes the feature a first-class, documented config field.


🟡 High — loadSocketOverrides always ignores custom --config path

loadSocketOverrides in factory.go:77 hardcodes the XDG default path:

configPath, err := xdg.ConfigFile("toolhive/config.yaml")

If a user runs thv --config /custom/path/config.yaml, the socket overrides will silently be read from ~/.config/toolhive/config.yaml, not from the specified file. This will cause confusing behavior.

There's no obvious fix here without significant refactoring (passing the config path down to NewDockerClient), but the limitation should at minimum be documented in the function's comment — and ideally tracked as a follow-up issue.


🟡 Medium — Parallel config type risks drift

containerRuntimeOverrides in factory.go:66 mirrors a fragment of the main config schema. Per project conventions (go-style.md):

Don't define a separate config/data type that mirrors an existing one. Embed or reuse the original — two parallel structs require a conversion step and will diverge over time.

If the field names in the main config ever change, containerRuntimeOverrides will silently diverge. The recommended fix (above) of adding the fields to pkg/config/Config removes this risk.


🟡 Medium — Colima override returns runtime.TypeDocker inconsistently

client_unix.go:87:

if overrides.colimaSocket != "" {
    return resolveConfigSocket(overrides.colimaSocket, runtime.TypeDocker, "Colima")
}

Auto-detection (client_unix.go:104) returns runtime.TypeColima. The env var handler also returns runtime.TypeDocker for Colima, which is a pre-existing inconsistency — but the config override should match auto-detection (runtime.TypeColima), or the inconsistency should be resolved consistently across all three paths.


🟡 Medium — Missing test coverage

client_unix_test.go has two tests, both for Docker. The following cases are untested:

  • podmanSocket override
  • colimaSocket override
  • Invalid socket path (file doesn't exist) — should return an error, not succeed
  • Config override when rt doesn't match the override type (currently broken, see above)

Also: TestFindContainerSocket_ConfigOverride is not parallel-safe if the rt-awareness bug is fixed — it currently passes only because the override fires unconditionally. After the fix, passing TypeDocker with dockerSocket set should still work, but there should be a complementary test that passes TypePodman with only dockerSocket set and verifies auto-detection is used for Podman.


🟢 Low — makeTempSocket creates a regular file, not a socket

func makeTempSocket(t *testing.T) string {
    t.Helper()
    p := filepath.Join(t.TempDir(), "test.sock")
    require.NoError(t, os.WriteFile(p, nil, 0600))
    return p
}

os.WriteFile creates a regular file. resolveConfigSocket only calls os.Stat, so the test passes regardless. The name makeTempSocket implies a Unix domain socket (net.Listen("unix", p)). The name should either be makeTempFile or use net.Listen("unix", p) with t.Cleanup. This is cosmetic but the misleading name could confuse future contributors.


🟢 Low — Empty PR description

The PR body is entirely unfilled template text. This makes it hard to understand the motivation, what issue it fixes, or how to test it. Per project conventions, the Summary, Type of change, and Test plan sections are required.


Summary table

Severity Issue
🔴 Build-breaking Windows compile error — client_windows.go not updated to new signature
🔴 Runtime bug Config overrides don't gate on rt, blocking runtime fallback
🟡 Usability container_runtime fields missing from main Config struct
🟡 Correctness loadSocketOverrides ignores custom --config path
🟡 Maintainability Parallel config type risks drifting from main schema
🟡 Correctness Colima override returns TypeDocker vs TypeColima in auto-detection
🟡 Test coverage No tests for Podman/Colima overrides, invalid paths, or rt-mismatch cases
🟢 Cosmetic makeTempSocket creates a regular file, not a socket
🟢 Process PR description is empty

@codecov

codecov Bot commented Apr 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.46154% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.12%. Comparing base (504241a) to head (5103d8f).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/container/runtime/types.go 66.66% 2 Missing ⚠️
pkg/container/docker/sdk/factory.go 93.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4943      +/-   ##
==========================================
+ Coverage   82.10%   82.12%   +0.01%     
==========================================
  Files         931      931              
  Lines       94306    94330      +24     
==========================================
+ Hits        77434    77468      +34     
+ Misses      16867    16857      -10     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 20, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 20, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 20, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 20, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 20, 2026
@kantord
kantord marked this pull request as ready for review April 21, 2026 12:54
@kantord
kantord requested review from JAORMX and jhrozek as code owners April 21, 2026 12:54
@kantord kantord self-assigned this Apr 21, 2026
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 21, 2026

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A few observations from reviewing the socket-override threading.

Comment thread pkg/container/docker/sdk/client_unix.go Resolved
Comment thread pkg/container/docker/sdk/factory.go Resolved
Comment thread pkg/container/docker/sdk/client_unix.go Resolved
Comment thread pkg/container/docker/sdk/factory.go Resolved
@eleftherias

Copy link
Copy Markdown
Member

@kantord I think this is still worth merging, could you take a look at the conflicts and comments?

@kantord

kantord commented Jun 30, 2026

Copy link
Copy Markdown
Member Author

@kantord I think this is still worth merging, could you take a look at the conflicts and comments?

absolutely, sorry for the delay

@kantord

kantord commented Jun 30, 2026

Copy link
Copy Markdown
Member Author

Hi @jhrozek sorry for the delayed response! I kept delaying it because your suggestions seemed to make a lot of sense, but also a good understanding of Go and the codebase 😄 But I never got the time to actually sit down and do it properly.

Would you mind actually pushing your suggestions directly to the branch?

@stantheman0128

Copy link
Copy Markdown
Contributor

Support. I originally treated this as Linux-only docker.sock config. That was wrong: client_windows.go already Dials env overrides with winio.DialPipeContext, and this PR adds resolveConfigPipe for config paths. Named pipes cannot be validated with os.Stat; Dial is the right probe.

The April Claude review that said Windows would not compile is stale. The current head already updates the Windows signature.

What still looks open from a Windows box:

  1. Runtime gating, same as @jhrozek already wrote on the Unix helper. if overrides.PodmanSocket != "" does not look at rt, so a leftover podman_socket fails the Docker iteration too. Env vars on current main already have that shape (TOOLHIVE_PODMAN_SOCKET is checked before rt == TypeDocker). Config should not copy it.

  2. Tests. client_unix_test.go is //go:build !windows. The DialPipe path never runs in Windows CI. pkg/server/discovery/health_windows_test.go already has a live named-pipe fixture.

Rebase is more than conflict markers. On current main, findPlatformContainerSocket returns []string, not a single path. The PR still has the old signature.

Follow-up, not a reason to NACK: if someone puts a unix://C:\... URL in docker_socket (Docker Desktop WSL / AF_UNIX on Win11), neither Stat nor DialPipe is the right probe. discovery.UnixSocketURL from #6416 is the sibling for that shape.

I will not open a second PR on #4612 while this one is open. If a Windows DialPipe test plus an rt gate would help after the rebase, say so.

ChrisJBurns and others added 2 commits November 25, 2026 22:35
# Conflicts:
#	pkg/config/config.go
#	pkg/container/docker/sdk/client_unix.go
#	pkg/container/docker/sdk/client_unix_test.go
#	pkg/container/docker/sdk/client_windows.go
#	pkg/container/docker/sdk/factory.go
Rework the config-file socket overrides on top of main's multi-candidate
socket discovery and address review feedback:

- Each runtime now only consults its own container_runtime field, so a
  stale podman_socket no longer fails the Docker and Colima probes in
  NewDockerClient's per-runtime loop (Unix and Windows).
- A Colima override reports runtime.TypeColima, matching auto-detection
  and the TOOLHIVE_COLIMA_SOCKET env var on main.
- Read the config file without xdg.ConfigFile's directory-creation side
  effect, and document why pkg/config's Provider cannot be used (import
  cycle).
- Cover per-runtime gating, env-over-config precedence, override
  replacing auto-detection, the best-effort YAML loader, and
  container_runtime surviving a config rewrite.
- Document the config file entries alongside the env var overrides.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/S Small PR: 100-299 lines changed size/M Medium PR: 300-599 lines changed labels Nov 25, 2026
@ChrisJBurns
ChrisJBurns merged commit f098ab4 into main Nov 25, 2026
56 checks passed
@ChrisJBurns
ChrisJBurns deleted the issue-4612 branch November 25, 2026 23:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Medium PR: 300-599 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support configuring container engine socket path via config file

6 participants