server

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 36 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.

Documentation

Overview

Package server is the vedette-host socket server: a unix-socket HTTP/1.1 JSON API with a closed command table, durable runs, one global write lock, a hash-chained audit log and per-connection peer authentication (docs/specs/host-api.md). It is the framework of; the system commands live in host/ops and are handed in through Options.Registry and Options.Readers.

OS assumption: the real peer check needs Linux (SO_PEERCRED, /proc). The server itself is portable so its tests run anywhere with an injected peer.Checker.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotAwaiting is returned by Settle when no run with that id is awaiting confirmation:
	// it was already settled (the other side of a confirm-against-timer race won), never waited,
	// or has not finished entering the awaiting state yet.
	ErrNotAwaiting = errors.New("host: that run is not awaiting confirmation")
	// ErrShuttingDown is returned by Settle once Shutdown has begun. The run stays awaiting on
	// disk; the next start asks Options.Resume.
	ErrShuttingDown = errors.New("host: shutting down")
)
View Source
var ErrAuditBroken = errors.New("host: audit chain is broken")

ErrAuditBroken means the chain on disk does not verify (or a write failed); nothing is appended after it.

View Source
var ErrNotParked = errors.New("host: that run is not parked")

ErrNotParked is returned by SettleParked when no run with that id is parked: it was already settled (the loser of a race), never parked, or has not finished parking yet.

View Source
var ErrWriteBusy = errors.New("host: another write command is running")

ErrWriteBusy is what WithWriteLock answers while a write command, or a run awaiting confirmation, holds the global write lock.

Functions

func NewCommandRunner

func NewCommandRunner(log *slog.Logger, bins ...vexec.Binary) (*vexec.Runner, error)

NewCommandRunner builds the one exec.Runner commands use for child processes. Every binary it gets runs with exactly PATH, LANG=C and DEBIAN_FRONTEND=noninteractive, no shell, from "/". A binary that sets its own Env is rejected: the environment is not the command's to choose.

func ParseOSRelease

func ParseOSRelease(data []byte) (distro, release string)

ParseOSRelease reads ID and VERSION_ID from the text of /etc/os-release. The file is data that root's tools write but the parser treats as untrusted: it returns only short, plain tokens ("ubuntu", "24.04"), "unknown" for anything missing or odd, and never fails.

func SocketLive

func SocketLive(ctx context.Context, path string) bool

SocketLive says whether something accepts connections on the unix socket at path: the host's own "is a daemon running" test. A daemon takes the socket before it serves, so a bootstrap that finds it live must not touch the state the daemon owns.

Types

type ArgsError

type ArgsError struct{ Details []api.Detail }

ArgsError is a validation failure of a command's args.

func Invalid

func Invalid(field, reason string) *ArgsError

Invalid builds an ArgsError for one field ("args.<name>"; an empty field means the whole args).

func (*ArgsError) Error

func (e *ArgsError) Error() string

type Awaiting

type Awaiting struct {
	RevertAt time.Time
	Result   any
}

Awaiting is what Run returns (as its result, with a nil error) to park the run in awaiting_confirm instead of finishing it: the run is stored with revert_at, an audit line awaiting_confirm is written, and the run KEEPS the global write lock until (*Server).Settle ends it. Result is stored as the run's result like Failure.Result. RevertAt must be set. The command arms its own timer (arm it in rc.OnParked) and ends the run with Claim and Finish, or Settle. RevertAt must be in the future and at most maxRevertWindow after the run started.

type Claimed

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

Claimed is the right to end one awaiting run, taken by Claim. Finish ends it exactly once.

func (*Claimed) Finish

func (c *Claimed) Finish(status api.Status, rerr *api.RunError) error

Finish ends the claimed run as status (succeeded, failed or reverted; failed and reverted need rerr): it writes the final audit line and the run, releases the write lock (or hands it to the WhileAwaiting command still running) and sends the final event, in that order, then runs the AfterFinish callbacks the awaiting command registered. The stored Awaiting.Result is kept. A bad status is an error and the claim stays open; a second successful Finish is ErrNotAwaiting.

type Command

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

