telemetry

package
v1.19.0 Latest Latest
Warning

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

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

Index

Constants

View Source
const (
	InvocationInstall = "install"
	InvocationOneTime = "one_time"
)

Wire-format values for the invocation_method field. Kept stable — console and backend match on these literal strings.

View Source
const (
	EnvRunRecord         = "STEPSEC_RUN_RECORD"
	EnvRunID             = "STEPSEC_RUN_ID"
	EnvBootstrapVersion  = "STEPSEC_BOOTSTRAP_VERSION"
	EnvBootstrapFallback = "STEPSEC_BOOTSTRAP_FALLBACK"
)

Env set by the bootstrap for scan runs (spec Contracts: Run record).

View Source
const CurrentPayloadSchemaVersion = 1

CurrentPayloadSchemaVersion is bumped when the delta-protocol wire shape changes in a way the backend cares about. 0 = legacy agent.

View Source
const EnvMaxExecutionDuration = "STEPSEC_MAX_EXECUTION_DURATION"

EnvMaxExecutionDuration is an optional environment-variable override for the execution watchdog, honored ahead of config.json for ad-hoc/manual runs (e.g. `STEPSEC_MAX_EXECUTION_DURATION=3s ./binary send-telemetry`). The loader no longer exports it: the configured value is delivered through config.json (config.MaxExecutionDuration), which the binary reads on every invocation — including scheduler-fired runs (launchd/systemd/schtasks) that bypass the loader.

Variables

View Source
var ErrPanic = errors.New("panic in telemetry.Run")

ErrPanic wraps a panic Run recovered from. The process must still end as a crash (exit 2), or the self-update health check would count a crashing version as healthy (panic after run-status "started") or neutral.

View Source
var ErrUpdateEventRejected = errors.New("run-status rejected the update event")

ErrUpdateEventRejected means the backend answered 400/422: retrying the same event cannot help.

Functions

func DetectInvocationMethod added in v1.11.4

func DetectInvocationMethod(exec executor.Executor, log *progress.Logger) string

DetectInvocationMethod reports whether THIS run was triggered by the installed scheduler ("install") or started manually ("one_time").

A scheduler footprint on disk is necessary but not sufficient — a developer can run `send-telemetry` by hand on a machine that also has the scheduler installed, and the field/UI mean per-invocation (scheduled vs manual), not "is a scheduler installed." So when a footprint exists we consult the live job state: only when the scheduler job is CONFIRMED idle do we report a manual run; if it's running, or the probe is inconclusive, we keep "install" so a genuine scheduled run is never mislabeled. Best-effort and never errors.

func ExecutionDeadline added in v1.11.7

func ExecutionDeadline(configValue string) time.Duration

ExecutionDeadline resolves the whole-process execution deadline with env > config > default precedence. The env var (EnvMaxExecutionDuration) is an optional ad-hoc override; configValue is the value the loader/installer persists into config.json (config.MaxExecutionDuration), the primary channel — it covers every invocation, including scheduler-fired runs (launchd/systemd/schtasks) that invoke the binary directly. Each source uses the same contract as scanDeadlineFromEnv (scan_deadline.go):

  • "0" / "off": 0 (watchdog disabled; main.go skips arming)
  • any positive Go time.ParseDuration string ("2h", "30m", "45m30s"): that duration
  • empty or unparseable: fall through to the next source, then to defaultExecutionDeadline (a typo in an unattended launchd/schtasks/systemd context must not be fatal to the scan)

func ExecutionDeadlineFromEnv added in v1.11.7

func ExecutionDeadlineFromEnv() time.Duration

ExecutionDeadlineFromEnv resolves the execution deadline from the environment only. Equivalent to ExecutionDeadline(""); kept for callers (and tests) that have no config fallback to supply.

func ExitCode added in v1.18.0

func ExitCode(err error) int

ExitCode is the process exit code for Run's error: 2 for a recovered panic (the Go runtime's own panic code), 1 for any other failure.

func PostUpdateEvent added in v1.18.0

func PostUpdateEvent(ctx context.Context, client *http.Client, ev UpdateEvent) error

PostUpdateEvent posts ev with a small retry budget. agent_version is always this process's version. It returns nil only on a 2xx, and ErrUpdateEventRejected only for 400/422 (or an event that can't be valid).

func ReportFatal added in v1.18.0

func ReportFatal(reason string, timeout time.Duration)

ReportFatal posts the in-flight Run's failed run-status (sharing Run's once-only guard) and waits at most timeout. For exit paths that bypass Run's own handlers, e.g. the Windows execution watchdog, which has no signal to deliver. No-op when no Run is in flight.

