PatchProof's cmd tree shows where a shared bootstrap helps and where a purpose-built entry point is clearer.
· 8 min read

How PatchProof Wires Eight Go Binaries


Open the cmd/ directory of PatchProof and you get eight main packages. Three services follow the same broad startup sequence. The API and controller differ mainly in their bootstrap options, while the all-in-one server also overrides the service role used by logging and telemetry. The other five entry points are more specialised.

The wiring is the interesting part. Everything below refers to commit 9e10cc8.

Three binaries, one bootstrap package

cmd/patchproof-api/main.go, cmd/patchproof-controller/main.go and cmd/patchproof-server/main.go share the same six-step shape:

  1. config.Load(os.Getenv("PATCHPROOF_CONFIG"))
  2. logging.New(cfg.Telemetry, cfg.Service)
  3. signal.NotifyContext for SIGINT and SIGTERM
  4. telemetry.InitTracing, with a deferred shutdown bounded by cfg.HTTP.ShutdownTimeout
  5. telemetry.NewMetrics()
  6. bootstrap.NewApp(...), then app.Run(ctx)

Their bootstrap.AppOptions values differ in step six:

  • API: bootstrap.AppOptions{Role: config.RoleAPI}
  • Controller: bootstrap.AppOptions{Role: config.RoleController, DisableHTTP: true}
  • Server: bootstrap.AppOptions{Role: config.RoleAllInOne, EnableLocalCluster: true}

The server also sets cfg.Service.Role = config.RoleAllInOne after loading the config. That is too late to change how config.Load validated role-specific settings. It does ensure that logging and tracing receive the all-in-one role, while AppOptions{Role: config.RoleAllInOne} controls which application components start.

So behavior doesn’t live in main.go. Each one is a short adapter that picks a role and hands the process to internal/bootstrap. If you’ve maintained a repo where every service’s main drifts apart over a year, one forgetting tracing shutdown, another catching signals a little differently, this is the antidote: one lifecycle path, and each binary is a config choice against it.

The main/run split

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, "patchproof-api:", err)
		os.Exit(1)
	}
}

func run() error {
	// everything else
}

os.Exit terminates the program immediately, so deferred functions do not run. If defer tracing.Shutdown(...) sits in the same function that calls os.Exit(1), the shutdown never fires and buffered spans may be lost.

Pushing the work into run() error fixes that: every defer in run completes before main picks an exit code. The API, controller and server all depend on it, because their tracing shutdown is a deferred closure that builds a fresh timeout from context.Background():

defer func() {
	shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.HTTP.ShutdownTimeout)
	defer cancel()
	_ = tracing.Shutdown(shutdownCtx)
}()

context.Background() rather than the signal-derived ctx is the bit people get wrong. By the time that closure runs, ctx is already cancelled, and handing a cancelled context to your exporter means the flush you carefully scheduled does nothing. Shutdown needs its own budget. If you want more on context plumbing generally, we’ve covered why context belongs first in your function signatures.

The broker takes a slightly different route. Its main sets up the signal context and defers stop(), but calls os.Exit(1) on an error. The defer runs after a successful run, but not on the error path. That distinction matters if more cleanup is added to main later.

Signal handling with signal.NotifyContext

Every long-running binary opens with the same two lines:

ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

signal.NotifyContext hands back a context cancelled when one of the listed signals arrives. stop unregisters the handler and puts default behavior back. Call it via defer and mean it: leave the handler installed and a second SIGTERM gets swallowed by your process instead of killing it, which is the failure mode where an operator starts reaching for kill -9.

In all three service binaries, config and logging come before the signal context, while tracing and the app come after. A config error therefore returns before the process installs its signal handler.

The proof verifier is a different kind of program

cmd/patchproof-proof/main.go breaks the pattern and should. It’s a one-shot CLI. No signal context, no tracing, no bootstrap. It parses flags and calls proofverify.Verify once.

It defines a repeatable flag type, the standard move for accepting --key more than once with the stdlib flag package:

type keyFlags []string

func (k *keyFlags) String() string { return fmt.Sprint([]string(*k)) }
func (k *keyFlags) Set(value string) error {
	*k = append(*k, value)
	return nil
}

flags.Var(&keys, "key", ...) registers it. Anything with String() string and Set(string) error satisfies flag.Value, and flag calls Set once per occurrence on the command line. For a wider tour, see our guide to the Go flag package.

The flag set sketches the verification story: -report for the report JSON bundle, -cas-root for a filesystem CAS root used for offline verification, S3 endpoint/region/bucket plus access and secret keys (defaulting to AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) for the remote case, -policy for trusted policy YAML, -key for trusted public keys as keyID=path or just path, -require-signature, -deep, -max-age and -json.

Two of those default to true: -require-signature and -deep (“verify every manifest leaf blob”). Signature checking and full blob verification are opt-out. For a verification tool that’s the correct default, even though deep verification is the expensive one. The cheap, convenient configuration should be the one you have to ask for by name.

Exit codes carry the verdict

The most portable idea in that file is the tail end of run:

switch result.Status {
case evidence.StatusValidIntegrity:
	return 0
case evidence.StatusInvalid:
	return 1
default:
	return 2
}

A flag parse failure returns 3. So does a non-nil error out of proofverify.Verify. That gives CI four distinguishable outcomes without touching stdout: valid, invalid, some other verification status, and “the tool itself failed.”

That last one is what most CLIs miss. Return 1 for both “the artifact is bad” and “I couldn’t open the file” and every pipeline downstream has to guess, usually by grepping an error string that changes next release.