Command is one entry of the closed command table (INV-1). Build it with Define; the only way to put it in a Registry is NewRegistry, and a Registry cannot change afterwards.

func Define

func Define[A any](s Spec[A]) Command

Define turns a Spec into a Command.

func (Command) Name

func (c Command) Name() string

Name is the command name, for example "os.check".

func (Command) Write

func (c Command) Write() bool

Write reports whether the command takes the global write lock.

type Failure

type Failure struct {
	Code    string
	Message string
	Result  any
}

Failure makes a run end as failed with a specific code and a message safe to show. Result, when not nil, is stored as the run's result next to the error (for example the health checks of a run that installed packages but left the box unhealthy).

func (*Failure) Error

func (e *Failure) Error() string

type File

type File struct {
	Body io.ReadCloser
	Size int64
	Name string
	Type string // media type, for example application/gzip
}

File is a download: the host opens it and the server streams it. Name is the download name (plain, chosen by the host).

type NoteWriter

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

NoteWriter appends host-originated lines to the audit chain without a running server: the bootstrap writes release_index_stored and installed lines to the same file and chain the daemon uses.

func OpenNoteWriter

func OpenNoteWriter(path string, ownerUID int) (*NoteWriter, error)

OpenNoteWriter opens (creating it 0600) and verifies the audit log at path, owned by ownerUID.

func (*NoteWriter) Close

func (w *NoteWriter) Close() error

Close closes the file.

func (*NoteWriter) Note

func (w *NoteWriter) Note(command, code string, detail map[string]any) error

Note is Server.Note.

type Options

type Options struct {
	SocketPath string // absolute, validated by config.ValidSocketPath
	SocketGID  int    // group that owns the socket and its directory (the "vedette" group)
	StateDir   string // runs, idempotency records; mode 0700
	AuditPath  string // audit.jsonl; its directory is created 0700
	Registry   *Registry
	Readers    Readers // read-only state endpoints (spec section 5); zero value: none
	// WriteGate, when set, is asked before a write command is accepted (after the idempotency
	// lookup, so a retry of an accepted request still gets its run). A non-nil refusal ends the
	// request like busy does: no run, one audit line. It must not block or take locks the server holds.
	WriteGate func() *Refusal
	// Resume is asked, during New (so before Listen), about each run a restart found in
	// awaiting_confirm or parked (running with parked_deadline). True: the run stays
	// as it was and keeps the write lock; the caller then re-arms its timer or settle goroutine
	// (after New returns) and ends the run with Settle or SettleParked, at once if revert_at has
	// passed. False, nil, a panic, or a second such run: the run is settled failed host_restarted
	// like any run a crash cut short. Any other run a restart finds unfinished is never offered (it
	// was cut short mid-command and fails host_restarted). Resume must only read.
	Resume    func(api.Run) bool
	PeerCheck peer.Checker // layers 2 and 3 of the peer check; required
	Version   string

	Logger        *slog.Logger
	Now           func() time.Time
	OSReleasePath string // default /etc/os-release

	RequestsPerMinute int
	WritesPerMinute   int
	KillGrace         time.Duration // how long a command may ignore its cancelled context before the run is reported failed (the write lock stays held)
	AbandonCeiling    time.Duration // how long past KillGrace a command may keep running before the host exits for systemd to restart it (default 5 min)
	CheckTimeout      time.Duration // bound of a command's synchronous Check (default 5 s)
	BodyDeadline      time.Duration // how long a request body may take to arrive (default 30 s)
	AuditThrottle     time.Duration // minimum spacing of unauthenticated-flood audit lines per uid (default 10 s)
	// OwnerUID is the uid that must own the state, audit and socket directories and the audit
	// file: 0 in production (the host runs as root). Tests set their own uid.
	OwnerUID int
	// Exit ends the process when a command cannot be stopped (default os.Exit). Tests replace it.
	Exit func(code int)
}

Options configures a Server. Zero values of the optional fields mean the defaults of spec section 10.

type Parked

type Parked struct {
	Deadline time.Time
	Result   any
}