func Run

func Run(exec executor.Executor, log *progress.Logger, cfg *cli.Config) (err error)

Run executes enterprise telemetry: scan, build payload, upload to S3. Output format matches the shell script's sample_log:

==========================================
StepSecurity Device Agent v1.9.1
==========================================
[scanning] Lock acquired (PID: 32560)
[scanning] Device ID (Serial): ...
...

Types

type ExecutionLogs

type ExecutionLogs struct {
	OutputBase64 string `json:"output_base64"`
	StartTime    int64  `json:"start_time"`
	EndTime      int64  `json:"end_time"`
	ExitCode     int    `json:"exit_code"`
	AgentVersion string `json:"agent_version"`
}

type LogCapture

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

LogCapture captures all stderr output during telemetry execution into a bounded ring buffer. The buffer's contents are exposed two ways:

  • Tail(n): the last n bytes, used by heartbeat posts to ship a fresh diagnostic slice on every progress upsert.
  • Finalize(): the entire current buffer, base64-encoded, embedded in the final ExecutionLogs payload.

Behavior change vs. previous unbounded bytes.Buffer: when a run produces more than captureRingCapacity bytes of log output (hours-long stuck runs, mainly), the OLDEST bytes are dropped and the final payload reflects only the most recent ~1 MB. That's a deliberate trade — the oldest output is rarely diagnostic for a hang, and the prior unbounded buffer could OOM the agent on a runaway scan.

Nesting with internal/progress/filelog: when filelog is active, os.Stderr is already the filelog pipe's write end. StartCapture saves that value as origErr, swaps os.Stderr to its own pipe, and on Finalize restores os.Stderr = origErr — re-enabling the filelog tee. Do not change Finalize to assign os.Stderr to the "real" stderr directly; that would orphan filelog mid-run and lose the suffix of the log file.

func StartCapture

func StartCapture() *LogCapture

StartCapture redirects stderr to a tee that writes to both the original stderr and an in-memory ring buffer for later base64 encoding.

func (*LogCapture) Finalize

func (lc *LogCapture) Finalize() string

Finalize stops capture and returns the base64-encoded output. Safe to call multiple times — subsequent calls return the cached result.

func (*LogCapture) Fprintf

func (lc *LogCapture) Fprintf(format string, args ...any)

Fprintf is a convenience method.

func (*LogCapture) Seed added in v1.13.0

func (lc *LogCapture) Seed(p []byte)

Seed writes pre-capture bytes directly into the ring buffer WITHOUT echoing them to the live stderr / agent.error.log. Used to fold in the loader script's earlier agent.log output so heartbeat tails and the final payload include it, even though it was logged before StartCapture redirected stderr. Call once, right after StartCapture and before any stderr output, so the seeded bytes sit at the head of the buffer.

func (*LogCapture) SnapshotBase64 added in v1.11.7

func (lc *LogCapture) SnapshotBase64() string

SnapshotBase64 returns the base64-encoded buffer contents WITHOUT stopping capture, so a caller can embed the session-so-far in the telemetry payload while the capture keeps recording (e.g. through the upload that follows). The real teardown — closing the pipe and restoring os.Stderr — stays in Finalize, which the caller still defers. Safe to call during active capture.

func (*LogCapture) Sync added in v1.14.0

func (lc *LogCapture) Sync()

Sync blocks until the tee goroutine has drained every byte written to the capture pipe before this call — i.e. everything logged so far is now in the ring and visible to a following SnapshotBase64/Tail. Unlike Finalize it does NOT stop capture: the pipe stays open, so later output (the upload result, the completion line) keeps being recorded for the run-status tail. It works by writing a unique marker to the pipe and waiting for the tee to read past it, which is the only reliable way to flush an asynchronous reader short of closing the pipe. Bounded by captureSyncTimeout so an absent or stuck tee cannot wedge the caller; on timeout the following snapshot simply reflects whatever had drained. No-op before StartCapture or after Finalize.

func (*LogCapture) Tail added in v1.11.7

func (lc *LogCapture) Tail(n int) []byte

Tail returns the last n captured bytes as a fresh slice. Safe to call concurrently with active capture; returns nil if the buffer is empty or n ≤ 0. Used by heartbeat posts to ship the most recent diagnostic slice without bloating the payload.

func (*LogCapture) Write

func (lc *LogCapture) Write(p []byte) (n int, err error)

Write allows direct writing to the capture buffer (for banner etc.) while also writing to stderr.

type Payload

