adminsock

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 22 Imported by: ? modules, 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 adminsock is an application's admin socket: its operator commands (Family Hub's `hub admin …`) run inside the application process and are reached over a unix socket. Packages and the application add commands to one Registry; a Server serves them while the application runs, and CLI is the client side for the application's command line.

The registry

A Registry holds the commands by name. Any package adds its own with Registry.Add — package auth adds setup-link and reset-access when auth.Options.Admin is set, and an application adds its own (Family Hub: status, legacy keys, cloudflare connect, …):

reg := adminsock.NewRegistry()
a, err := auth.New(auth.Options{…, Admin: reg})              // setup-link, reset-access
err = reg.Add(adminsock.Command{Name: "status", Summary: "…", Run: status})
srv, err := adminsock.New(adminsock.Options{Path: "data/admin.sock", Logger: log, Registry: reg})
err = srv.Start(ctx); defer srv.Stop(ctx)

A name is one or more lower-case words ("setup-link", "legacy-key import"); "help" belongs to the CLI. Add refuses a bad or repeated name, or a command without Run, and then adds none of the commands it was given. Commands may be added before or after Start: the server looks them up per request.

Who may use it

The socket file is 0600 and the server also checks the peer's uid (SO_PEERCRED on Linux, LOCAL_PEERCRED on macOS; other platforms refuse every peer): only the application's own user and root get in, so a mode slip alone does not open it to others. Whoever gets in is the server operator: commands need no passkey, no session and no step-up.

