Files
pipelines/internal/harness/prefix.go
T
alan 05ae530442 Make Pipelines Docker-only with OpenCode and Pi
Install current verified harness releases inside Docker, preserve persistent accounts and settings, and provide separate interactive and pipeline model defaults with terminal onboarding and fuzzy pickers.

Add Docker-aware authoring transport, Pi stage execution, bounded workflow controls, reliable final-result readback and usage settlement, and finite short-lived CLI pipe draining. Keep dated installation evidence and packaged authoring guidance consistent.

Verified with a real Docker installation, both harness stages and interactive authors, the built-in plan/implement/review starter, independent host race/vet checks, installer tests, and packaged skill tests. Generated release receipts stay ignored in clean checkouts.
2026-10-11 23:00:25 +01:00

201 lines
7.5 KiB
Go

package harness
import (
"context"
"fmt"
"net"
"net/url"
"os/exec"
"strconv"
"strings"
"time"
)
// ContainerCLI is the pipelines executable inside the Docker harness image. A
// Docker-linked profile must never embed the host executable in a prompt prefix:
// Linux containers can see the mounted macOS host binary but cannot execute it
// (exec format error), and the container's loopback is its own network namespace.
const ContainerCLI = "/usr/local/bin/pipelines"
// ShellQuote quotes a value for safe use in a POSIX shell command line. It is the
// single shared quoting helper for CLI, TUI and runinspect prefixes.
func ShellQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
}
// composePort reads the published host port for a Compose service with a single
// bounded probe. It is a package variable so tests can substitute it instead of
// running Docker.
var composePort = func(directory, service, containerPort string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
output, err := exec.CommandContext(ctx, "docker", "compose", "--project-directory", directory, "port", service, containerPort).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(output)), nil
}
// binding is one host:port pair published by `docker compose port`. Host may be
// an IPv4/IPv6 literal or a wildcard (0.0.0.0, ::); the port is decimal.
type binding struct {
host string
port string
}
// covers reports whether this binding serves the requested loopback host and
// port. A wildcard binding serves only its own address family; a specific
// non-loopback address never serves a loopback request, so a different local
// service on the same port cannot be mis-attributed. "localhost" resolves to
// loopback in either family, so any loopback or wildcard binding covers it.
func (b binding) covers(host, port string) bool {
if b.port != port {
return false
}
bindIP := net.ParseIP(b.host)
loopbackBind := bindIP != nil && bindIP.IsLoopback()
wildcardV4 := b.host == "0.0.0.0" || b.host == ""
wildcardV6 := b.host == "::" || b.host == ""
if strings.EqualFold(host, "localhost") {
return loopbackBind || wildcardV4 || wildcardV6
}
requestIP := net.ParseIP(host)
if requestIP == nil || !requestIP.IsLoopback() {
return false
}
if loopbackBind {
return requestIP.Equal(bindIP)
}
if requestIP.To4() != nil {
return wildcardV4
}
return wildcardV6
}
// publishedBindings returns the host:port bindings that THIS Compose project
// publishes for the pipelines service's container port 8080. At most one bounded
// probe runs, and only for a Docker-linked loopback endpoint. Every non-empty
// line must be a complete IPv4/IPv6 host:port (including [::]:port and
// wildcards); a malformed or port-only line fails clearly instead of silently
// taking the last field.
func publishedBindings(directory string) ([]binding, error) {
output, err := composePort(directory, "pipelines", "8080")
if err != nil {
return nil, fmt.Errorf("could not confirm the Docker service's published port in %s: %w", directory, err)
}
var bindings []binding
for _, line := range strings.Split(output, "\n") {
if line = strings.TrimSpace(line); line == "" {
continue
}
host, port, err := net.SplitHostPort(line)
if err != nil {
return nil, fmt.Errorf("unexpected Docker published binding %q in %s: %w", line, directory, err)
}
if value, err := strconv.Atoi(port); err != nil || value < 1 || value > 65535 {
return nil, fmt.Errorf("unexpected Docker published binding %q in %s: invalid port", line, directory)
}
bindings = append(bindings, binding{host: host, port: port})
}
if len(bindings) == 0 {
return nil, fmt.Errorf("Docker service in %s did not report a published port", directory)
}
return bindings, nil
}
// loopback reports whether a host names this machine's loopback interface. It
// accepts only IP literals that parse and are loopback, plus the exact
// case-insensitive name "localhost". A remote DNS name that merely begins with
// "127." (for example 127.remote.example) is NOT loopback.
func loopback(host string) bool {
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
// transportAliases validates a Docker-linked logical endpoint against THIS Compose
// service. A loopback endpoint yields explicit source/target aliases only when a
// published binding covers the logical loopback address and this service's 8080
// port; a remote endpoint yields no aliases and stays remote; and a mismatched or
// unsupported local endpoint fails closed rather than silently redirecting to a
// different server or downgrading TLS to plaintext.
func transportAliases(directory, logicalURL string) (source, target string, err error) {
u, err := url.Parse(logicalURL)
if err != nil || (u.Scheme != "ws" && u.Scheme != "wss") || u.Hostname() == "" {
return "", "", nil
}
if !loopback(u.Hostname()) {
return "", "", nil
}
if u.Scheme == "wss" {
return "", "", fmt.Errorf("configured endpoint %s uses wss on a loopback host; this Docker service has no supported local TLS mapping, so refusing to redirect", logicalURL)
}
if u.User != nil || u.Fragment != "" {
return "", "", fmt.Errorf("unsupported configured endpoint %s; refusing to redirect", logicalURL)
}
port := u.Port()
if port == "" {
port = "80"
}
bindings, err := publishedBindings(directory)
if err != nil {
return "", "", err
}
for _, b := range bindings {
if b.covers(u.Hostname(), port) {
path := u.Path
if path == "" {
path = "/connect"
}
target = "ws://127.0.0.1:8080" + path
if u.RawQuery != "" {
target += "?" + u.RawQuery
}
return logicalURL, target, nil
}
}
return "", "", fmt.Errorf("configured endpoint %s is loopback but this Docker service does not publish container port 8080 on a matching host and port; refusing to redirect an endpoint that is not this Compose service", logicalURL)
}
// CLIPrefix builds the shell-quoted pipelines CLI prefix embedded in authoring and
// debugging prompts. A Docker-linked profile uses the in-container executable and,
// for this Compose service's own loopback endpoint, embeds scoped transport alias
// assignments that client.Dial maps by exact match. The original logical --url and
// all draft metadata remain unchanged; the aliases live in the prefix string (not
// cmd.Env) so the pre-existing OpenCode server's tools inherit them.
func CLIPrefix(profile Profile, logicalURL, hostExecutable string) (string, error) {
executable := hostExecutable
aliases := ""
if profile.DockerDirectory != "" {
executable = ContainerCLI
source, target, err := transportAliases(profile.DockerDirectory, logicalURL)
if err != nil {
return "", err
}
if source != "" {
aliases = "PIPELINES_TRANSPORT_SOURCE=" + ShellQuote(source) + " PIPELINES_TRANSPORT_TARGET=" + ShellQuote(target) + " "
}
}
return aliases + ShellQuote(executable) + " --url " + ShellQuote(logicalURL), nil
}
// CLIPrefixFor resolves a configured harness name (empty selects the default) and
// builds its CLI prefix. With no configured profile (for example, before harness
// setup) the native host executable is authoritative and no Docker probe runs.
func CLIPrefixFor(name, logicalURL, hostExecutable string) (string, error) {
c, err := Load()
if err != nil {
return "", err
}
if name == "" {
name = c.Default
}
profile, ok := c.Profiles[name]
if !ok {
return CLIPrefix(Profile{}, logicalURL, hostExecutable)
}
return CLIPrefix(profile, logicalURL, hostExecutable)
}