Documentation
¶
Index ¶
- Constants
- func DetectInvocationMethod() string
- func ExecutionDeadline(configValue string) time.Duration
- func ExecutionDeadlineFromEnv() time.Duration
- func Run(exec executor.Executor, log *progress.Logger, cfg *cli.Config) (err error)
- type ExecutionLogs
- type LogCapture
- type Payload
- type PerformanceMetrics
- type PhaseCompletion
- type PhaseTracker
- type RunStatusInfo
Constants ¶
const ( InvocationInstall = "install" InvocationOneTime = "one_time" )
Wire-format values for the invocation_method field. Kept stable — console and backend match on these literal strings.
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 ¶
This section is empty.
Functions ¶
func DetectInvocationMethod ¶ added in v1.11.4
func DetectInvocationMethod() string
DetectInvocationMethod returns "install" when the dev-machine-guard scheduler footprint is present on this machine, else "one_time".
The check is best-effort and never returns an error: a stat failure or a flaky schtasks call degrades to "one_time" so an unknown environment is never misreported as an installed agent. Detection is filesystem-based on darwin/linux and a single schtasks query on windows, so an agent rolled out before this code shipped starts reporting "install" on its next scheduled fire without any installer changes.
func ExecutionDeadline ¶ added in v1.11.7
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
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 Run ¶
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 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) 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) 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.
type Payload ¶
type Payload struct {
CustomerID string `json:"customer_id"`
DeviceID string `json:"device_id"`
SerialNumber string `json:"serial_number"`
UserIdentity string `json:"user_identity"`
Hostname string `json:"hostname"`
Platform string `json:"platform"`
OSVersion string `json:"os_version"`
Resources model.MachineResources `json:"resources"`
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"`
SystemPackageScans []model.SystemPackageScanResult `json:"system_package_scans"`
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"`
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"`
}
type PhaseCompletion ¶ added in v1.11.4
type PhaseCompletion struct {
Name string `json:"name"`
FinishedAt int64 `json:"finished_at"`
DurationMs int64 `json:"duration_ms"`
}
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()
Finish records completion of the current phase. No-op when nothing is in flight — safe to defer.
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"`
}
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.