dockerproxy

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const MaxBodyBytes = 32 * 1024 * 1024 // 32 MiB

MaxBodyBytes caps body reads to prevent DoS / memory exhaustion.

Variables

This section is empty.

Functions

func Reap

func Reap(ctx context.Context, upstreamSocket string, l *Ledger) error

Reap reads the ledger and issues stop+rm to the upstream Docker socket for every resource the job created. Deletion order is containers → networks → volumes (dependency order); exec entries are skipped because they are cleaned up automatically when their container is removed.

Individual stop/rm failures are logged and skipped rather than aborting, so a single stuck container does not prevent the rest from being cleaned up. cleanupSandboxAfterWait and the GC loop call this function.

Persistent workspace HOME volumes are never deleted here regardless of what the ledger says — see the volume loop's own comment.

func ResolveUpstream

func ResolveUpstream(explicit string) (string, error)

ResolveUpstream finds the upstream Docker socket path using this precedence:

  1. explicit — non-empty value from config (returned as-is, no existence check)
  2. DOCKER_HOST env var — must be unix:// prefix; TCP returns an error
  3. $XDG_RUNTIME_DIR/docker.sock — rootless docker
  4. $XDG_RUNTIME_DIR/podman/podman.sock — rootless podman
  5. /run/user/<uid>/docker.sock — rootless docker fallback
  6. /run/user/<uid>/podman/podman.sock — rootless podman fallback
  7. /var/run/docker.sock — rootful docker
  8. /run/podman/podman.sock — rootful podman

docker candidates always rank above podman within the same scope so that hosts running both daemons keep their existing behavior; podman is added as a fallback for the common case where only podman is installed.

func RewriteLedger added in v0.1.0

func RewriteLedger(path string, entries []ResourceEntry) error

RewriteLedger atomically replaces the ledger file at path with exactly entries — internal/reap's own drain step uses this to remove entries it has already confirmed destroyed, so a subsequent `boid reap` run does not re-attempt (and re-report as an error) an id that is already gone. Writes to a temp file in the same directory, fsyncs it, then os.Rename onto path: any reader always observes either the pre-rewrite or post-rewrite content in full, never a partial write.

A package-level function, not a *Ledger method, deliberately: reap's caller constructs a fresh, unshared Ledger per read, so there is no in-memory cache to keep in sync. entries may be empty (path ends up holding zero lines — still a valid, empty ledger).

Types

type Ledger

type Ledger struct {
	// contains filtered or unexported fields
}

Ledger persists Docker resource IDs created by a sandbox job to a JSONL file, enabling both id scope checks and GC (Reap) after the job exits. The file path (runtime directory) is injected by the caller; Ledger itself has no knowledge of the daemon's directory structure.

func NewLedger

func NewLedger(path string) *Ledger

NewLedger returns a Ledger backed by the given file path. The file is created on first Append if it does not exist.

func (*Ledger) Append

func (l *Ledger) Append(e ResourceEntry) error

Append writes the entry to the ledger file (append + fsync) before updating the in-memory cache. Callers must call Append before returning the creation response to the client so that "every ID the client knows is in the ledger".

func (*Ledger) Contains

func (l *Ledger) Contains(resourceType, id string) (bool, error)

Contains returns true when the ledger holds an entry with the given type and ID.

func (*Ledger) ReadAll

func (l *Ledger) ReadAll() ([]ResourceEntry, error)

ReadAll returns a snapshot of all entries currently in the ledger. Returns nil (not an error) when the ledger file does not exist yet.

type ReservedVolumes added in v0.1.0

type ReservedVolumes struct {
	// contains filtered or unexported fields
}

ReservedVolumes is the set of docker volume names a sandboxed client may neither create, delete, nor mount. It has two halves and they are ADDITIVE, never alternatives:

  • dockerres.IsReservedVolumeName — the static "boid-ws-" namespace boid names itself and can therefore recognize without asking anyone.
  • names, the set discovered at daemon startup by inspecting the daemon's OWN container (internal/dispatcher.DetectDaemonStateVolumes). These cannot be recognized by shape: under the compose deploy the daemon's entire persistent state lives in a volume the COMPOSE PROJECT names, so boid does not choose the string and cannot pattern match it.

The zero value is valid and means "static prefix only". That is deliberate: bare `boid start` has no state volume to protect, and a detection failure must not silently swap one rule for another.

func NewReservedVolumes added in v0.1.0

func NewReservedVolumes(names []string) ReservedVolumes

NewReservedVolumes captures names as the runtime half of the reserved set. Empty/blank entries are dropped: an empty Source or Name is how a client spells "anonymous volume", and reserving "" would deny every one of those.

func (ReservedVolumes) IsReserved added in v0.1.0

func (r ReservedVolumes) IsReserved(name string) bool