Parked is what Run returns (as its result, with a nil error) to park the run instead of finishing it: the run is stored running with parked_deadline, an audit line parked and a log event are written, and the run KEEPS the global write lock until (*Server).SettleParked ends it, in this process or in the next one (Options.Resume). Result is stored as the run's result until then. Deadline must be in the future and at most maxParkWindow after the run started; the server does not end the run at Deadline by itself, the command's settle goroutine does.

type ReadError

type ReadError struct {
	Status  int
	Code    string
	Message string
}

ReadError is what a Readers function returns to answer with a specific status and code (spec section 11): 404 for an id the host does not know, 403 for a file that must not leave the box, 409 for a state that is changing right now (read it again later).

func NewReadError

func NewReadError(status int, code, message string) *ReadError

NewReadError builds a ReadError. Programming error (panic) for a status outside 403, 404 and 409 or a bad code.

func (*ReadError) Error

func (e *ReadError) Error() string

type Readers

type Readers struct {
	OS            func(ctx context.Context) (any, error) // GET /v1/state/os
	Time          func(ctx context.Context) (any, error) // GET /v1/state/time (the operating system's time zone)
	Backups       func(ctx context.Context) (any, error) // GET /v1/state/backups
	Net           func(ctx context.Context) (any, error) // GET /v1/state/net
	Containers    func(ctx context.Context) (any, error) // GET /v1/state/containers (slice 3-6)
	Host          func(ctx context.Context) (any, error) // GET /v1/state/host (host.self_update)
	Packages      func(ctx context.Context) (any, error) // GET /v1/state/packages (the box's dpkg list)
	Ports         func(ctx context.Context) (any, error) // GET /v1/state/ports (the ports the box listens on, inventory INV-3)
	HPTouches     func(ctx context.Context) (any, error) // GET /v1/state/hp-touches (new connection attempts to the decoys)
	BackupContent func(id string) (File, error)          // GET /v1/backups/{id}/content
	ExportContent func(id string) (File, error)          // GET /v1/exports/{id}/content
	ZapReport     func(id string) (File, error)          // GET /v1/zap/{id}/content (the report of the last zap.baseline)
}

Readers are the read-only state endpoints of spec section 5 that the system commands provide. A nil function means the endpoint does not exist yet and answers 404 unknown_command, like any other path outside the spec. Each function must only read.

type Refusal

type Refusal struct {
	Status  int
	Code    string
	Message string
	// RetryAfterS, when positive, is the hint "try again in this many seconds" (also sent as Retry-After).
	RetryAfterS int
}

Refusal makes a run end as refused. Status is the HTTP status (409 for a state conflict, 412 for a failed precondition, 404 for an id the host does not know, spec section 11).

func Refuse

func Refuse(status int, code, message string) *Refusal

Refuse builds a Refusal. Programming error (panic) if the status is not 404, 409 or 412 or the code is not snake_case.

func RefuseRetry

func RefuseRetry(status int, code, message string, retryAfterS int) *Refusal

RefuseRetry is Refuse with a retry hint in seconds.

func (*Refusal) Error

func (e *Refusal) Error() string

type Registry

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

Registry is the closed command table: built once, read-only, no Register method.

func NewRegistry

func NewRegistry(cmds ...Command) (*Registry, error)

NewRegistry validates and freezes the table.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (Command, bool)

Lookup finds a command by exact name.

func (*Registry) Names

func (r *Registry) Names() []string

Names lists the commands, sorted (the commands[] of GET /v1/info).

type Reverted

type Reverted struct {
	Code    string
	Message string
	Result  any
}

Reverted makes a run end with status reverted: the command changed the system, it did not work, and the command put the previous state back. Result is stored like Failure.Result.

func (*Reverted) Error

func (e *Reverted) Error() string

type RunContext

type RunContext struct {
	RunID string
	Actor string
	// RequestID is the X-Request-Id the run was accepted with (host.self_update keeps it in its journal).
	RequestID string
	// contains filtered or unexported fields
}

RunContext is what a running command gets to report progress.

func (*RunContext) AfterFinish

func (rc *RunContext) AfterFinish(fn func(ctx context.Context, st api.Status))

