app

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MPL-2.0 Imports: 108 Imported by: 0

Documentation

Overview

Package app wires config, store, migrations, service, and the HTTP layer into the runnable subcommands.

Index

Constants

View Source
const (
	AutomaticUpgradeRefusedExitCode  = 23
	AutomaticUpgradeRestoredExitCode = 24
)

AutomaticUpgradeRefusedExitCode preserves a proven pre-mutation refusal through re-execution of an independently verified upgrade coordinator. AutomaticUpgradeRestoredExitCode is the same refusal after the source service was stopped and proven serving again, which costs an outage and is counted.

View Source
const AutomaticUpgradeRolledBackExitCode = 25

AutomaticUpgradeRolledBackExitCode is the exit of a verified target coordinator that rolled the database back and restarted the source.

View Source
const MinRestoreSchemaVersion = 16

MinRestoreSchemaVersion is the first schema that carries the restore state a restore has to write (migration 00016, pinned to the migration file by TestMinRestoreSchemaVersionMatchesTheMigration). An archive below it is refused by name rather than failing deep inside the load transaction with a missing column — the operator's fix is "restore it with the binary that took it", and an error has to be able to say so.

View Source
const SecurityMaintenanceConfigFormat = "hikyo.security-maintenance-config/v1"
View Source
const SecurityMaintenanceConfigPath = "/etc/hikyo/security-maintenance.json"

Variables

View Source
var ErrHybridPolicyClassicalCustody = errors.New("HIKYO_BACKUP_RECIPIENTS selects hybrid post-quantum backups, but the automatic upgrade custody identity is X25519 and would export, and retain, a classical archive of this data; refusing before any backup. Use the manual upgrade route with a hybrid recipient and a separately held hybrid identity: hikyo backup upgrade-export --recipient <hybrid recipient>, then the operator hikyo backup upgrade-drill --identity-file <hybrid identity> (see Backup and restore: Hybrid post-quantum recipients)")

ErrHybridPolicyClassicalCustody is the refusal described above.

View Source
var ErrPreparationAborted = errors.New("unattended preparation aborted before the live database was written")

ErrPreparationAborted marks a target whose journal says it stopped before the live database was written. The process stays up and idle, so the coordinator can ask it and put the source back; a retry here could cross "write-intent" first.

View Source
var Version = "dev"

Version is the build's version string, set from main's linker-stamped value. It is what /api/v1/meta advertises, so a client that refuses an operation above the server's API revision can name the version it refused.

Functions

func AdminUsage

func AdminUsage(w io.Writer)

AdminUsage is the frozen help text for the local-admin group.

func AuthComponents

func AuthComponents(cfg *config.Config) (crypto.PasswordParams, *admission.Limiter, error)

AuthComponents resolves the two authentication settings and, in doing so, runs two boot invariants that must fail fast rather than surface at the first login:

  • the Argon2id parameters are checked against the floor the human-auth ADR fixes, and the server refuses to start below it;
  • the admission budget must hold at least one verification plus the global headroom, so a configuration where one login cannot fit is a config error caught here, never a runtime surprise.

It deliberately does not build the service: the service holds the keyring, and the redaction analyzer bans key-bearing types from reaching a log call — so the caller assembles it and logs from these values instead.

func AutomaticUpgradeExitCode

func AutomaticUpgradeExitCode(err error) int

func AutomaticUpgradeHandoffError

func AutomaticUpgradeHandoffError(err error) error

AutomaticUpgradeHandoffError is only for the independently verified child, never an arbitrary host subprocess whose exit status may also be 23.

func BackupUsage

func BackupUsage(w io.Writer)

BackupUsage is the frozen help text for the export verb group.

func EscrowUsage

func EscrowUsage(w io.Writer)

EscrowUsage is the frozen help text for the escrow verb group.

func GenerateReleaseCompatibility

func GenerateReleaseCompatibility(ctx context.Context, request ReleaseCompatibilityRequest) ([]byte, error)

GenerateReleaseCompatibility applies actual embedded migrations to both scratch engines and uses the same canonical domain catalog inspector as boot.

func Logger

func Logger(dev bool) *slog.Logger

Logger builds the process logger: text in dev, JSON in production.

func RestoreUsage

func RestoreUsage(w io.Writer)

RestoreUsage is the frozen help text for the restore verb group.

func RunAdmin