IsReserved reports whether a sandboxed docker client is forbidden from naming this volume, for any of create / delete / mount.

Exact string match on the runtime half, no prefix semantics: the names come from the engine's own answer about this very container, so there is nothing to generalize from and every generalization ("anything starting with the compose project name") is a way to catch an operator's unrelated volume.

type ResourceEntry

type ResourceEntry struct {
	Type string `json:"type"` // "container", "network", "volume", "exec"
	ID   string `json:"id"`
}

ResourceEntry is a single entry in the Docker resource ledger.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a Docker API proxy that filters and forwards requests to an upstream Docker daemon via a Unix socket.

func New

func New(upstreamSocket string) *Server

New creates a Server that forwards to the given upstream Unix socket path.

func NewWithLedger

func NewWithLedger(upstreamSocket string, l *Ledger) *Server

NewWithLedger creates a Server with an attached resource ledger. The ledger enables id scope checks (404 for IDs not owned by this sandbox) and write-ahead ID recording from creation responses.

func (*Server) Close

func (s *Server) Close() error

Close shuts down the server.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve begins accepting connections on ln. It blocks until Close is called.

func (*Server) ServeTLS added in v0.1.0

func (s *Server) ServeTLS(ln net.Listener, tlsConfig *tls.Config) error

ServeTLS wraps ln in tlsConfig (expected to require and verify a client certificate — see internal/mtls.CA.ServerTLSConfig) and serves on it, blocking until Close is called. This is the TCP(mTLS) counterpart to the per-sandbox UNIX socket Serve already uses. Policy allowlist logic (CheckRequest / serveHTTP above) is untouched — only the transport differs.

func (*Server) SetReservedVolumeNames added in v0.1.0

func (s *Server) SetReservedVolumeNames(names []string)

SetReservedVolumeNames adds names to the set of volume names this Server refuses to let a sandboxed docker client create, delete, or mount, on top of the static "boid-ws-" namespace that always applies.

Production passes the volumes the daemon discovered mounted into its OWN container at startup (internal/dispatcher.DetectDaemonStateVolumes, wired through Runner.ReservedVolumeNames in startDockerProxy). Under the compose deploy that is `boid_boid_state` — the single volume holding boid.db, secret.key, tls/ca.key, web_secret and install_id. Nothing about that name is derivable from boid's own naming conventions (the compose project names it), which is why it has to be injected rather than pattern matched.

Call this BEFORE Serve/ServeTLS. It is a startup-time configuration knob with the same single-writer contract as SetWorkspaceNetwork, not a live policy update: CheckRequest is a pure function over its arguments and this value is one of them, so mutating it while requests are in flight would be both a data race and an unauditable policy change. Never calling it (bare `boid start`, every existing test) leaves the zero ReservedVolumes, which behaves exactly as the policy did before this method existed.

func (*Server) SetWorkspaceNetwork added in v0.1.0

func (s *Server) SetWorkspaceNetwork(network string)

SetWorkspaceNetwork configures forced workspace-network injection: once set, every POST /containers/create request this Server forwards has its top-level NetworkingConfig REPLACED with `{EndpointsConfig: {network: {}}}` before it reaches the upstream Docker daemon — discarding whatever network configuration the sandboxed client asked for, not merging with it. This keeps job → sibling reachability (container IP + container port, direct access) scoped to the job's own workspace: every sibling a job creates always lands on that job's workspace network regardless of what the client (a docker CLI, TestContainers, ...) running inside the sandbox requested.

Empty (the zero value) preserves the prior behavior exactly: no body rewrite at all.

type Verdict

type Verdict struct {
	Allow  bool
	Reason string // populated when Allow==false
}

Verdict is the result of a policy check.

func CheckRequest

func CheckRequest(method, path string, body []byte, denyHostPortPublish bool, reserved ReservedVolumes) Verdict

CheckRequest is the main policy entry point. method is the HTTP method, path is the raw request path (may include API version prefix), body is the request body bytes (may be nil for GET/HEAD).

denyHostPortPublish gates the HostConfig.PortBindings / PublishAllPorts checks in checkContainersCreate. It must be true only for the container backend's Server, once Server.SetWorkspaceNetwork has configured a real per-job workspace network — denying it unconditionally would turn a legitimate `docker run -p`/`docker run -P` sibling use into a 403 for a caller with no workspace network to publish onto instead.

reserved is the volume-name set the three name-dependent branches below consult (POST /volumes/create's Name, DELETE /volumes/{name}, and POST /containers/create's HostConfig.Mounts[].Source). It is a plain VALUE computed once at daemon startup and handed in, never a callback or an engine handle: this function stays a pure function of its arguments so it remains auditable and so no policy decision can depend on a live query whose answer could change (or hang) mid-request. See ReservedVolumes for what goes in it. The zero value reproduces the pre-existing behavior exactly.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL