ota

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ota

Over-the-air updates for Go programs. Your release pipeline signs the update, the machine streams and verifies it, swaps the binary atomically, and keeps the new version only after it proves it is healthy. If anything fails, including a power cut halfway through, the machine is left running the version it had before.

offer ─▶ verify signature ─▶ download (resumable, hashed) ─▶ swap ─▶ restart ─▶ health gate ─▶ commit
                                                                                         └──▶ roll back
  • The server holds no signing key. The publisher signs offers in CI. The server only chooses which signed offer each machine sees, so a compromised server cannot install anything the publisher did not sign.
  • One binary. Updating needs no second program to ship or manage: the updater lives inside the program it updates.
  • No dependencies. The core modules use only the standard library, and pure Go (no CGo) on Linux, macOS and Windows.

Status

Alpha (0.0.x): the API and the on-disk state may change between any two releases, so pin an exact version. What holds regardless: the core modules take no third-party dependencies (a test fails otherwise), and the fault-injection suite below runs on every change.

What it does

Tested end to end by suites that run real binaries: a fault-injection run kills the updater at every step, and the launcher and CLI suites exercise every hand-off.

  • Client: check, verify, resumable streamed download, atomic swap with crash repair, health-gated commit and rollback, and a durable outbox for reports.
  • Signatures: Sigstore/cosign (keyless, verified offline against a pinned root and signer identity) or pinned ed25519 keys. The trust root can be rotated through a signed offer.
  • Publishing: ota offer builds the offer from goreleaser output. See docs/goreleaser.md.
  • Server:
    • Intake from GitHub Releases or a static index; offers are verified at intake too.
    • Channels, staged rollouts with stable buckets, per-client pins, and a host Targeter.
    • Automatic halt on a failure rate.
    • An admin API that exists only when you give it an authorizer.
  • Restarts: re-exec, in-place service restart, side-by-side (blue/green) services, or a resident launcher (run) that supervises the program and moves itself onto the new version without restarting it.
  • Your binary's CLI: update (with stable exit codes) and run, mounted as subcommands.
  • Host hooks: approve, defer or refuse an offer; drain before the swap; reorder the update's steps.
  • OpenTelemetry: metrics and traces through an optional add-on module.

Modules

Each is its own Go module, so you take on only the dependencies you use.

Module What it is Third-party deps
github.com/ArmornetIO/ota client, server, restart strategies, health gate none
github.com/ArmornetIO/ota/lifecycle ordered start/stop hooks with rollback none
github.com/ArmornetIO/ota/service register a program with systemd, launchd or Windows Task Scheduler none
github.com/ArmornetIO/ota/verify/sigstore Sigstore verification sigstore-go
github.com/ArmornetIO/ota/server/source/github release intake from GitHub Releases go-github
github.com/ArmornetIO/ota/otel OpenTelemetry metrics and traces OpenTelemetry
github.com/ArmornetIO/ota/cmd/ota standalone server (ota serve) and publisher CLI (ota offer) the above

Every module needs Go 1.27 or newer. A test holds the core modules to the standard library.

Using it

In your program

Call Boot first thing in main. It finishes anything a previous run left behind: it repairs an interrupted swap, rolls back a version that kept crashing, and starts the health gate for a version on its first run. Call CheckAndUpdate whenever you decide to look for an update. ota never schedules anything itself.

import (
	"github.com/ArmornetIO/ota/client"
	"github.com/ArmornetIO/ota/health"
	"github.com/ArmornetIO/ota/verify/ed25519"
)

verifier, err := ed25519.New(publisherKey) // pinned in the binary
if err != nil {
	log.Fatal(err)
}

c, err := client.New(client.Options{
	Program:        "myapp",
	ClientID:       installID, // your stable id for this installation
	CurrentVersion: version,   // set with -ldflags at build time
	Transport:      &client.HTTPTransport{BaseURL: "https://updates.example.com"},
	Verifier:       verifier,
	Health:         health.ProbeURL("http://127.0.0.1:8080/healthz"),
})
if err != nil {
	log.Fatal(err)
}

// First thing in main.
if _, err := c.Boot(ctx); err != nil {
	log.Fatal(err)
}

// Whenever you decide to look for an update. With the default restarter this
// does not return when an update is applied: the process becomes the new
// version, whose Boot runs the health gate.
res, err := c.CheckAndUpdate(ctx)

Verifier is required and has no default, so a program can't ship unverified by omission.

Proving the new version is healthy

A new version is kept only after the health gate commits it:

  • In-process status: health.StatusFunc(func() string { ... }) returning one of the OpenTelemetry Collector status values (Starting, OK, RecoverableError, PermanentError, FatalError, Stopping, Stopped).
  • A local URL: health.ProbeURL(url). A 2xx means OK and a 503 means Starting. A JSON body with a status field in the vocabulary above takes precedence over the status code.
  • Explicitly: health.CommitOnly() (the default) plus a call to c.Commit() once your program knows it is working.

The gate commits after SteadyWindow (default 30s) of continuous OK. It rolls back on FatalError, on a missed CommitDeadline (default 5m), or after MaxAttempts starts that never committed (default 3), which catches crash loops.

Letting the host decide when

Hooks.BeforeApply answers each verified offer with ota.ApplyNow(), ota.DeferUntil(t, reason) or ota.RefuseOffer(reason). If you want a person to approve, ask them inside the hook; ota never draws a UI. Hooks.Drain runs before the swap with a deadline so your program can shut down gracefully. If it overruns, the attempt is abandoned rather than forced.

From the command line, in your own binary
import "github.com/ArmornetIO/ota/cli"

switch os.Args[1] {
case "update", "run", "offer":
	os.Exit(cli.Commands(loadConfig)[os.Args[1]](os.Args[2:]))
}
  • myapp update checks and applies once. It never restarts itself. If a launcher runs the program, it asks the launcher to restart onto the new version. Otherwise, if the program is a registered service, it restarts the service. Otherwise it leaves the update installed for the next start and exits 60. It then waits for the new version's verdict.
  • myapp run -- serve runs myapp serve as a child and keeps it running. Crashes are restarted with backoff unless a service manager already does that. Updates restart the child, and after a commit the launcher re-execs itself onto the new version while keeping the child running.
Exit Meaning
0 up to date, or updated and committed
10 deferred or refused by your BeforeApply hook
11 your Drain hook overran its deadline; nothing swapped
20 offer refused (signature, replay, expiry, channel, downgrade)
30 download failed
40 installed, then rolled back
50 another update is in progress
60 installed; applies on the program's next start
Choosing how the new version starts

client.Options.Restarter:

  • restart.SelfExec(): the default. Replaces the process in place.
  • restart.ServiceInPlace(spec, nil): swaps under a registered service and restarts it.
  • restart.ServiceBlueGreen(...): installs each version side by side as its own service and switches only after the new one is healthy. The program must allow port sharing (SO_REUSEPORT) for zero downtime.
  • Under run, the child strategy is chosen automatically.

Every strategy is a chain of named lifecycle steps. Options.EditChain lets you insert, remove or reorder them.

Serving updates
import (
	"github.com/ArmornetIO/ota"
	"github.com/ArmornetIO/ota/server"
	"github.com/ArmornetIO/ota/verify/ed25519"
)

store := server.NewMemStore()
if err := store.PutOffer(ota.SignedOffer{Offer: offerJSON, Signature: sig, Kind: ed25519.Kind}); err != nil {
	log.Fatal(err)
}

srv, err := server.New(server.Options{
	Store:     store,
	Blobs:     server.FSBlobStore{Dir: "/var/lib/ota/blobs"},
	Authorize: checkBearerToken, // nil only behind a host that already authenticates
})
if err != nil {
	log.Fatal(err)
}
http.Handle("/", srv.Handler())

The handler is a plain http.Handler: mount it on your own router, or behind http.StripPrefix. It serves POST /v1/check, GET /v1/artifacts/{sha256} (with resumable Range requests, and gzip when the whole file is requested) and POST /v1/reports.

Rollouts: nothing is offered until a rollout, a pin or your Targeter chooses a version, and each can only choose among offers the publisher signed. With AuthorizeAdmin set, /v1/admin/* lists releases, triggers intake, accepts a signed offer upload, sets rollouts and pins, and shows what every client runs.

Client IDs: if your Authorize returns a client id, it replaces the id in the request body, so one client cannot check or report as another.

Standalone: ota serve runs the same server on its own (see ota serve -h). If you run your own http.Server, set ReadHeaderTimeout but not ReadTimeout/WriteTimeout: artifact downloads are long-lived streams.

The offer

An offer is a small JSON document, signed by the publisher over its exact bytes. The client verifies it before parsing anything, so there is no canonical form to get wrong.

{
  "schema": "ota.offer/v1",
  "program": "myapp",
  "version": "1.8.0",
  "issued_at": 1789776000000,
  "channels": ["stable"],
  "artifacts": [
    { "os": "linux", "arch": "amd64", "sha256": "9f2c…", "size": 48213504,
      "urls": ["https://mirror.example.com/myapp_linux_amd64"] }
  ]
}

A client refuses an offer when any of these hold:

  • The signature fails.
  • It is for another program.
  • issued_at is not newer than the last offer it acted on (replay).
  • issued_at is too far in the future (5-minute tolerance).
  • It has expired (expires_at, optional).
  • It excludes the client's channel.
  • It names an older version without "downgrade": true.
  • It has no artifact for the client's OS and architecture.

A deliberate rollback is a new signed offer naming the older version.

Security model

  • The publisher signs offers; nothing else can. A compromised release server can withhold offers, but it cannot forge one, and it cannot replay an old one: each machine remembers the newest offer it acted on.
  • Accepted risk: with expires_at unset (the default), a compromised server can hide newer releases and keep machines on an older signed version. Set an expiry and re-sign on a schedule if that matters to you.
  • Downloads are checked against the signed size and SHA-256 as they stream and again over the whole file, including after a resume. So a mirror, a proxy or a tampered partial file can only make an update fail, never install the wrong bytes.
  • Mirror URLs must be https. Plain http is allowed only for localhost.

On disk

State lives next to the binary, in <dir>/.ota/<binary-name>/ (mode 0700). Keeping it on the same filesystem makes the swap a single atomic rename, and two programs installed in the same directory never share state.

File Purpose
lock Single-updater lock; the OS releases it if the process dies
state.json Last accepted offer (the replay floor), running version
pending.json An update awaiting its health gate
prev The previous binary, kept until commit
.ota-*.part, download.json A resumable partial download

Temp files are created exclusively with mode 0600. Leftovers from crashed runs are removed at the next Boot, but only while holding the lock.

Platforms

Linux, macOS and Windows, pure Go. On Windows a running .exe cannot be overwritten, so the swap renames it aside first. The displaced file is removed at the next start, and a crash between the two renames is repaired at boot.

Development

go test ./...                 # needs to open localhost listeners
go test ./... -short          # skips the suites that build binaries

The fault-injection suite (client/faults_test.go) builds testdata/sampleapp twice, as v1 and v2, and kills the updater at every step using the otatest build tag. Without that tag the kill hooks compile to nothing, so no shipped binary can be made to exit by an environment variable.

Each module has its own go.mod, so go test ./... at the root covers only the core; .github/workflows/ci.yml lists all six. Build the ota command from a clone (cd cmd/ota && go build .): it resolves its sibling modules from the tree, so go install …@version refuses it.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package ota holds the types shared by the ota client, server and CLI: the signed offer, update events and reports, and the sentinel errors callers branch on.

Index

Constants

View Source
const OfferSchema = "ota.offer/v1"

OfferSchema is the only offer schema this version understands. The major version is what a client checks; unknown fields are ignored so v1 clients survive additive changes such as deltas.

Variables

View Source
var (
	// ErrRefused: the offer failed verification, replay, expiry, channel or
	// downgrade rules. Nothing was downloaded or changed.
	ErrRefused = errors.New("ota: offer refused")
	// ErrDeferred: the host deferred or refused the offer.
	ErrDeferred = errors.New("ota: update deferred by host")
	// ErrDrainTimeout: the host's drain step overran its deadline; nothing was swapped.
	ErrDrainTimeout = errors.New("ota: host drain exceeded its deadline")
	// ErrDownload: the download failed or its bytes did not match the offer.
	ErrDownload = errors.New("ota: download failed")
	// ErrRolledBack: the new version was installed, failed its health gate and
	// was replaced by the previous one.
	ErrRolledBack = errors.New("ota: update rolled back")
	// ErrLocked: another updater holds the lock for this installation.
	ErrLocked = errors.New("ota: another update is in progress")
	// ErrRestartNeeded: the update is verified and staged, and applies on the
	// program's next start.
	ErrRestartNeeded = errors.New("ota: update staged; restart needed")
)

Sentinels map one-to-one onto the CLI exit codes, so a caller branches with errors.Is and the CLI never parses a message.

Functions

func ValidChannel

func ValidChannel(s string) bool

ValidChannel reports whether s is a well-formed channel name.

func ValidSHA256

func ValidSHA256(s string) bool

ValidSHA256 reports whether s is a lowercase hex SHA-256, the only form an artifact path segment may take before it reaches a store.

Types

type Action

type Action int

Action is the host's answer to an offer.

const (
	Apply Action = iota
	Defer
	Refuse
)

type Artifact

type Artifact struct {
	OS     string   `json:"os"`
	Arch   string   `json:"arch"`
	SHA256 string   `json:"sha256"`
	Size   int64    `json:"size"`
	URLs   []string `json:"urls,omitempty"`
}

Artifact is one platform's binary, identified by its content hash.

type CheckRequest

type CheckRequest struct {
	ClientID          string `json:"client_id"`
	Program           string `json:"program"`
	OS                string `json:"os"`
	Arch              string `json:"arch"`
	Channel           string `json:"channel,omitempty"`
	RunningVersion    string `json:"running_version"`
	LastOfferIssuedAt int64  `json:"last_offer_issued_at"`
}

CheckRequest is what a client tells the server when asking for an offer.

type Decision

type Decision struct {
	Action Action
	// Until is when a deferred offer may be reconsidered.
	Until  time.Time
	Reason string
}

Decision is what a BeforeApply hook returns. ota never prompts anyone; a host that wants a person to approve asks them inside the hook and answers here.

func ApplyNow

func ApplyNow() Decision

ApplyNow is the Decision that proceeds immediately.

func DeferUntil

func DeferUntil(t time.Time, reason string) Decision

DeferUntil postpones the offer; it is reconsidered at or after t.

func RefuseOffer

func RefuseOffer(reason string) Decision

RefuseOffer declines this offer; it is reported and not retried.

type Event

type Event struct {
	Stage   Stage
	Program string
	Version string
	// Bytes and Total are set on download progress events.
	Bytes, Total int64
	Err          error
	At           time.Time
}

Event is emitted to Options.OnEvent at every stage transition.

type Offer

type Offer struct {
	Schema   string `json:"schema"`
	Program  string `json:"program"`
	Version  string `json:"version"`
	IssuedAt int64  `json:"issued_at"`
	// ExpiresAt is optional and off by default; zero means the offer does not
	// expire. See the accepted freeze risk in the security model.
	ExpiresAt int64 `json:"expires_at,omitempty"`
	// Downgrade must be set for an offer whose Version is lower than what a
	// client runs, so a mislabelled offer cannot roll a machine back by accident.
	Downgrade bool     `json:"downgrade,omitempty"`
	Channels  []string `json:"channels,omitempty"`
	// MinVersion is reserved; v1 clients ignore it.
	MinVersion      string           `json:"min_version,omitempty"`
	Artifacts       []Artifact       `json:"artifacts"`
	TrustRootUpdate *TrustRootUpdate `json:"trust_root_update,omitempty"`
	// Deltas is reserved for patch updates; v1 clients ignore it.
	Deltas json.RawMessage `json:"deltas,omitempty"`
	// contains filtered or unexported fields
}

Offer is the publisher-signed statement that clients may move to Version. The signature covers the exact bytes it was parsed from, never a re-serialisation, so there is no canonical form to get wrong.

func ParseOffer

func ParseOffer(b []byte) (Offer, error)

ParseOffer decodes and shape-checks an offer. Call it only on bytes whose signature has already verified: the fields are publisher input, and nothing here is a substitute for that check.

func (Offer) AdmitsChannel

func (o Offer) AdmitsChannel(channel string) bool

AdmitsChannel reports whether a client on channel may be shown this offer.

func (Offer) ArtifactFor

func (o Offer) ArtifactFor(goos, goarch string) (Artifact, bool)

ArtifactFor returns the artifact built for exactly this OS and architecture.

func (Offer) Expires

func (o Offer) Expires() (time.Time, bool)

Expires returns the expiry and whether one is set.

func (Offer) Issued

func (o Offer) Issued() time.Time

Issued returns IssuedAt as a time.

func (Offer) SemVer

func (o Offer) SemVer() Version

SemVer returns the parsed Version. Valid only on an Offer from ParseOffer.

type Report

type Report struct {
	ClientID      string `json:"client_id"`
	Program       string `json:"program"`
	Version       string `json:"version"`
	OfferIssuedAt int64  `json:"offer_issued_at"`
	Stage         Stage  `json:"stage"`
	Error         string `json:"error,omitempty"`
	At            int64  `json:"at"`
}

Report is one reported stage of one attempt, as sent to the server.

type SignedOffer

type SignedOffer struct {
	Offer     []byte `json:"offer"`
	Signature []byte `json:"signature"`
	Kind      string `json:"signature_kind"`
}

SignedOffer is an offer's exact bytes plus the publisher's signature over them. The server passes both through untouched; it cannot mint either.

type Stage

type Stage string

Stage is a point in an update attempt, reported to the server and emitted as an event. The set is closed: rollout auto-halt counts specific stages, so an ad-hoc string would silently fall out of that arithmetic.

const (
	StageOfferSeen   Stage = "offer_seen"
	StageDeferred    Stage = "deferred"
	StageRefused     Stage = "refused"
	StageDownloading Stage = "downloading"
	StageDownloaded  Stage = "downloaded"
	StageVerified    Stage = "verified"
	StageSwapped     Stage = "swapped"
	StageInstalled   Stage = "installed"
	StageHealthy     Stage = "healthy"
	StageCommitted   Stage = "committed"
	StageRolledBack  Stage = "rolled_back"
	StageFailed      Stage = "failed"
	StageStaged      Stage = "staged"
)

func (Stage) Reported

func (s Stage) Reported() bool

Reported is whether a stage is sent to the server. The rest are local progress: useful to a host watching events, noise in a server's report.

type TrustRootUpdate

type TrustRootUpdate struct {
	Version int64           `json:"version"`
	Kind    string          `json:"kind"`
	Root    json.RawMessage `json:"root"`
}

TrustRootUpdate carries replacement trust material. A client adopts it only from an offer that verified under the root it already trusts.

type Version

type Version struct {
	Major, Minor, Patch uint64
	Pre                 []string
	Build               string
	// contains filtered or unexported fields
}

Version is a parsed semantic version (semver 2.0). Build metadata is kept for display but ignored in comparisons, as the spec requires.

func MustParseVersion

func MustParseVersion(s string) Version

MustParseVersion is for constants in tests and examples.

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion accepts "1.8.0", "v1.8.0", "1.9.0-rc.1+abc". A leading "v" is allowed because git tags carry one and offers are generated from tags.

func (Version) Compare

func (v Version) Compare(o Version) int

Compare returns -1, 0 or 1. A prerelease sorts before its release, which is what keeps 1.9.0-rc.1 from being offered as an upgrade over 1.9.0.

func (Version) String

func (v Version) String() string

String renders the version without a leading "v", the form offers use.

Directories

Path Synopsis
Package cli gives a host program ota's commands as subcommands of its own binary, so updating never needs a second program:
Package cli gives a host program ota's commands as subcommands of its own binary, so updating never needs a second program:
Package client checks for, verifies and applies updates to the running program.
Package client checks for, verifies and applies updates to the running program.
examples
hello command
Command hello is a program that keeps itself up to date: it prints its version, then checks the update server every -every and becomes the new version when a signed one is offered.
Command hello is a program that keeps itself up to date: it prints its version, then checks the update server every -every and becomes the new version when a signed one is offered.
Package health decides whether a freshly installed version is healthy enough to keep.
Package health decides whether a freshly installed version is healthy enough to keep.
internal
stage
Package stage owns everything that touches disk before a swap: the single-updater lock, the state directory, free-space checks, and the streamed, resumable, hash-verified download.
Package stage owns everything that touches disk before a swap: the single-updater lock, the state directory, free-space checks, and the streamed, resumable, hash-verified download.
swap
Package swap replaces the installed binary with a verified new one and puts it back when the new one fails.
Package swap replaces the installed binary with a verified new one and puts it back when the new one fails.
testkit/fixture
Package fixture builds sampleapp as v1 and v2, installs v1 and serves v2, for the suites that exercise real binaries.
Package fixture builds sampleapp as v1 and v2, installs v1 and serves v2, for the suites that exercise real binaries.
lifecycle module
otel module
Package restart decides how a swapped-in version starts running.
Package restart decides how a swapped-in version starts running.
Package server is the ota release server: it chooses which publisher-signed offer each client sees, streams artifacts, and records what clients report.
Package server is the ota release server: it chooses which publisher-signed offer each client sees, streams artifacts, and records what clients report.
source/httpindex
Package httpindex reads releases from a static JSON index, which any host can publish: GitLab or Gitea release pages, an S3 bucket, a plain file server.
Package httpindex reads releases from a static JSON index, which any host can publish: GitLab or Gitea release pages, an S3 bucket, a plain file server.
source/github module
service module
Package verify defines how an offer's signature is checked.
Package verify defines how an offer's signature is checked.
ed25519
Package ed25519 verifies offers signed with a pinned ed25519 key.
Package ed25519 verifies offers signed with a pinned ed25519 key.
sigstore module

Jump to

Keyboard shortcuts

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