func RunAdmin(ctx context.Context, cfg *config.Config, log *slog.Logger, args []string, stderr io.Writer,
	terminalSession *disclose.TerminalSession, terminalError error,
) error

RunAdmin dispatches the local-admin verb group.

func RunAutomaticUpgrade

func RunAutomaticUpgrade(ctx context.Context, args []string, out io.Writer, readPassword func(string) (string, error)) (err error)

RunAutomaticUpgrade is the root operator entrypoint. It is deliberately separate from the retired remotely callable updater and server boot path.

func RunBackup

func RunBackup(ctx context.Context, cfg *config.Config, log *slog.Logger, args []string, stderr io.Writer,
	terminalSession *disclose.TerminalSession, terminalError error,
) error

RunBackup dispatches the export verb group.

func RunEscrow

func RunEscrow(ctx context.Context, cfg *config.Config, _ *slog.Logger, args []string, out io.Writer, _ *disclose.TerminalSession, _ error) error

func RunMigrate

func RunMigrate(ctx context.Context, cfg *config.Config, log *slog.Logger) error

RunMigrate is `hikyo migrate`: explicit migration application. Loads no keyring (DDL only). Signed public evidence authorizes schema application; maintenance remains until the exact candidate boot proves hierarchy health.

func RunRestore

func RunRestore(ctx context.Context, cfg *config.Config, log *slog.Logger, args []string, stderr io.Writer,
	_ *disclose.TerminalSession, _ error,
) error

RunRestore dispatches the restore verb group.

func RunSecurityFeed

func RunSecurityFeed(ctx context.Context, args []string, out io.Writer) error

RunSecurityFeed performs explicit local feed-authoring operations. Release verification is independently anchored in the current binary's build stamp; feed signing keys cannot substitute release execution authority.

func RunSecurityMaintenance

func RunSecurityMaintenance(ctx context.Context, args []string, out io.Writer) error

RunSecurityMaintenance is a separate local operator role. It never grants the serving process workload-control authority and never revives remote apply.

func RunSecurityUpgrade

func RunSecurityUpgrade(ctx context.Context, target releaseidentity.Identity, configuration string, out io.Writer) error

RunSecurityUpgrade runs the native coordinator for an independently selected exact release. The selection is a claim, not artifact authority: the normal release verifier, compatibility route and recovery gates still apply. Legacy passphrase custody requires an explicit one-time operator migration. AutomaticHandoff is returned to the command owner for trusted re-execution.

func RunUnattendedUpgrade

func RunUnattendedUpgrade(ctx context.Context, cfg *config.Config, options UnattendedUpgradeOptions) (cleanup func() error, err error)

RunUnattendedUpgrade prepares the exact running image before ordinary Boot. It never selects latest, replaces the image executable or contacts Docker. The caller retains cleanup until server shutdown to serialize replacements sharing the installation's persistent upgrade directory.

func RunUpgradeBackup

func RunUpgradeBackup(ctx context.Context, cfg *config.Config, args []string, out io.Writer, trust TrustContext) error

func RunUpgradeOperator

func RunUpgradeOperator(ctx context.Context, cfg *config.Config, args []string, out io.Writer) error

RunUpgradeOperator is local-only administration. It must dispatch before server initialization, admission, listeners and ordinary root-key configuration.

func SecurityFeedUsage

func SecurityFeedUsage(out io.Writer)

SecurityFeedUsage describes local authoring and signing operations. None of them uploads a feed, enrolls an installation or activates a production root.

func SecurityMaintenanceUsage

func SecurityMaintenanceUsage(out io.Writer)

Types

type AutomaticHandoff

type AutomaticHandoff struct {
	Executable string
	Arguments  []string
}

AutomaticHandoff asks the entrypoint to run the authenticated target's own coordinator. The current service executable has not been changed at this point.

func (*AutomaticHandoff) Error

func (e *AutomaticHandoff) Error() string

type LeaseManager

type LeaseManager interface {
	// Now is the datastore clock. All lease-time comparisons read time from
	// here so every node shares one clock, removing per-node skew as a
	// split-brain vector.
	Now(ctx context.Context) (time.Time, error)
	// A nonzero fence returned alongside an error is provisional: it may
	// only be confirmed by RenewLease or cleaned up by exact ReleaseLease.
	ClaimLease(ctx context.Context, name, owner string, now, expires time.Time) (fence int64, held bool, err error)
	RenewLease(ctx context.Context, name, owner string, fence int64, now, expires time.Time) (held bool, err error)
	ReleaseLease(ctx context.Context, name, owner string, fence int64) error
}