type Payload struct {
	UserIDMissing   bool `json:"user_id_missing"`
	DeviceIDMissing bool `json:"device_id_missing"`
	// PayloadSchemaVersion gates the delta-protocol sibling fields below
	// (NodeProjectsUnchanged etc.). Zero/absent = legacy snapshot, every
	// scanned project ships its full body in NodeProjects/PythonProjects.
	PayloadSchemaVersion int                    `json:"payload_schema_version,omitempty"`
	CustomerID           string                 `json:"customer_id"`
	DeviceID             string                 `json:"device_id"`
	SerialNumber         string                 `json:"serial_number"`
	DeviceIDSource       string                 `json:"device_id_source,omitempty"`   // env | config | serial | wsl_guest
	DeviceIDTemplate     string                 `json:"device_id_template,omitempty"` // the template in force when it carries a token; "" for serial or literal ids
	DeviceTag            string                 `json:"device_tag"`                   // config.json device_tag; always present so the backend can tell "cleared" from "older agent"
	Virtualization       *model.Virtualization  `json:"virtualization,omitempty"`
	UserIdentity         string                 `json:"user_identity"`
	UserToken            string                 `json:"user_token,omitempty"` // the signed-in user's token (short name + fingerprint); the backend files this upload under that user of the device. "" for a service account
	Hostname             string                 `json:"hostname"`
	Platform             string                 `json:"platform"`
	OSVersion            string                 `json:"os_version"`
	Resources            model.MachineResources `json:"resources"`
	WSL                  *model.WSLInfo         `json:"wsl,omitempty"`
	WSLGuest             *model.WSLGuest        `json:"wsl_guest,omitempty"`
	AgentVersion         string                 `json:"agent_version"`
	CollectedAt          int64                  `json:"collected_at"`
	NoUserLoggedIn       bool                   `json:"no_user_logged_in"`

	// InvocationMethod is "install" when the agent ran from an installed
	// launchd/systemd/schtasks unit, "one_time" for a manual CLI run.
	// Duplicated on this struct (also lives on the run-status row) so the
	// stored telemetry record is self-describing for backfills.
	InvocationMethod string `json:"invocation_method,omitempty"`

	// StatusInfo carries the final phase completion list and total elapsed
	// time the agent saw at upload time. Snapshot of the same RunStatusInfo
	// streamed via the run-status endpoint during the run.
	StatusInfo *RunStatusInfo `json:"status_info,omitempty"`

	IDEExtensions        []model.Extension        `json:"ide_extensions"`
	IDEInstallations     []model.IDE              `json:"ide_installations"`
	NodePkgManagers      []model.PkgManager       `json:"node_package_managers"`
	NodeGlobalPackages   []model.NodeScanResult   `json:"node_global_packages"`
	NodeProjects         []model.NodeScanResult   `json:"node_projects"`
	BrewPkgManager       *model.PkgManager        `json:"brew_package_manager,omitempty"`
	BrewScans            []model.BrewScanResult   `json:"brew_scans"`
	BrewFormulae         []model.BrewPackage      `json:"brew_formulae,omitempty"`
	BrewCasks            []model.BrewPackage      `json:"brew_casks,omitempty"`
	PythonPkgManagers    []model.PkgManager       `json:"python_package_managers"`
	PythonGlobalPackages []model.PythonScanResult `json:"python_global_packages"`
	PythonProjects       []model.ProjectInfo      `json:"python_projects"`
	// Delta-protocol siblings (PayloadSchemaVersion >= 1). NodeProjects /
	// NodeGlobalPackages / PythonProjects / PythonGlobalPackages above carry
	// only the `changed` subset; everything else is here.
	NodeProjectsUnchanged   []model.UnchangedProjectRef     `json:"node_projects_unchanged,omitempty"`
	NodeProjectsRemoved     []model.RemovedProjectRef       `json:"node_projects_removed,omitempty"`
	NodeGlobalsUnchanged    []model.UnchangedGlobalRef      `json:"node_globals_unchanged,omitempty"`
	PythonProjectsUnchanged []model.UnchangedProjectRef     `json:"python_projects_unchanged,omitempty"`
	PythonProjectsRemoved   []model.RemovedProjectRef       `json:"python_projects_removed,omitempty"`
	PythonGlobalsUnchanged  []model.UnchangedGlobalRef      `json:"python_globals_unchanged,omitempty"`
	SystemPackageScans      []model.SystemPackageScanResult `json:"system_package_scans"`
	RuntimeScan             *model.RuntimeScanResult        `json:"runtime_scan,omitempty"` // nil = runtime inventory disabled
	AIAgents                []model.AITool                  `json:"ai_agents"`
	MCPConfigs              []model.MCPConfigEnterprise     `json:"mcp_configs"`
	NPMRCAudit              *model.NPMRCAudit               `json:"npmrc_audit,omitempty"`
	PipAudit                *model.PipAudit                 `json:"pip_audit,omitempty"`
	RuleScan                *model.RuleScan                 `json:"rule_scan,omitempty"`
	PnpmAudit               *model.PnpmAudit                `json:"pnpm_audit,omitempty"`
	BunAudit                *model.BunAudit                 `json:"bun_audit,omitempty"`
	YarnAudit               *model.YarnAudit                `json:"yarn_audit,omitempty"`
	AgentSkills             []model.AgentSkill              `json:"agent_skills,omitempty"`
	AgentSkillScan          *model.AgentSkillScanInfo       `json:"agent_skill_scan,omitempty"`
	AgentPlugins            *model.AgentPlugins             `json:"agent_plugins,omitempty"`
	CredentialScan          *model.CredentialScanInfo       `json:"credential_scan,omitempty"`
	// Nil means the phase did not run, and that is the only signal a reader has
	// for it: a section carrying zero findings is the positive claim that this
	// machine's browsers hold no extensions.
	BrowserExtensionScan *model.BrowserExtensionScanInfo `json:"browser_extension_scan,omitempty"`
	// Full bounded snapshots on every run, independent of the npm/Python deltas.
	GoInventory         *model.GoInventory         `json:"go_inventory,omitempty"`
	GoConfigAudit       *model.GoConfigAudit       `json:"go_config_audit,omitempty"`
	CargoInventory      *model.CargoInventory      `json:"cargo_inventory,omitempty"`
	CargoConfigAudit    *model.CargoConfigAudit    `json:"cargo_config_audit,omitempty"`
	ComposerInventory   *model.ComposerInventory   `json:"composer_inventory,omitempty"`
	ComposerConfigAudit *model.ComposerConfigAudit `json:"composer_config_audit,omitempty"`
	NuGetInventory      *model.NuGetInventory      `json:"nuget_inventory,omitempty"`
	NuGetConfigAudit    *model.NuGetConfigAudit    `json:"nuget_config_audit,omitempty"`
	RubyInventory       *model.RubyInventory       `json:"ruby_inventory,omitempty"`
	RubyConfigAudit     *model.RubyConfigAudit     `json:"ruby_config_audit,omitempty"`
	CondaInventory      *model.CondaInventory      `json:"conda_inventory,omitempty"`
	CondaConfigAudit    *model.CondaConfigAudit    `json:"conda_config_audit,omitempty"`
	MavenInventory      *model.MavenInventory      `json:"maven_inventory,omitempty"`
	MavenConfigAudit    *model.MavenConfigAudit    `json:"maven_config_audit,omitempty"`
	GradleConfigAudit   *model.GradleConfigAudit   `json:"gradle_config_audit,omitempty"`
	SwiftInventory      *model.SwiftInventory      `json:"swift_inventory,omitempty"`
	SwiftConfigAudit    *model.SwiftConfigAudit    `json:"swift_config_audit,omitempty"`

	ExecutionLogs      *ExecutionLogs      `json:"execution_logs,omitempty"`
	PerformanceMetrics *PerformanceMetrics `json:"performance_metrics,omitempty"`
}