That makes the socket exactly as strong as the uid boundary. In a container, or under a dedicated service user (Linux), the uid is the server alone. On a desktop where the application runs as the logged-in user, every program of that user gets in, and such a program can as well replace the application's binary or read its data dir, so no check of the socket alone would close that. What the server adds is a trace: each command's Invocation.Peer holds the peer's pid and executable path and who started it (Peer.Chain: up to three ancestors, since the peer is usually the application's own CLI), the log line of every command names them, and destructive commands (package auth's reset-access and setup-link) put them into their audit entries.

The wire

HTTP/1.1 over the socket:

GET  /v1/commands  → 200 [{"name","usage","summary","stdin"}]
POST /v1/run {"command","args","stdin"}
                   → 200 application/x-ndjson: one {"out":"…"} frame per write of the command, then a final
                     {"done":true} or {"error":"<code>","message":"…"} frame;
                     400 or 404 {"error":"<code>","message":"…"} when it cannot start

Output streams while the command runs, so a command can print a URL and wait for the operator (Family Hub's `cloudflare connect`). It goes to the operator's terminal only: the server never logs a command's arguments, standard input or output, only its name, its result code and how long it took.

Index

Constants

View Source
const (
	ExitOK     = 0
	ExitFailed = 1
	ExitUsage  = 2
)

Exit codes of CLI.Run.

View Source
const (
	// MaxStdin caps the standard input the CLI sends along for a command that reads it.
	MaxStdin = 64 << 10
)

Variables

View Source
var ErrUsage = errors.New("usage")

ErrUsage marks a command error the operator caused: wrong arguments. The CLI then exits with 2.

Functions

This section is empty.

Types

type CLI

type CLI struct {
	Socket string // the socket's path
	Prog   string // how the operator runs it, in usage lines and errors, e.g. "hub admin"; "" is "admin"
	App    string // what serves the socket, in errors, e.g. "hub"; "" is "server"
	Hint   string // a line printed when the socket does not answer; "" prints none
}

CLI is the operator's side of the socket, for the application's command line (Family Hub: `hub admin <args…>` is CLI{Socket: <data dir>/admin.sock, Prog: "hub admin", App: "hub", Hint: "Is the hub running? Run this inside its container."}.Run(…)).

func (CLI) Run

func (cli CLI) Run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) int

Run finds the command among the running server's (the longest name that the arguments start with), sends the remaining arguments and, for a command that reads it, the standard input; it streams the output to stdout and errors to stderr, and returns the exit code: ExitOK, ExitFailed or ExitUsage. No arguments, or "help", lists the commands.

type Client

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

Client talks to a running application over its admin socket.

func NewClient

func NewClient(path string) *Client

NewClient returns a client for the socket at path. It has no timeout of its own: commands may wait for the operator; cancel the context instead.

func (*Client) Commands

func (c *Client) Commands(ctx context.Context) ([]CommandInfo, error)

Commands lists the server's commands, sorted by name.

func (*Client) Run

func (c *Client) Run(ctx context.Context, name string, args []string, stdin []byte, out io.Writer) error

Run runs a command and copies its output to out as it arrives. A failure the server reports is a *RemoteError.

type Command

type Command struct {
	// Name is one or more lower-case words, e.g. "setup-link" or "legacy-key import".
	Name string
	// Usage shows the arguments after the name, e.g. "--module <id> --person <id> --label <label>".
	Usage string
	// Summary is one line for the CLI's help.
	Summary string
	// Stdin makes the CLI read its standard input (at most MaxStdin bytes) and send it along.
	Stdin bool
	// Run does the work. What it writes to inv.Out reaches the operator's terminal as it is written. An error ends
	// the command with its text as the message; errors wrapping ErrUsage, core.ErrConflict or core.ErrNotFound get
	// the codes invalid, conflict and not_found. Error texts are shown, never logged: keep secrets out of them anyway.
	Run func(ctx context.Context, inv Invocation) error
}

Command is one admin command.

type CommandInfo

type CommandInfo struct {
	Name    string `json:"name"`
	Usage   string `json:"usage,omitempty"`
	Summary string `json:"summary"`
	Stdin   bool   `json:"stdin,omitempty"`
}

CommandInfo describes a command to the CLI.

type Invocation

type Invocation struct {
	Args  []string  // the words after the command name; never nil
	Stdin []byte    // the CLI's standard input when Command.Stdin is set, else nil
	Out   io.Writer // the operator's terminal; nothing written here is logged
	Peer  Peer      // the process that connected; the zero Peer when unknown (Handler without the socket)
}

Invocation is one run of a command.

type Options

type Options struct {
	// Path is the socket file, at most 103 bytes (macOS's sun_path). Its directory is made 0700 when missing.
	Path string
	// Logger gets the server's own lines; nil discards.
	Logger *slog.Logger
	// Registry holds the commands; nil serves an empty one (Server.Registry returns it).
	Registry *Registry
}

Options is what New needs.

type Peer added in v0.2.0

type Peer struct {
	UID int    // the peer's user id
	PID int    // the peer's process id; 0 when unknown
	Exe string // the absolute path of the peer's executable; "" when unknown
	// Chain names who started the peer: up to three of its ancestors, nearest first, each "<exe> (pid N)" joined by
	// " < ", e.g. "/bin/zsh (pid 41) < login (pid 40) < /…/Terminal (pid 12)". The peer is usually the application's
	// own CLI, so this is the part that tells who asked. An ancestor whose executable the kernel does not show (one of
	// another user) is named by its short command name; one that cannot be read ends the chain. "" when unknown.
	Chain string
}

Peer is the process on the other end of the socket, as the kernel named it when it connected (SO_PEERCRED on Linux; LOCAL_PEERCRED and LOCAL_PEERPID on macOS). Only UID decides who gets in; PID, Exe and Chain are for the audit and the log (who ran a destructive command), never for access: the process may have exited since and its pid been reused, and a process of the same user can be any program.

type Registry

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

Registry is the set of commands a Server serves. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) Add

func (r *Registry) Add(cmds ...Command) error

Add checks the commands (names of lower-case words, unique here and among the registered ones, none called "help", a Run each) and registers them, all or none.

func (*Registry) Commands

func (r *Registry) Commands() []CommandInfo

Commands lists the registered commands, sorted by name; never nil.

type RemoteError

type RemoteError struct {
	Code    string // invalid, conflict, not_found, failed or internal
	Message string
}

RemoteError is a refusal or a failure the server reported for a command.

func (*RemoteError) Error

func (e *RemoteError) Error() string

type Server

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

Server serves a registry's commands on the socket.

func New

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

New checks the options and returns a server for the socket at o.Path. Start listens.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler serves the wire protocol; Start serves it on the socket. Tests use it directly.

func (*Server) Registry

func (s *Server) Registry() *Registry

Registry is the registry the server serves.

func (*Server) Start

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

Start listens on the socket (0600) and serves in the background. A socket file left by a process that is gone is replaced; one that still answers, or a path that is not a socket, is refused and left alone.

func (*Server) Stop

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

Stop cancels the running commands, closes the socket and removes its file.

Jump to

Keyboard shortcuts

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