LeaseManager is the fenced singleton lease the scheduler uses under HA. It is satisfied by *store.Coordination; the scheduler depends on the interface so the app layer never needs a datastore-typed field.

type ReleaseCompatibilityRequest

type ReleaseCompatibilityRequest struct {
	Profile       releaseidentity.Profile
	Version       string
	Sequence      uint64
	Commit        string
	Sources       map[releaseidentity.Engine][]upgradecompat.SourceEdge
	PostgreSQLDSN string
}

ReleaseCompatibilityRequest is build tooling input, never runtime admission. Sources come from a reviewed source-owned declaration. PostgreSQLDSN must identify an isolated empty scratch database; nonempty targets refuse writes.

type ScheduledJob

type ScheduledJob struct {
	Name        string
	Run         func(context.Context) error
	LastSuccess func(context.Context) (time.Time, bool, error)
}

ScheduledJob is one bounded background operation. LastSuccess reads the job's persisted health marker; nil means the job has no staleness contract.

type Scheduler

type Scheduler struct {
	Jobs     []ScheduledJob
	Interval time.Duration
	Deadline time.Duration
	Log      *slog.Logger
	Now      func() time.Time

	// Lease, NodeID, LeaseTTL, and Heartbeat drive HA leadership. When Lease
	// is nil the scheduler is single-node and always runs its jobs (v1
	// behaviour, unchanged). When set, jobs run only while this node holds the
	// scheduler lease, so every singleton executes at most once across the
	// cluster and a stale leader that loses the lease has its in-flight jobs
	// cancelled. Its term identity also travels in the job context: tx.Write
	// locks and validates that fence before mutation, so a paused leader cannot
	// commit after takeover even before cancellation reaches it.
	Lease     LeaseManager
	NodeID    string
	LeaseTTL  time.Duration
	Heartbeat time.Duration

	// OnTick runs on every heartbeat on every node, leader or not. HA uses it
	// to refresh this node's registry heartbeat (so nodes_seen stays accurate
	// on standbys) and to sweep expired admission windows. Nil is a no-op.
	OnTick func(context.Context)
	// contains filtered or unexported fields
}

Scheduler runs every registered job once on startup and then hourly. Jobs share no transaction or deadline, so one failure cannot roll back another or silently disable future ticks.

func (*Scheduler) IsLeader

func (s *Scheduler) IsLeader() bool

IsLeader reports whether this node currently holds the scheduler lease. A single-node scheduler is always the leader. Health and /metrics read it for the hikyo_ha_is_leader gauge.

func (*Scheduler) Run

func (s *Scheduler) Run(ctx context.Context)

Run blocks until cancellation. Without a lease it is the single-node loop: a startup catch-up run then the interval tick. With a lease it runs the HA leadership loop instead.

type SecurityFeedConfiguration

type SecurityFeedConfiguration struct {
	MetadataURL      string `json:"metadata_url"`
	TargetsURL       string `json:"targets_url"`
	RootFile         string `json:"root_file"`
	OfflineDirectory string `json:"offline_directory,omitempty"`
}

type SecurityMaintenanceConfiguration

type SecurityMaintenanceConfiguration struct {
	Format         string                     `json:"format"`
	StateDirectory string                     `json:"state_directory"`
	Feed           SecurityFeedConfiguration  `json:"feed"`
	Policy         securitymaintenance.Policy `json:"policy"`
	Kind           string                     `json:"kind"`
	NativeConfig   string                     `json:"native_config,omitempty"`
	// TimeoutSeconds is how long a native replacement may stay unfinished before a later
	// run stops and rolls it back (default 30 minutes, at most 24 hours). It must fit the
	// installation's largest migration. The other kinds set theirs under deployment.
	TimeoutSeconds int                        `json:"timeout_seconds,omitempty"`
	Deployment     *securitydeployment.Config `json:"deployment,omitempty"`
	// StatusFile optionally publishes a public status subset for the serving
	// application to read. It must not be inside the private state directory.
	StatusFile string `json:"status_file,omitempty"`
}

SecurityMaintenanceConfiguration is installation-owned authority, never downloaded metadata. The serving application does not load it or its tokens.