Payload is the enterprise telemetry JSON structure.

type PerformanceMetrics

type PerformanceMetrics struct {
	ExtensionsCount       int   `json:"extensions_count"`
	NodePackagesScanMs    int64 `json:"node_packages_scan_ms"`
	NodeGlobalPkgsCount   int   `json:"node_global_packages_count"`
	NodeProjectsCount     int   `json:"node_projects_count"`
	BrewFormulaeCount     int   `json:"brew_formulae_count"`
	BrewCasksCount        int   `json:"brew_casks_count"`
	PythonGlobalPkgsCount int   `json:"python_global_packages_count"`
	PythonProjectsCount   int   `json:"python_projects_count"`
	SystemPackagesCount   int   `json:"system_packages_count"`
	RuntimesCount         int   `json:"runtimes_count"`
	AgentSkillsCount      int   `json:"agent_skills_count"`
	AgentPluginsCount     int   `json:"agent_plugins_count"`
}

type PhaseCompletion added in v1.11.4

type PhaseCompletion struct {
	Name       string `json:"name"`
	FinishedAt int64  `json:"finished_at"`
	DurationMs int64  `json:"duration_ms"`
	// CPUMs is CPU consumed during the phase (self plus subprocesses
	// where the platform attributes them), so an expensive phase is
	// distinguishable from a merely slow one. There is no memory
	// equivalent: peak RSS is a lifetime high-water mark and cannot be
	// differenced across phase boundaries.
	CPUMs int64 `json:"cpu_ms,omitempty"`
	// SleptMs is how long the system was suspended while this phase ran:
	// wall-clock elapsed minus awake elapsed (internal/awakeclock: the
	// monotonic clock on macOS and Linux, QueryUnbiasedInterruptTime on
	// Windows). DurationMs is awake time, the actual work, so a phase that
	// spanned a laptop nap reports both honestly.
	SleptMs int64 `json:"slept_ms,omitempty"`
}