AfterFinish registers fn to run once the run is recorded as final: audit line and run file written, write lock released, final event sent. fn gets the final status and a context that outlives the run and the server's shutdown (it is only ever cancelled by nothing: the callback is short and must finish its work). It runs on its own goroutine, and only when the command returned (a command that ignored its deadline gets no callbacks). Use it for effects that must not be part of the run, such as rebooting the machine after the run is recorded as succeeded. Call it from the command's Run goroutine only.

func (*RunContext) Log

func (rc *RunContext) Log(line string)

Log appends one line (cut to 2 KiB, control characters removed) to the run's event stream.

func (*RunContext) OnParked

func (rc *RunContext) OnParked(fn func())

OnParked registers fn to run right after the run is parked (in awaiting_confirm, or running as Parked), when the write lock and the parked state are already published and stored: arm the revert timer here, or start the goroutine that does the work outside the process and settles the run, so that it can never find the run "not yet parked". fn must not block. It does not run when the run ends any other way (an invalid Awaiting or Parked included). Call it from Run only. Neither OnParked nor AfterFinish callbacks survive a host restart: after one, whoever resumed the run (Options.Resume, then Ops.Start from net/pending.json or the journal) must re-arm itself. The context Run got is cancelled as soon as Run returns, a park included: a goroutine started here must not use it (give it a context of its own, as the settle goroutine of a Parked run needs).

func (*RunContext) Progress

func (rc *RunContext) Progress(percent int)

Progress reports 0..100 (clamped).

type Server

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

Server serves the host API.

func New

func New(o Options) (*Server, error)

New opens the state, verifies the audit chain and recovers runs a crash left in progress. A broken audit chain does not stop it: writes are refused with audit_unavailable and /v1/info reports audit_ok=false; the caller should also log AuditError.

func (*Server) AuditError

func (s *Server) AuditError() error

AuditError is nil while the audit chain verifies; otherwise it says why writes are refused.

func (*Server) AwaitingConfirm

func (s *Server) AwaitingConfirm() bool

AwaitingConfirm reports whether a run is parked in awaiting_confirm. ops uses it as the network-change-pending check of os.reboot.

func (*Server) Claim

func (s *Server) Claim(runID string) (*Claimed, error)

Claim is the compare-and-set of an awaiting run: it takes the run out of the waiting state, so every other Claim, Settle and WhileAwaiting command for it gets ErrNotAwaiting / 412 from now on, but it KEEPS the write lock until Finish. Confirm and revert must Claim first, do their effects, then Finish: the race between a confirm and the timer is then decided before either touches the system, and nothing else can write while the winner works. A Claimed must always be finished (use defer): until then the lock is held and Shutdown waits for it (bounded by its ctx). ErrNotAwaiting: no such run is waiting (already claimed or settled, never waited); ErrShuttingDown after Shutdown began (the run stays awaiting on disk).

func (*Server) Listen

func (s *Server) Listen(ctx context.Context) (net.Listener, error)

Listen prepares the directory and returns the unix listener. The directory must be a real directory owned by OwnerUID and group SocketGID, mode 0750 or stricter (created so when absent); a stale socket file is replaced, a live one refused. The socket is then given to group SocketGID (Lchown, which never follows a symlink) and set to 0660 by path, and the path is checked, before and after, to still be that very socket (same inode); see secureSocket for why this is safe. There is no other listener anywhere in the program (FORBID-2).

func (*Server) Note

func (s *Server) Note(command, code string, detail map[string]any) error

Note appends one host-originated line to the audit chain: something the host did on its own (a scheduled reboot, noticing that a reboot finished), not a request. Actor is "system", the result "ok", and detail (small, no secrets) goes to args_redacted. It fails when the chain is broken.

func (*Server) Serve

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

Serve accepts connections on ln until Shutdown. It returns nil after a Shutdown.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the whole API. The connection was authenticated at accept time.

func (*Server) Settle

func (s *Server) Settle(runID string, status api.Status, rerr *api.RunError) error

Settle is Claim and Finish in one call, for an ending that has no effects of its own to run between the two (see Claim). It works exactly once per run (the loser of a race gets ErrNotAwaiting and changes nothing).

func (*Server) SettleParked

func (s *Server) SettleParked(runID string, status api.Status, result any, rerr *api.RunError) error