func (SecurityMaintenanceConfiguration) Validate

type Server

type Server struct {
	Maintenance     bool
	Addr            string
	OperationalAddr string
	CLISocket       string
	// contains filtered or unexported fields
}

Server is a booted, listening server that has not started serving yet.

func Boot

func Boot(ctx context.Context, cfg *config.Config, log *slog.Logger) (*Server, error)

Boot runs the fail-closed startup sequence: process hardening before any key material exists, migrations (auto-apply by default; with auto-apply disabled a pending migration state refuses to serve), datastore open with the boot-enforced pragma policy, keyring load (root key read, master key unwrapped or minted, root key zeroed), then the listener. Any error means the process must exit without serving.

func (*Server) Close

func (s *Server) Close() error

Close releases resources for a booted server that never served.

func (*Server) ReloadTLS

func (s *Server) ReloadTLS() error

ReloadTLS preserves the applied managed certificate when SIGHUP is received.

func (*Server) ServeWithReady

func (s *Server) ServeWithReady(ctx context.Context, ready func()) error

Serve blocks until ctx is cancelled, then shuts down gracefully. ServeWithReady runs both HTTP serving goroutines and calls ready (when non-nil) after they have started. The command uses the ready hook to present an accurate startup summary without teaching the application package about terminal output; tests pass nil.

type Status

type Status = service.Status

Status is service.Status, aliased so the printer's signature does not drag the service package into every caller's head.

type TrustContext

type TrustContext struct {
	BundleDirectory string
	Pinned          releasetrust.PinnedTrust
	Target          releaseidentity.Identity
	Floor           releaseidentity.SnapshotFloor
	OperatorPin     backupreceipt.PinnedOperator
}

TrustContext is supplied by the shared build/installation gate. No CLI flag can substitute a root, target identity, floor or current operator pin.

type UnattendedUpgradeOptions

type UnattendedUpgradeOptions struct {
	Progress func(string)
	// PreparedConfiguration runs outside the migration lock. It may start the
	// public maintenance listener using only authenticated effective transport.
	PreparedConfiguration func(*config.Config) error
}

type UpgradeDrillRequest

type UpgradeDrillRequest struct {
	Scratch    store.Config
	Ciphertext *backupreceipt.Ciphertext
	Receipt    []byte
	Plan       upgradecompat.Plan
	Operator   backupreceipt.PinnedOperator
	Unlock     backup.Unlock
	RootKey    []byte
	Principal  domain.PrincipalID
	Scope      domain.Scope
	Now        time.Time
	Lifetime   time.Duration
	// AutoCredentialProof selects one existing authorized principal only in
	// this isolated scratch restore. Ordinary manual drills remain explicit.
	AutoCredentialProof bool
}

type UpgradeDrillResult

type UpgradeDrillResult struct {
	Attestation       []byte
	HierarchyReadable bool
	SecretProof       string
	CredentialProof   string
}

UpgradeDrillResult contains public proof outcomes and an unsigned statement. Signing occurs only after this function has performed the actual recovery.

func DrillUpgrade

func DrillUpgrade(ctx context.Context, request UpgradeDrillRequest) (UpgradeDrillResult, error)

DrillUpgrade is a local operator operation. It consumes separately supplied root escrow, decrypts a pinned copy in full, restores an empty scratch target, proves the existing hierarchy and never writes private custody to a server.

type UpgradeWindow

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

UpgradeWindow owns temporary listeners while the unattended coordinator holds tenant serving closed. Start accepts authenticated effective configuration, never unvalidated bootstrap transport settings.

func NewUpgradeWindow

func NewUpgradeWindow() *UpgradeWindow

func (*UpgradeWindow) Close

func (u *UpgradeWindow) Close() error

func (*UpgradeWindow) Progress

func (u *UpgradeWindow) Progress(phase string)

func (*UpgradeWindow) RuntimeStatus

func (u *UpgradeWindow) RuntimeStatus(context.Context) (service.RuntimeStatus, error)

func (*UpgradeWindow) Start

func (u *UpgradeWindow) Start(cfg *config.Config) error

func (*UpgradeWindow) Started

func (u *UpgradeWindow) Started() bool

func (*UpgradeWindow) Wait

func (u *UpgradeWindow) Wait(ctx context.Context) error

Jump to

Keyboard shortcuts

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