PhaseCompletion records a single analysis phase that ran to completion. The list of these forms phases_completed in the run-status payload.

type PhaseTracker added in v1.11.4

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

PhaseTracker accumulates phase lifecycle events for a single telemetry run. The heartbeat goroutine and the main scan goroutine both touch it concurrently — Snapshot returns a defensive copy so the caller never observes a torn slice while a phase is appended.

func NewPhaseTracker added in v1.11.4

func NewPhaseTracker() *PhaseTracker

NewPhaseTracker constructs a tracker anchored at the current time.

func (*PhaseTracker) Finish added in v1.11.4

func (t *PhaseTracker) Finish() (PhaseCompletion, bool)

Finish records completion of the current phase and returns it. The bool is false when nothing was in flight — safe to defer and to call in statement position.

func (*PhaseTracker) Snapshot added in v1.11.4

func (t *PhaseTracker) Snapshot() RunStatusInfo

Snapshot returns a copy of the tracker state safe for marshalling on another goroutine. The returned slice is independent of the tracker's internal buffer.

When the in-flight phase has a detail set, it's folded into CurrentPhase as "<phase> (<detail>)" so the wire format stays flat — older backends without a dedicated detail field still render the progress verbatim. PhasesCompleted entries keep their base name; detail is per-tick state, not a permanent label.

func (*PhaseTracker) Start added in v1.11.4

func (t *PhaseTracker) Start(phase string)

Start records the beginning of a new phase. Calling Start while another phase is already in flight implicitly finishes the previous one — this keeps call sites tidy when phases run back-to-back without a Finish in between. Detail from the previous phase is cleared so it never leaks into the new one.

func (*PhaseTracker) UpdateDetail added in v1.11.4

func (t *PhaseTracker) UpdateDetail(detail string)

UpdateDetail sets a free-form sub-progress string for the current phase ("project 12 of 47", "scanning pip3", ...). No-op when no phase is in flight — keeps call sites tidy when a scanner reports progress from inside a goroutine that may outlive its enclosing Start/Finish.

type RunStatusInfo added in v1.11.4

type RunStatusInfo struct {
	PhasesCompleted []PhaseCompletion `json:"phases_completed,omitempty"`
	CurrentPhase    string            `json:"current_phase,omitempty"`
	ElapsedMs       int64             `json:"elapsed_ms"`
	// LogTailGzipBase64 is an optional snapshot of the most recent
	// captureTailBytes bytes of the agent's stderr stream, gzip-compressed
	// and base64-encoded. Attached on a throttle (logTailHeartbeatInterval)
	// so the wire cost stays bounded even when phase boundaries fire
	// rapidly. Backend handlers must tolerate this field being absent on
	// any given snapshot.
	LogTailGzipBase64 string `json:"log_tail_gzip_b64,omitempty"`
	// SleptMs is the run-level counterpart of PhaseCompletion.SleptMs,
	// measured from run start so it also covers sleep that lands between
	// phases. ElapsedMs is awake time; the two add up to wall-clock time.
	SleptMs int64 `json:"slept_ms,omitempty"`
}

RunStatusInfo is the structured progress snapshot sent on each phase boundary and on every heartbeat tick. The same struct is embedded on the final telemetry Payload so a stored telemetry record is self-describing without joining to the run-status table.

In-flight sub-progress (set via PhaseTracker.UpdateDetail) is folded into CurrentPhase as "<phase> (<detail>)" rather than carried in a separate field, so older backends that don't know about phase-detail still surface the string verbatim. Completed phases keep their base name only.

type UpdateEvent added in v1.18.0

type UpdateEvent struct {
	ExecutionID    string
	DeviceID       string
	InstallChannel string // "msi" | "loader"
	Event          string
	From, To       string
	Error          string
}

UpdateEvent is one self-update event (spec Contracts: Update event), posted to run-status with status "update".

Jump to

Keyboard shortcuts

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