Skip to content
Open
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
5 changes: 3 additions & 2 deletions cmd/thv/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,9 @@ func init() {
serveCmd.Flags().IntVar(&port, "port", 8080, "Port to bind the server to")
serveCmd.Flags().BoolVar(&enableDocs, "openapi", false,
"Enable OpenAPI documentation endpoints (/api/openapi.json and /api/doc)")
serveCmd.Flags().StringVar(&socketPath, "socket", "", "UNIX socket path to bind the "+
"server to (overrides host and port if provided)")
serveCmd.Flags().StringVar(&socketPath, "socket", "",
`UNIX socket path or, on Windows, a named pipe (\\.\pipe\<name>) to bind the `+
"server to (overrides host and port if provided)")

// Add experimental MCP server flags
serveCmd.Flags().BoolVar(&enableMCPServer, "experimental-mcp", false,
Expand Down
2 changes: 1 addition & 1 deletion docs/cli/thv_serve.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

80 changes: 35 additions & 45 deletions pkg/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,41 +366,25 @@ func (b *ServerBuilder) setupDefaultRoutes(r *chi.Mux) {
}
}

func setupTCPListener(address string) (net.Listener, error) {
return net.Listen("tcp", address)
// namedPipePrefix is the Windows named-pipe namespace prefix. The canonical
// definition lives in pkg/server/discovery so the listener and dialer cannot
// drift; pkg/api re-aliases it here so per-platform socket files do not need
// to import discovery directly.
const namedPipePrefix = discovery.NamedPipePrefix

// isNamedPipeAddress reports whether address is a Windows named-pipe path.
// The check is platform-agnostic so callers on non-Windows can fail fast with
// a clear error before reaching the listener code. The comparison is
// case-insensitive because the Windows pipe namespace is case-insensitive at
// the kernel layer; without EqualFold an address like \\.\Pipe\foo would
// silently fall through to AF_UNIX and then fail to bind.
func isNamedPipeAddress(address string) bool {
return len(address) >= len(namedPipePrefix) &&
strings.EqualFold(address[:len(namedPipePrefix)], namedPipePrefix)
}

func setupUnixSocket(address string) (net.Listener, error) {
// Remove the socket file if it already exists
if _, err := os.Stat(address); err == nil {
if err := os.Remove(address); err != nil {
return nil, fmt.Errorf("failed to remove existing socket: %w", err)
}
}

// Create the directory for the socket file if it doesn't exist
if err := os.MkdirAll(filepath.Dir(address), 0750); err != nil {
return nil, fmt.Errorf("failed to create socket directory: %w", err)
}

// Create UNIX socket listener
listener, err := net.Listen("unix", address)
if err != nil {
return nil, fmt.Errorf("failed to create UNIX socket listener: %w", err)
}

// Set file permissions on the socket to allow other local processes to connect
if err := os.Chmod(address, socketPermissions); err != nil {
return nil, fmt.Errorf("failed to set socket permissions: %w", err)
}

return listener, nil
}

func cleanupUnixSocket(address string) {
if err := os.Remove(address); err != nil && !os.IsNotExist(err) {
slog.Warn("failed to remove socket file", "error", err)
}
func setupTCPListener(address string) (net.Listener, error) {
return net.Listen("tcp", address)
}

func headersMiddleware(next http.Handler) http.Handler {
Expand Down Expand Up @@ -592,7 +576,7 @@ func NewServer(ctx context.Context, builder *ServerBuilder) (*Server, error) {
// bound address from the listener (important when binding to port 0).
func (s *Server) ListenURL() string {
if s.isUnixSocket {
return fmt.Sprintf("unix://%s", s.address)
return socketURL(s.address)
}
return fmt.Sprintf("http://%s", s.listener.Addr().String())
}
Expand Down Expand Up @@ -715,24 +699,30 @@ func (s *Server) cleanup() {
}
}

// createListener creates the appropriate listener based on the configuration
// createListener creates the appropriate listener based on the configuration.
// Named-pipe addresses are only supported on Windows; other platforms reject
// them up front rather than creating a literal-backslash file via AF_UNIX.
func createListener(address string, isUnixSocket bool) (net.Listener, string, error) {
var listener net.Listener
var addrType string
var err error
if !isUnixSocket {
listener, err := setupTCPListener(address)
if err != nil {
return nil, "", err
}
return listener, "HTTP", nil
}

if isUnixSocket {
listener, err = setupUnixSocket(address)
addrType = "UNIX socket"
} else {
listener, err = setupTCPListener(address)
addrType = "HTTP"
addrType := "UNIX socket"
if isNamedPipeAddress(address) {
if !supportsNamedPipe() {
return nil, "", fmt.Errorf("named pipe addresses are only supported on Windows: %s", address)
}
addrType = "Windows named pipe"
}

listener, err := setupUnixSocket(address)
if err != nil {
return nil, "", err
}

return listener, addrType, nil
}

Expand Down
64 changes: 64 additions & 0 deletions pkg/api/socket_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

//go:build !windows

package api

import (
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"os"
"path/filepath"
)

// supportsNamedPipe reports whether the current build target can host a
// Windows named-pipe listener. Used by createListener to reject pipe addresses
// before reaching the per-platform setupUnixSocket implementation.
func supportsNamedPipe() bool { return false }

// setupUnixSocket creates a UNIX domain socket listener at the given path.
// On non-Windows platforms named-pipe addresses are not supported; callers
// guard against that in createListener.
func setupUnixSocket(address string) (net.Listener, error) {
if err := os.Remove(address); err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("failed to remove existing socket: %w", err)
}

if err := os.MkdirAll(filepath.Dir(address), 0750); err != nil {
return nil, fmt.Errorf("failed to create socket directory: %w", err)
}

listener, err := net.Listen("unix", address)
if err != nil {
return nil, fmt.Errorf("failed to create UNIX socket listener: %w", err)
}

if err := os.Chmod(address, socketPermissions); err != nil {
// Roll back the bound listener and the socket file rather than leaking
// either: the listener owns the AF_UNIX file and net.Listen will not
// rebind the same path while the file exists.
_ = listener.Close()
_ = os.Remove(address)
return nil, fmt.Errorf("failed to set socket permissions: %w", err)
}

return listener, nil
}

// cleanupUnixSocket removes the socket file at address. Missing files are not
// an error since cleanup may run after a partial startup.
func cleanupUnixSocket(address string) {
if err := os.Remove(address); err != nil && !errors.Is(err, fs.ErrNotExist) {
slog.Warn("failed to remove socket file", "error", err)
}
}

// socketURL returns the URL form of a Unix-socket address for the discovery
// file. Non-Windows platforms only ever produce unix:// URLs.
func socketURL(address string) string {
return "unix://" + address
}
48 changes: 48 additions & 0 deletions pkg/api/socket_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

//go:build !windows

package api

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestSocketURL_Unix(t *testing.T) {
t.Parallel()
assert.Equal(t, "unix:///tmp/test.sock", socketURL("/tmp/test.sock"))
}

func TestIsNamedPipeAddress(t *testing.T) {
t.Parallel()
tests := []struct {
name string
address string
want bool
}{
{"plain socket", "/tmp/thv.sock", false},
{"named pipe", `\\.\pipe\thv-api`, true},
{"named pipe mixed case", `\\.\Pipe\thv-api`, true},
{"empty", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tt.want, isNamedPipeAddress(tt.address))
})
}
}

// TestCreateListener_NamedPipe_Unsupported asserts that createListener rejects
// pipe addresses on non-Windows up front, mirroring the dialer-side guard
// covered by TestCheckHealth_NamedPipe_Unsupported_OnNonWindows.
func TestCreateListener_NamedPipe_Unsupported(t *testing.T) {
t.Parallel()
_, _, err := createListener(`\\.\pipe\thv-api`, true)
require.Error(t, err)
assert.Contains(t, err.Error(), "only supported on Windows")
}
91 changes: 91 additions & 0 deletions pkg/api/socket_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

//go:build windows

package api

import (
"errors"
"fmt"
"io/fs"
"log/slog"
"net"
"os"
"path/filepath"

"github.com/Microsoft/go-winio"
)

// namedPipeBufferSize is the size of the input/output buffers winio allocates
// per pipe instance. 64 KiB matches what go-winio uses in similar consumers
// (Docker, containerd, Podman) and is well above any single HTTP header chunk.
const namedPipeBufferSize = 64 * 1024

// supportsNamedPipe reports whether the current build target can host a
// Windows named-pipe listener. Used by createListener to choose between the
// pipe and AF_UNIX paths without dragging the runtime package into server.go.
func supportsNamedPipe() bool { return true }

// setupUnixSocket creates either a Windows named-pipe listener (when address
// has the \\.\pipe\ prefix) or an AF_UNIX listener at a filesystem path.
//
// Named pipes are kernel objects rather than files, so the os.Stat / os.Remove
// precheck, os.MkdirAll, and os.Chmod steps are skipped: the pipe namespace
// has no parent directory, and access control is governed by the security
// descriptor on the listener (winio's default restricts access to the
// creating user, which matches the toolhive-studio same-user use case).
//
// AF_UNIX is supported on Windows 10 1803+. The chmod step is dropped on this
// path because POSIX file modes do not apply on Windows.
func setupUnixSocket(address string) (net.Listener, error) {
if isNamedPipeAddress(address) {
// MessageMode is left at false (byte stream) explicitly because HTTP
// requires byte-oriented framing.
listener, err := winio.ListenPipe(address, &winio.PipeConfig{
MessageMode: false,
InputBufferSize: namedPipeBufferSize,
OutputBufferSize: namedPipeBufferSize,
})
if err != nil {
return nil, fmt.Errorf("failed to create named pipe listener: %w", err)
}
return listener, nil
}

if err := os.Remove(address); err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("failed to remove existing socket: %w", err)
}

if err := os.MkdirAll(filepath.Dir(address), 0750); err != nil {
return nil, fmt.Errorf("failed to create socket directory: %w", err)
}

listener, err := net.Listen("unix", address)
if err != nil {
return nil, fmt.Errorf("failed to create UNIX socket listener: %w", err)
}

return listener, nil
}

// cleanupUnixSocket removes the AF_UNIX socket file at address, or no-ops for
// named pipes (the pipe is destroyed when the listener closes).
func cleanupUnixSocket(address string) {
if isNamedPipeAddress(address) {
return
}
if err := os.Remove(address); err != nil && !errors.Is(err, fs.ErrNotExist) {
slog.Warn("failed to remove socket file", "error", err)
}
}

// socketURL returns the URL form of a Unix-socket or named-pipe address for
// the discovery file. Named pipes are emitted as npipe://<name> where <name>
// is everything after the \\.\pipe\ prefix.
func socketURL(address string) string {
if isNamedPipeAddress(address) {
return "npipe://" + address[len(namedPipePrefix):]
}
return "unix://" + address
}
Loading
Loading