Documentation
¶
Overview ¶
Package updatestate owns the on-disk self-update layout: version directories, state.json, the updater lock and the bootstrap's run records.
<install root>\versions\<v>\ immutable once renamed in
<install root>\versions\.staging-<v>-*\ never executed
<install root>\seed\<msi-ver>\ MSI-owned fallback payload
<install root>\state\{state.json,update.lock,update.log}
<data root>\runs\<v>.json user-writable, advisory only
Index ¶
- Constants
- Variables
- func AppendRun(path string, r RunRecord) error
- func BootstrapRoot(exePath string, exists func(string) bool) (string, bool)
- func Compare(a, b Version) int
- func DataRoot() string
- func EnsureProtectedDir(path string) (fixed bool, err error)
- func FileSHA256(path string) (string, error)
- func FinalizeRun(path, runID string, exitCode int, watchdogKilled bool, at time.Time) error
- func IsSweepable(name string) bool
- func LoadReason(found bool, corrupt bool, err error) string
- func MarkRunStarted(path, runID string) error
- func MarkRunStartedLocked(path, runID string, wait time.Duration) error
- func MaxRunSeq(path string) int
- func RenameBlocked(err error) bool
- func RenameDir(src, dst string) error
- func ResolveInstallRoot(exePath string) (string, error)
- func RunLockPath(runFile string) string
- func Save(path string, st *State) error
- func SaveCheckpointed(path string, st *State, prefix string) error
- func SaveUpdaterRecord(path, prefix string, fn func(version string, failures int) (string, int)) error
- func StateGeneration(path string) (uint64, bool)
- func SweepStaleAdoptSnapshot(path string)
- func SweepTemps(path string)
- func VerifyVersionDir(dir string, v Version) error
- func VersionDirComplete(dir string) error
- func VersionDirUsable(dir string) bool
- func WriteAdoptSnapshot(path string, s *AdoptSnapshot) error
- func WriteManifest(dir string, m Manifest) error
- type AdoptSnapshot
- type Layout
- func (l Layout) AdoptSeedRule(st *State, seed Version, now time.Time) (changed bool, why string)
- func (l Layout) AdoptSnapshotFile() string
- func (l Layout) CheckVersionDir(s string) (Version, string)
- func (l Layout) CopySeedVersion(v Version, now time.Time, verifyPublisher func(path string) error) (string, error)
- func (l Layout) FindSeed() (Version, bool)
- func (l Layout) LockFile() string
- func (l Layout) LogFile() string
- func (l Layout) MSIHelperFile() string
- func (l Layout) MSIOwnedFiles() []string
- func (l Layout) RunFile(v Version) string
- func (l Layout) RunLockFile(v Version) string
- func (l Layout) RunsDir() string
- func (l Layout) SeedDir(v Version) string
- func (l Layout) StagingDir(v Version) (string, error)
- func (l Layout) StateDir() string
- func (l Layout) StateFile() string
- func (l Layout) VersionDir(v Version) string
- func (l Layout) VersionsDir() string
- type Lock
- type Manifest
- type OutboxEvent
- type Pointers
- type Probation
- type Quarantine
- type Restage
- type RunChoice
- type RunRecord
- type RunVerdict
- type State
- type Updater
- type Version
Constants ¶
const ( // ManifestName is the per-version manifest written before the rename in. ManifestName = "manifest.json" // StagingPrefix and TrashPrefix name entries of VersionsDir that S1 sweeps. StagingPrefix = ".staging-" TrashPrefix = ".trash-" )
const ( AgentFile = "stepsecurity-dev-machine-guard.exe" LauncherFile = "stepsecurity-dev-machine-guard-task.exe" LinuxFile = "dmg-linux" )
Files of a version directory. They keep their release names so the launcher finds the agent beside itself (internal/launcher.AgentBinary) and the WSL scan finds dmg-linux beside the agent, unchanged.
const ( FallbackStateMissing = "state_missing" FallbackStateCorrupt = "state_corrupt" FallbackStateUnreadable = "state_unreadable" FallbackCurrentMissing = "current_missing" FallbackCurrentIncomplete = "current_incomplete" FallbackStartFailed = "start_failed" FallbackUpdaterFailed = "updater_failed" FallbackNoUpdater = "no_confirmed_updater" FallbackNothingRunnable = "no_runnable_version" )
Fallback reasons for the bootstrap's EnvBootstrapFallback. Reasons about a named version carry it after a colon (current_missing:1.20.0) so the agent can report update_pointer_invalid with update_from = that version.
const AdoptSnapshotMaxAge = time.Hour
AdoptSnapshotMaxAge bounds how long an adopt-seed snapshot is honoured: an MSI transaction is far shorter, so an older one belongs to an MSI that ended without its commit or rollback action and is swept, never applied.
const BootstrapFile = "stepsecurity-dev-machine-guard-bootstrap.exe"
BootstrapFile is the MSI-owned stable entry point in the install root.
const MaxRunRecords = 10
MaxRunRecords is how many run records a runs\<v>.json keeps.
const SchemaVersion = 1
SchemaVersion is the state.json schema this package writes. A file with a higher schema is read for its known fields and written back with its own schema number and unknown keys intact.
Variables ¶
var ErrIncomplete = errors.New("updatestate: version directory incomplete")
ErrIncomplete means a version directory lacks a file or its manifest.
var ErrLocked = errors.New("updatestate: update lock held by another process")
ErrLocked means another process holds the update lock.
var ErrNoOpenRun = errors.New("updatestate: no open run record")
ErrNoOpenRun means the run file has no unfinalized record with that run_id.
var ErrNotRecordable = errors.New("updatestate: state not recordable by this build")
ErrNotRecordable means SaveUpdaterRecord found no state it may patch: the file is missing or its pointers (schema/current/previous) are unreadable.
var ErrRunID = errors.New("updatestate: run record needs a unique run_id")
ErrRunID means AppendRun got an empty run_id or one already in the file; such a record could never be finalized by its own launch.
var ErrUnsafeRoot = errors.New("untrusted install root")
ErrUnsafeRoot means a binary's install root can't be trusted as an MSI install root: no bootstrap in it, or users can write it.
var VersionFiles = []string{AgentFile, LauncherFile, LinuxFile}
VersionFiles lists every file a complete version directory holds besides its manifest.
Functions ¶
func BootstrapRoot ¶
BootstrapRoot returns the install root of the MSI bootstrap install that the binary at exePath belongs to: its own directory (the bootstrap, or a legacy top-level agent) or, for a binary under seed\<v>\ or versions\<v>\, two levels up. ok is false when no bootstrap sits in that root. This is the one rule for finding the root; exists reports whether a file exists.
func EnsureProtectedDir ¶
EnsureProtectedDir creates path if missing. Off Windows there is no protected-DACL model to enforce, so it never reports drift.
func FileSHA256 ¶
FileSHA256 returns the lowercase hex sha256 of a file.
func FinalizeRun ¶
FinalizeRun closes the open record runID.
func IsSweepable ¶
IsSweepable reports whether a VersionsDir entry is staging or trash.
func LoadReason ¶
LoadReason maps a LoadPointers/Load result to a fallback reason, "" when a state was read.
func MarkRunStarted ¶
MarkRunStarted sets the started marker on the open record runID.
func MarkRunStartedLocked ¶
MarkRunStartedLocked is the agent's MarkRunStarted under the run-record lock the bootstrap takes for AppendRun/FinalizeRun (RunLockPath), waiting at most wait. On timeout it returns an error without writing; callers skip the marker and never fail the scan.
func MaxRunSeq ¶
MaxRunSeq is the highest sequence number assigned in a run file (0 when none). The updater records it at a switch as the probation's start.
func RenameBlocked ¶ added in v1.19.0
RenameBlocked reports whether err is a rename RenameDir gave up on because an open handle kept blocking it.
func RenameDir ¶ added in v1.19.0
RenameDir renames a directory, retrying while another process's open handle blocks it: on Windows an AV/EDR scanning a freshly written executable holds it without FILE_SHARE_DELETE, and the rename of its directory fails with ERROR_ACCESS_DENIED until the scan ends. Other errors are returned at once.
func ResolveInstallRoot ¶
ResolveInstallRoot returns the install root of the binary at exePath (BootstrapRoot) after checking users can't write it. A SYSTEM process must never trust a root it can't vouch for, so there is no fallback.
func RunLockPath ¶
RunLockPath is the lock beside a run file (runs\<v>.json.lock) that every read-modify-write of it takes: the bootstrap's AppendRun/FinalizeRun (via Layout.RunLockFile) and the agent's MarkRunStartedLocked.
func Save ¶
Save atomically replaces state.json with st (schema set to 1). It refuses a state that Load would reject. After a crash at any point, Load returns either the old or the new state.
func SaveCheckpointed ¶
SaveCheckpointed writes st with Generation+1 (and sets st.Generation on success). It is Save with fault checkpoints <prefix>.state-temp (temp file durable, target untouched) and <prefix>.state-renamed (target replaced), e.g. prefix "S6", "rollback" or "adopt". An empty prefix disables them. An injected error at state-renamed is returned although the new state is already in place, as a late write error would be.
func SaveUpdaterRecord ¶
func SaveUpdaterRecord(path, prefix string, fn func(version string, failures int) (string, int)) error
SaveUpdaterRecord rewrites only state.updater.{version,consecutive_failures} via fn, through the same tolerant read as LoadPointers (D18): every other byte of the file, including values this build's Load would reject and unknown keys inside updater, is kept. Written atomically with checkpoints <prefix>.state-temp / <prefix>.state-renamed. Call it with the update lock held.
func StateGeneration ¶
StateGeneration reads state.json's generation without full validation (0 when absent).
func SweepStaleAdoptSnapshot ¶
func SweepStaleAdoptSnapshot(path string)
SweepStaleAdoptSnapshot removes a snapshot older than AdoptSnapshotMaxAge (or unreadable). Callers hold the update lock.
func SweepTemps ¶
func SweepTemps(path string)
SweepTemps removes temp files that a killed writer left beside path. Call it only while holding the update lock, so no live writer is affected.
func VerifyVersionDir ¶
VerifyVersionDir checks that dir is a complete version v whose files match the manifest hashes.
func VersionDirComplete ¶
VersionDirComplete is the updater's cheap integrity check: every VersionFiles entry and the manifest exist as regular files. It does not hash. (VersionDirUsable is the bootstrap's narrower launchability check: agent and launcher only, no manifest.)
func VersionDirUsable ¶
VersionDirUsable reports whether dir holds LauncherFile and AgentFile as non-empty regular files: what the bootstrap needs to launch a version. It is file presence only; integrity is the updater's manifest check (VerifyVersionDir), not the bootstrap's.
func WriteAdoptSnapshot ¶
func WriteAdoptSnapshot(path string, s *AdoptSnapshot) error
WriteAdoptSnapshot writes s atomically.
func WriteManifest ¶
WriteManifest atomically writes dir\manifest.json.
Types ¶
type AdoptSnapshot ¶
type AdoptSnapshot struct {
Seed string `json:"seed"`
StatePresent bool `json:"state_present"`
State []byte `json:"state,omitempty"` // state.json bytes before adopt-seed
CreatedDir bool `json:"created_dir"` // adopt-seed created versions\<seed>
// AfterGeneration is the generation adopt-seed wrote; nil when it left
// state.json unchanged. A rollback restores state only while the file
// still carries it (nobody wrote since).
AfterGeneration *uint64 `json:"after_generation,omitempty"`
}
AdoptSnapshot is what adopt-seed recorded before changing anything, so the MSI's rollback action can undo it if the transaction fails.
func ReadAdoptSnapshot ¶
func ReadAdoptSnapshot(path string) (*AdoptSnapshot, time.Duration, error)
ReadAdoptSnapshot returns the snapshot and its age by file time; a missing file is (nil, 0, nil).
type Layout ¶
Layout resolves every self-update path from an install root (versions, seed, state) and a data root (runs). Production code derives it from the running binary (ResolveLayout); nothing hard-codes the MSI's folders.
func ResolveLayout ¶
ResolveLayout is the MSI layout of the binary at exePath: the install root from ResolveInstallRoot and the data root from DataRoot.
func (Layout) AdoptSeedRule ¶
AdoptSeedRule applies seed adoption to an existing state in memory: current = seed when current's dir is unusable, or when the seed is newer than current and not under an unexpired quarantine (previous = the old current, and the old current's probation ends). An MSI never downgrades a self-updated device. It reports whether st changed and why.
func (Layout) AdoptSnapshotFile ¶
AdoptSnapshotFile is state\adopt-snapshot.json.
func (Layout) CheckVersionDir ¶
CheckVersionDir validates versions\<s>\ and returns its version, or the fallback reason (current_missing / current_incomplete) it is unusable.
func (Layout) CopySeedVersion ¶
func (l Layout) CopySeedVersion(v Version, now time.Time, verifyPublisher func(path string) error) (string, error)
CopySeedVersion copies seed\<v> into versions\<v> through a staging dir after the seed's agent and launcher pass verifyPublisher, checks every copied file against the source's sha256 and size taken before the copy, writes its manifest (so the updater treats it as a verified version) and renames it into place. A dir that already verifies is kept (immutable); anything else at that path is moved to trash first. Used by the MSI's adopt-seed and by the updater; the caller holds the update lock. It returns a note for the log ("" when nothing was copied).
func (Layout) MSIHelperFile ¶
MSIHelperFile is the copy of the bootstrap the MSI's stop-for-msi action runs (state\msi\…): not an MSI file, so the action's own image never holds a file the MSI is about to replace.
func (Layout) MSIOwnedFiles ¶
MSIOwnedFiles lists the files Windows Installer replaces or removes: the bootstrap and every file under seed\. Nothing may hold them open when the MSI's file actions run (D29), or the change needs a reboot.
func (Layout) RunLockFile ¶
RunLockFile is the lock beside runs\<v>.json that every read-modify-write of that file takes (R-B-2): the bootstrap's AppendRun/FinalizeRun and the agent's MarkRunStarted, so overlapping scan tasks never lose a record.
func (Layout) StagingDir ¶
StagingDir creates a fresh versions\.staging-<v>-<rand> directory. It sits in VersionsDir (which must exist) so the final rename stays on one volume.
func (Layout) VersionDir ¶
func (Layout) VersionsDir ¶
type Lock ¶
type Lock struct {
// contains filtered or unexported fields
}
Lock is an OS-owned exclusive lock that the kernel releases when the holder dies. The lock file is never removed: every contender must lock the same file.
func AcquireLock ¶
AcquireLock takes the lock without blocking; it returns ErrLocked when another process holds it.
type Manifest ¶
type Manifest struct {
Schema int `json:"schema"`
Version string `json:"version"`
Files map[string]string `json:"files"` // file name -> lowercase hex sha256
}
Manifest is versions\<v>\manifest.json: the sha256 of every file, written (and fsynced) before the directory is renamed into place.
func ReadManifest ¶
ReadManifest reads dir\manifest.json.
type OutboxEvent ¶
type OutboxEvent struct {
ExecutionID string `json:"execution_id"`
Event string `json:"update_event"`
From string `json:"update_from,omitempty"`
To string `json:"update_to,omitempty"`
Error string `json:"error_message,omitempty"`
At time.Time `json:"at"`
// Attempts and NextAttempt implement the retry backoff.
Attempts int `json:"attempts,omitempty"`
NextAttempt time.Time `json:"next_attempt,omitzero"`
Extra map[string]json.RawMessage `json:"-"` // unknown keys, kept on Save
}
OutboxEvent is a pending update event (spec Contracts: Update event).
func (OutboxEvent) MarshalJSON ¶
func (o OutboxEvent) MarshalJSON() ([]byte, error)
func (*OutboxEvent) UnmarshalJSON ¶
func (o *OutboxEvent) UnmarshalJSON(b []byte) error
type Pointers ¶
type Pointers struct {
Schema int
Current string
Previous string
Probation string // probation version, "" when none (schema 1 only)
// Updater bookkeeping (schema 1 only).
UpdaterVersion string
UpdaterFailures int
}
Pointers is the frozen bootstrap read contract of state.json: the fields every bootstrap, including the first one ever shipped, must keep reading. Probation and Updater are only filled for schema 1; a higher schema is read as current/previous only and never as corrupt.
func LoadPointers ¶
LoadPointers reads state.json for the bootstrap through the frozen read contract (R-B-1): only schema (an integer >= 1), current (strict x.y.z) and previous (strict x.y.z, else dropped) decide whether the state is usable; no other field is validated, for any schema, so a future writer can change everything else without stranding first-generation bootstraps on the seed. Probation and updater are read best-effort, for any schema, for the update verb's selection: anything malformed there reads as absent, never corrupt. The (p, corrupt, err) contract matches Load.
type Probation ¶
type Probation struct {
Version string `json:"version"`
Since time.Time `json:"since"`
OK int `json:"ok"`
Bad int `json:"bad"`
SmokeOK bool `json:"smoke_ok"`
// SinceSeq is the run file's highest sequence number at the switch;
// runs with a higher seq belong to the probation (additive).
SinceSeq *int `json:"since_seq,omitempty"` // nil: an older probation (time rule)
// Ticks counts update ticks that evaluated this probation, so it closes
// even if the clock jumps (additive).
Ticks int `json:"ticks,omitempty"`
Extra map[string]json.RawMessage `json:"-"` // unknown keys, kept on Save
}
Probation tracks a newly switched-to version until it is confirmed or rolled back. OK and Bad count runs (Bad counts consecutive bad runs).
func (Probation) MarshalJSON ¶
func (*Probation) UnmarshalJSON ¶
type Quarantine ¶
type Quarantine struct {
Reason string `json:"reason"`
At time.Time `json:"at"`
// Until, when set, ends the quarantine (D5: inconclusive probation).
// Zero means permanent.
Until time.Time `json:"until,omitzero"`
Extra map[string]json.RawMessage `json:"-"` // unknown keys, kept on Save
}
func (Quarantine) MarshalJSON ¶
func (q Quarantine) MarshalJSON() ([]byte, error)
func (*Quarantine) UnmarshalJSON ¶
func (q *Quarantine) UnmarshalJSON(b []byte) error
type Restage ¶
type Restage struct {
Count int `json:"count"`
First time.Time `json:"first"`
Last time.Time `json:"last"`
}
Restage counts re-stagings of one version since First (Last: the latest).
type RunChoice ¶
type RunChoice struct {
Version Version
Dir string
Reason string // why this is not the state's current; "" when it is
}
RunChoice is one launchable directory in the bootstrap's run order.
func ResolveRunChain ¶
ResolveRunChain orders current → previous → seed, skipping unusable directories. p is the LoadPointers result (nil when missing or corrupt); stateReason is LoadReason of that load. Every choice after the state's current carries the reason current was not used.
type RunRecord ¶
type RunRecord struct {
RunID string `json:"run_id,omitempty"`
// Seq is the per-file launch sequence number (max+1 at append).
Seq int `json:"seq,omitempty"`
Version string `json:"version"`
// StartedAt is when the record was appended (the launch began).
StartedAt time.Time `json:"start,omitzero"`
// Abandoned marks an open record whose launch outlived any possible
// scan (its bootstrap died); it is Neutral and evicted first.
Abandoned bool `json:"abandoned,omitempty"`
// OwnerPID/OwnerStart identify the bootstrap process that owns an open
// record (its creation time guards against PID reuse); FirstSeen is
// when a writer first saw a record whose start time it couldn't trust.
OwnerPID int `json:"owner_pid,omitempty"`
OwnerStart time.Time `json:"owner_start,omitzero"`
FirstSeen time.Time `json:"first_seen,omitzero"`
ExecutionID string `json:"execution_id,omitempty"`
Started bool `json:"started"`
ExitCode *int `json:"exit_code,omitempty"`
WatchdogKilled bool `json:"watchdog_killed,omitempty"`
At time.Time `json:"at,omitzero"`
}
RunRecord is one bootstrap launch of a version. The bootstrap generates RunID, appends the record and passes STEPSEC_RUN_ID to the agent; the agent sets Started right after a successful run-status "started", and the bootstrap finalizes ExitCode, WatchdogKilled and At. Both updates match by RunID, so overlapping launches never touch each other's record. A nil ExitCode means not finalized yet.
type RunVerdict ¶
type RunVerdict int
RunVerdict is the health reading of one run record (spec §4).
const ( // RunOpen: not finalized (still running, or the bootstrap died). RunOpen RunVerdict = iota // RunHealthy: the started marker is set, no panic exit, no watchdog kill. RunHealthy // RunBad: a watchdog kill, exit code 2 (Go panic), or an exit before the // started marker with a crash-like code (anything but 0 or 1). RunBad // RunNeutral: exited 0 or 1 without the started marker. That is how the // agent ends when the backend is unreachable or another scan holds the // instance lock; spec §4 says environmental failures are not bad runs. RunNeutral )
func ClassifyRun ¶
func ClassifyRun(r RunRecord) RunVerdict
ClassifyRun applies the bad-run rule to one record.
type State ¶
type State struct {
Schema int `json:"schema"`
Current string `json:"current"`
Previous string `json:"previous"`
Probation *Probation `json:"probation"`
Quarantine map[string]Quarantine `json:"quarantine"`
Updater Updater `json:"updater"`
SwitchDeferrals int `json:"switch_deferrals"`
Dedupe map[string]time.Time `json:"dedupe"`
// Generation is incremented by every Save. After a write error, a
// re-read showing the expected generation proves the write landed.
Generation uint64 `json:"generation,omitempty"`
// LastCheck is when the updater last asked latest-binary for a target.
LastCheck time.Time `json:"last_check,omitzero"`
// Outbox holds update events not yet accepted by the backend. Events
// are added in the same atomic write as the state change they report.
Outbox []OutboxEvent `json:"outbox,omitempty"`
// SmokeTimeouts counts consecutive smoke-test timeouts per version; the
// third quarantines it (a timeout alone is retried).
SmokeTimeouts map[string]int `json:"smoke_timeouts,omitempty"`
// Restages counts re-stagings of a version whose dir was damaged (an AV
// deleting a file); RestageBackoff pauses them (version -> until).
Restages map[string]Restage `json:"restages,omitempty"`
RestageBackoff map[string]time.Time `json:"restage_backoff,omitempty"`
// PendingSwitch is a staged target whose switch was deferred; its
// versions dir is kept and SwitchDeferrals counts for it alone.
PendingSwitch string `json:"pending_switch,omitempty"`
// OutboxDropped counts events dropped because the outbox was full.
OutboxDropped uint64 `json:"outbox_dropped,omitempty"`
// Extra holds keys this version doesn't know; Save writes them back.
Extra map[string]json.RawMessage `json:"-"`
}
State is state.json (schema 1, spec "Contracts"). Version fields hold strict x.y.z strings; Load guarantees they parse.
func Load ¶
Load reads state.json. A missing file returns (nil, false, nil). An unreadable-as-state file (bad JSON, unknown schema, invalid fields, oversize) returns (nil, true, nil): callers treat it as missing and report update_state_corrupt. err is set only for I/O failures other than absence.
func (State) MarshalJSON ¶
func (*State) UnmarshalJSON ¶
type Updater ¶
type Updater struct {
Version string `json:"version"`
ConsecutiveFailures int `json:"consecutive_failures"`
Extra map[string]json.RawMessage `json:"-"` // unknown keys, kept on Save
}
Updater records which version last ran the updater and how often in a row it failed, for the bootstrap's updater selection.
func (Updater) MarshalJSON ¶
func (*Updater) UnmarshalJSON ¶
type Version ¶
type Version struct{ Major, Minor, Patch uint32 }
Version is a strict x.y.z release version. Prereleases and build metadata are refused (spec §6).
func ParseVersion ¶
ParseVersion accepts only x.y.z with decimal components, no sign, no "v" prefix and no leading zeros.
func ResolveRunVersion ¶
ResolveRunVersion is the version a scan launched now would run for st (nil = missing or corrupt state), with the fallback reason ("" when it is st.Current). With nothing runnable it returns the zero Version and FallbackNothingRunnable.