state

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: Apache-2.0 Imports: 15 Imported by: 0 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 state owns the server-driven hook enable/disable cache.

Flow:

scheduled tick / install  ──▶  Reconciler.Reconcile
                                   │
                                   ├─ Fetcher.Fetch  (GET /developer-mdm-agent/features)
                                   ├─ cache.Write    (~/.stepsecurity/hooks-state.json)
                                   └─ InstallFn / UninstallFn  (idempotent)

_hook hot path  ──▶  cache.Read  ──▶  short-circuit to allow if disabled

The cache file is the single source of truth for the hot path. Both the polling reconciler (this package) and any future WebSocket transport are expected to converge on the same file, so the hot path never has to know which transport is active.

Defaults: cache missing or unparseable ⇒ Default() (enabled). Hot path is fail-open by contract; a corrupt cache must not break the agent.

Index

Constants

View Source
const (
	SourcePoll      = "poll"
	SourceManual    = "manual"
	SourceInstall   = "install"
	SourceWebsocket = "websocket" // reserved
)

Source values record where the cache write came from. Diagnostic only — the hot path never branches on Source.

View Source
const CacheFilename = "hooks-state.json"

CacheFilename is the basename of the cache file. Lives under ~/.stepsecurity/ alongside config.json and ai-agent-hook-errors.jsonl.

View Source
const DefaultFetchTimeout = 5 * time.Second

DefaultFetchTimeout caps a single Fetch round-trip. Matches ingest.DefaultHookUploadTimeout for consistency with the existing HTTP timeout budget; the reconciler runs off the scheduled tick, not the hot path, so a 5s ceiling is comfortable.

View Source
const FeatureKeyHooks = "ai_agents_hooks_install"

FeatureKeyHooks mirrors agent-api's DeveloperMDMFeatureAIAgentsHooksInstall. Constant in both repos must match for the toggle to plumb through.

View Source
const SchemaVersion = 1

SchemaVersion is the wire/disk version of the cache file. Bump only on a breaking shape change; older daemons keep parsing v1.

Variables

This section is empty.

Functions

func CachePath

func CachePath() string

CachePath returns the absolute cache path, honoring the test override when set.

func SetCachePathForTest

func SetCachePathForTest(p string) (restore func())

SetCachePathForTest redirects CachePath() to the given absolute path and returns a restore function. Test-only; production code never calls this. Living on the package surface (rather than as a build-tagged file) keeps cross-package tests in hook/* and main_test able to drive the override without an internal-import trick.

func Write

func Write(s State) error

Write atomically replaces the cache file. No backups are kept — the cache is rewritten on every reconcile tick, and orphaned backups would accumulate trash. Parent dir is created with 0o700.

Types

type FetchResult

type FetchResult struct {
	Enabled bool
}

FetchResult is what one successful Fetch resolves to. Today there is only a single toggle; future fields land here as the contract grows.

type Fetcher

type Fetcher interface {
	Fetch(ctx context.Context, customerID, deviceID string) (FetchResult, error)
}

Fetcher returns the desired feature state for one device.

type HTTPFetcher

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

HTTPFetcher is the production Fetcher. Safe for concurrent use; the underlying *http.Client owns connection state.

func NewHTTPFetcher

func NewHTTPFetcher(cfg ingest.Config, h *http.Client) (*HTTPFetcher, bool)

NewHTTPFetcher constructs a Fetcher from a strict enterprise config (the same gate the upload path uses). Returns ok=false when the config is incomplete — the caller treats nil as "skip reconcile", matching how upload disables itself in community mode.

func (*HTTPFetcher) Fetch

func (c *HTTPFetcher) Fetch(ctx context.Context, customerID, deviceID string) (FetchResult, error)

Fetch issues the GET against /developer-mdm-agent/features. Missing feature key in the response ⇒ Enabled=false (matches server-side baseline-disabled default; backend keeps unset features out of the map rather than emitting a zero entry).

type HookCommandFn

type HookCommandFn func(ctx context.Context, exec executor.Executor, agent string, stdout, stderr io.Writer) int

HookCommandFn is the install/uninstall seam shape. Production wires these to internal/aiagents/cli.RunInstall and .RunUninstall in main.go (state can't import cli without a cycle, so the seam stays a plain function type).

type Hooks

type Hooks struct {
	Enabled bool `json:"enabled"`
}

Hooks carries the feature toggles the hot path reads. Today there's only Enabled; per-agent granularity goes here when the contract grows.

type Reconciler

type Reconciler struct {
	Exec        executor.Executor
	Fetcher     Fetcher
	CustomerID  string
	DeviceID    string
	Agent       string // "" = every detected agent
	Stdout      io.Writer
	Stderr      io.Writer
	InstallFn   HookCommandFn
	UninstallFn HookCommandFn
	Now         func() time.Time
}

Reconciler turns a desired enable/disable into local actions. One instance per main.go call site; the struct holds the wiring and no per-call state.

func (*Reconciler) Reconcile

func (r *Reconciler) Reconcile(ctx context.Context) error

Reconcile fetches desired state, writes the cache, and converges settings to match by calling InstallFn / UninstallFn. Both are idempotent so we don't need to detect the current state — install is a no-op when entries are already in place, uninstall is a no-op when no DMG-owned entries exist.

Order: cache write first, then settings reconciliation. If the settings reconciliation fails, the cache still reflects the desired state — the hot path honors the new value immediately, and the next tick retries the settings change.

Errors are returned to the caller for logging via cli.AppendError; Reconcile itself never panics into the caller's hot path.

type State

type State struct {
	SchemaVersion int       `json:"schema_version"`
	FetchedAt     time.Time `json:"fetched_at"`
	Source        string    `json:"source,omitempty"`
	Hooks         Hooks     `json:"hooks"`
}

State is the on-disk cache shape. JSON keys are the wire format.

func Default

func Default() State

Default is the in-memory fallback for any read failure. Enabled is true: the hot path only runs because settings carry a DMG entry, so defaulting to disabled would silently turn off first-run after install (before the reconciler has had a chance to write the cache).

func Read

func Read() (State, bool)

Read returns (state, true) on a successful parse. Any I/O or parse error returns (Default(), false) — Read never surfaces an error because the hot path must remain fail-open.

Jump to

Keyboard shortcuts

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