Note the shape here too: main is os.Exit(run()) with run returning an int. Same discipline as the servers, applied to a program whose verdict is a number rather than an error.

The broker runs with fewer credentials on purpose

cmd/patchproof-broker/main.go carries the most useful comment in the tree. The command “performs the trusted stage-in and stage-out halves of brokered offline artifact IO. It holds the CAS credentials and the attempt token; the executing sandbox holds neither.”

That’s a privilege boundary drawn as a binary boundary. The code that moves artifacts in and out has credentials. The code that runs untrusted work does not. You can enforce that with a separate container image and service account in a way you cannot enforce with a comment inside one process.

Its config loading leans on the same idea. Before calling config.Load, it fills in a role if none was set:

if strings.TrimSpace(os.Getenv("PATCHPROOF_ROLE")) == "" {
	if err := os.Setenv("PATCHPROOF_ROLE", string(config.RoleWorker)); err != nil {
		return config.Config{}, fmt.Errorf("set broker role: %w", err)
	}
}

The comment above it explains why: the broker is a trusted worker-role component, and defaulting the role avoids requiring database and event settings that worker-role validation skips. Mutating process environment before loading config is not especially elegant, but it keeps the broker on the shared config path.

Flag parsing is stricter than the stdlib defaults. The broker builds its own flag.NewFlagSet with flag.ContinueOnError, sends output to io.Discard so errors surface through the normal error path instead of an auto-printed usage block, and refuses leftover arguments:

if flags.NArg() > 0 {
	return options{}, fmt.Errorf("unexpected positional arguments: %s", strings.Join(flags.Args(), " "))
}

Then --spec-file, --local-root and --callback-url each fall back to PATCHPROOF_SPEC_FILE, PATCHPROOF_LOCAL_ROOT and PATCHPROOF_CALLBACK_URL. Sensible for a binary that an orchestrator launches: Kubernetes injects env vars, humans type flags, and neither has to care which the other prefers.

The cluster agent builds its own capability advertisement

cmd/patchproof-cluster-agent/main.go is the one long-running binary that assembles domain objects itself instead of calling bootstrap.NewApp.

After config, logging and the signal context, it refuses to continue without two settings:

if cfg.Execution.ClusterID == "" {
	return fmt.Errorf("PATCHPROOF_CLUSTER_ID is required")
}
if cfg.Execution.AgentToken == "" {
	return fmt.Errorf("PATCHPROOF_AGENT_TOKEN is required")
}

Then it opens a store via bootstrap.OpenStore with a defer store.Close(), builds a kubernetes.New(kubernetes.Config{...}) executor from internal/adapters/executors/kubernetes, and passes both into clusteragent.New. The store doubles as the Registrar. Heartbeats go out every 30 seconds.

The tier selection is a small function worth reading twice:

func isolationTiers(cfg config.Config) []domain.IsolationTier {
	if len(cfg.Execution.SupportedIsolationTiers) > 0 {
		out := make([]domain.IsolationTier, 0, len(cfg.Execution.SupportedIsolationTiers))
		for _, tier := range cfg.Execution.SupportedIsolationTiers {
			out = append(out, domain.IsolationTier(tier))
		}
		return out
	}
	tiers := []domain.IsolationTier{domain.IsolationTrustedLocal, domain.IsolationContainer}
	if cfg.Execution.RuntimeClass != "" {
		tiers = append(tiers, domain.IsolationGVisor)
	}
	return tiers
}

Explicit config wins. Otherwise the agent advertises gVisor only when a Kubernetes RuntimeClass name is configured. That checks configuration, not whether the named RuntimeClass actually exists in the cluster, but it avoids advertising gVisor with no runtime class configured at all.

There’s a typing detail hiding in that loop. cfg.Execution.SupportedIsolationTiers is a []string, and each element is converted with domain.IsolationTier(tier). Validation happens in the config layer; the entry point converts the validated strings to domain types when it builds the advertised cluster record.

The capability advertisement is less consistent. The executor is configured from bootstrap.ConfiguredLanguages(cfg) and bootstrap.ConfiguredEngines(cfg), but the domain.Cluster the agent registers hardcodes Languages: []string{"go"}, Architectures: []string{"amd64"} and four engines. The two engine lists already differ at this revision: ConfiguredEngines also includes go-security by default and appends configured plugins. Allowed languages can diverge too. Scheduling based on the registered cluster record can therefore miss capabilities that the executor was configured to run.

The remaining two entry points

The worker and the top-level patchproof CLI complete the set of eight. The worker reads a step specification, builds execution engines, then chooses between remote reporting, a local offline result file and brokered offline storage. The CLI is a command dispatcher for local and remote verification, run management, reports, proof verification and cluster diagnostics. Neither fits the three-service bootstrap: one executes a single scheduled step, while the other routes short-lived user commands.

What to take from this

The lesson is the shape of cmd/. Three lifecycle-managed services share a bootstrap path and differ by a role constant and two booleans. The verifier, worker and user-facing CLI have short-lived jobs. The cluster agent builds its own wiring because it advertises capabilities, while the broker selects the worker role before loading shared config so it can run with a narrower set of required settings.

If you’re splitting a Go system into several binaries, the useful question isn’t how to avoid duplicating main. It’s which parts of main are honestly per-binary. Write that list down first. If it’s longer than a role and a couple of flags, you’re probably looking at a shared bootstrap that doesn’t exist yet.