SettleParked ends the parked run exactly once as status (succeeded, failed or reverted; failed and reverted need rerr) with result (nil keeps the Parked.Result stored when it parked). As for an awaiting run it writes the final audit line, then the run file together with the release of the write lock, then the final event (seq goes on from the stored events), then runs the AfterFinish callbacks of the command. A bad status is an error and the run stays parked; ErrNotParked when no run with that id is parked (a second call included); ErrShuttingDown once Shutdown has begun, and the run stays parked on disk for the next start.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops accepting work: new requests get 503 host_shutting_down, running commands have their context cancelled, and it waits for them (bounded by ctx) before closing the listener and the audit log. A run awaiting confirmation or parked stays as it is on disk, with the write lock it holds (the next start decides, Options.Resume); Claim, Settle and SettleParked after Shutdown began return ErrShuttingDown and change nothing. A command that returns Parked after Shutdown began is not parked: its run ends failed host_shutting_down.

func (*Server) WithWriteLock

func (s *Server) WithWriteLock(ctx context.Context, fn func(ctx context.Context)) error

WithWriteLock runs fn holding the global write lock, the way a command does (INV-3: never two writes at once): a command that arrives meanwhile gets 409 busy. It does not wait: when the lock is taken it returns ErrWriteBusy and the caller tries again later. It exists for the work the host does on its own after it is ready (the post-READY step of ops), which has no request.

func (*Server) WriteActive

func (s *Server) WriteActive() bool

WriteActive reports whether a write command holds the global write lock right now (a run that awaits confirmation holds it too).

type Spec

type Spec[A any] struct {
	Name    string
	Write   bool
	Timeout time.Duration // required, at most 2 h
	// WhileAwaiting marks net.confirm and net.revert: the only commands that run while a run awaits
	// confirmation, and only when args.run_id is that run's id. They must be Write commands
	// and take a run_id field in A. A write command without this flag gets 409 pending_confirm
	// while a run waits; a WhileAwaiting command with no matching waiting run gets 412
	// not_awaiting_confirm and never runs. One such command runs at a time (a second gets busy).
	WhileAwaiting bool
	// Awaits marks net.apply: the only kind of command whose Run may return Awaiting. It must be a
	// Write command and cannot also be WhileAwaiting; an Awaiting from any other command fails the
	// run as invalid (command_failed).
	Awaits bool
	// Parks marks host.self_update: the only kind of command whose Run may return Parked. It
	// must be a Write command and cannot also be Awaits or WhileAwaiting; a Parked from any other
	// command fails the run as invalid (command_failed).
	Parks bool
	// MaxBody is the largest request body in bytes; 0 means 512 KiB, at most 4 MiB.
	MaxBody int64
	// Validate checks the decoded args; return Invalid(...) for field errors. May be nil for no args.
	Validate func(*A) error
	// Check runs the cheap preconditions synchronously (five seconds at most) before the run starts.
	// It must only read: it must not change the system, because if it ignores its deadline the run
	// is failed but the write lock stays held until it returns. The one exception is container.pull:
	// it stores a newer verified release index even when it then refuses, so that a revocation
	// is not lost; that write is small and atomic, and is logged and audited (release_index_stored).
	// Return a *Refusal to refuse; the run is recorded as refused with the matching HTTP status.
	Check func(ctx context.Context, args A) error
	// Run does the work. It must obey ctx. Return nil error with a JSON-encodable result, an Awaiting
	// (the run waits for Settle and keeps the write lock), a Parked (the run stays running past the
	// process and keeps the write lock until SettleParked), a *Refusal, a *Failure, or any other error
	// (reported as command_failed without its text).
	Run func(ctx context.Context, rc *RunContext, args A) (any, error)
}

Spec describes a command; A is its args type (a struct of typed fields, or struct{} for none). Nothing in A may name a binary, an argv or a path: values reach argv only through the command's own code, after Validate (INV-2).

Directories

Path Synopsis
Package servertest starts a real host server on a temporary unix socket with an injected fake peer check, for tests of host/server, host/client and the host contract.
Package servertest starts a real host server on a temporary unix socket with an injected fake peer check, for tests of host/server, host/client and the host contract.

Jump to

Keyboard shortcuts

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