-
Notifications
You must be signed in to change notification settings - Fork 20
feat: run-on-login scheduling, reliability fixes, scheduler diagnostics #146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shubham-stepsecurity
wants to merge
1
commit into
step-security:main
Choose a base branch
from
shubham-stepsecurity:sm/scheduler-info-interval-gate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| package launchd | ||
|
|
||
| import ( | ||
| "strings" | ||
| "testing" | ||
| "text/template" | ||
|
|
||
| "github.com/step-security/dev-machine-guard/internal/executor" | ||
| ) | ||
|
|
||
| func TestPlistTemplate_RunAtLoadAndScheduled(t *testing.T) { | ||
| tmpl, err := template.New("plist").Parse(plistTmpl) | ||
| if err != nil { | ||
| t.Fatalf("parse template: %v", err) | ||
| } | ||
| var sb strings.Builder | ||
| if err := tmpl.Execute(&sb, plistTemplateData{ | ||
| Label: label, | ||
| BinaryPath: "/usr/local/bin/stepsecurity-dev-machine-guard", | ||
| IntervalSeconds: 14400, | ||
| LogDir: "/Users/dev/.stepsecurity", | ||
| }); err != nil { | ||
| t.Fatalf("execute template: %v", err) | ||
| } | ||
| out := sb.String() | ||
|
|
||
| // RunAtLoad must be true so login/boot is a (gated) catch-up trigger. | ||
| if !strings.Contains(out, "<key>RunAtLoad</key>\n <true/>") { | ||
| t.Errorf("plist must set RunAtLoad=true:\n%s", out) | ||
| } | ||
| if strings.Contains(out, "<false/>") { | ||
| t.Errorf("plist must not contain RunAtLoad=false:\n%s", out) | ||
| } | ||
| if !strings.Contains(out, "<string>send-telemetry</string>") { | ||
| t.Errorf("plist must invoke send-telemetry:\n%s", out) | ||
| } | ||
| } | ||
|
|
||
| func TestDomainTarget(t *testing.T) { | ||
| root := executor.NewMock() | ||
| root.SetIsRoot(true) | ||
| if domain, target := DomainTarget(root); domain != "system" || target != "system/"+label { | ||
| t.Errorf("root DomainTarget = %q,%q; want system, system/%s", domain, target, label) | ||
| } | ||
|
|
||
| user := executor.NewMock() | ||
| user.SetIsRoot(false) | ||
| domain, target := DomainTarget(user) | ||
| if !strings.HasPrefix(domain, "gui/") { | ||
| t.Errorf("non-root domain = %q, want gui/<uid>", domain) | ||
| } | ||
| if target != domain+"/"+label { | ||
| t.Errorf("target = %q, want %q", target, domain+"/"+label) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| //go:build darwin | ||
|
|
||
| package schedinfo | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/step-security/dev-machine-guard/internal/executor" | ||
| "github.com/step-security/dev-machine-guard/internal/launchd" | ||
| ) | ||
|
|
||
| func gather(ctx context.Context, exec executor.Executor) Info { | ||
| info := Info{ | ||
| Platform: "darwin", | ||
| Manager: "launchd", | ||
| Label: launchd.Label, | ||
| ConfiguredHours: configuredHours(), | ||
| Management: ManagementUnknown, | ||
| LogMtime: logMtime(), | ||
| } | ||
|
|
||
| // Resolve the plist for this run's privilege level (root LaunchDaemon vs | ||
| // per-user LaunchAgent), mirroring the install/uninstall paths. | ||
| plistPath := launchd.DaemonPlistPath | ||
| if !exec.IsRoot() { | ||
| plistPath = launchd.UserPlistPath() | ||
| } | ||
| info.UnitPath = plistPath | ||
| info.Scheduled = exec.FileExists(plistPath) | ||
|
|
||
| // Parse the plist directly — it's our own well-formed XML, so reading | ||
| // StartInterval/RunAtLoad/ProgramArguments from disk is more robust than | ||
| // scraping plutil and needs no subprocess. | ||
| if data, err := os.ReadFile(plistPath); err == nil { | ||
| if pl, perr := parsePlist(data); perr == nil { | ||
| if pl.StartInterval > 0 { | ||
| info.IntervalSeconds = pl.StartInterval | ||
| } | ||
| ral := pl.RunAtLoad | ||
| info.RunAtLoad = &ral | ||
| info.Management = managementFromCmd(strings.Join(pl.ProgramArguments, " ")) | ||
| } else { | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("parse plist %s: %v", plistPath, perr)) | ||
| } | ||
| } else if info.Scheduled { | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("read plist %s: %v", plistPath, err)) | ||
| } | ||
|
|
||
| // Live runtime state via `launchctl print <domain>/<label>` — parsed for | ||
| // state / pid / last-exit-code. We deliberately do NOT dump its full output: | ||
| // it's ~100 lines of internal launchd detail (endpoints, sandbox, inherited | ||
| // env) that's noise for troubleshooting. The concise plist config below is | ||
| // the illustrative dump instead. | ||
| domain, target := launchd.DomainTarget(exec) | ||
| stdout, stderr, code, err := exec.RunWithTimeout(ctx, queryTimeout, "launchctl", "print", target) | ||
| switch { | ||
| case err != nil: | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("launchctl print %s: %v", target, err)) | ||
| case code != 0: | ||
| // Expected on no-GUI / SSH sessions ("Could not find service ...", | ||
| // "Bootstrap failed: 5") — see docs/launchd-troubleshooting.md. | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("launchctl print %s exited %d: %s", target, code, firstLine(stderr))) | ||
| default: | ||
| info.Loaded = true | ||
| applyLaunchctlPrint(&info, stdout) | ||
| } | ||
|
|
||
| // Fallback: `launchctl list <label>` for last exit + pid when print failed. | ||
| if !info.Loaded { | ||
| if out, _, c, e := exec.RunWithTimeout(ctx, queryTimeout, "launchctl", "list", launchd.Label); e == nil && c == 0 { | ||
| info.Loaded = strings.Contains(out, "LastExitStatus") || strings.Contains(out, launchd.Label) | ||
| applyLaunchctlList(&info, out) | ||
| } | ||
| } | ||
| _ = domain // domain currently informational; target carries it | ||
|
|
||
| // Illustrative config dump: `plutil -p` of the plist — the focused, readable | ||
| // schedule config (Label, ProgramArguments, StartInterval, RunAtLoad, env), | ||
| // the macOS analog of `schtasks /query /v`, far less noisy than launchctl print. | ||
| if out, _, c, e := exec.RunWithTimeout(ctx, queryTimeout, "plutil", "-p", plistPath); e == nil && c == 0 { | ||
| info.Raw = strings.TrimSpace(out) | ||
| } | ||
|
|
||
| // launchd exposes no "next fire" for a StartInterval job, so estimate it from | ||
| // the last run (agent.log mtime) + the interval. Labeled an estimate so it's | ||
| // not mistaken for a value launchd reported. | ||
| if !info.LogMtime.IsZero() && info.IntervalSeconds > 0 { | ||
| next := info.LogMtime.Add(time.Duration(info.IntervalSeconds) * time.Second) | ||
| info.NextRunTime = next.Format(time.RFC3339) + " (estimated: last run + interval)" | ||
| } | ||
|
|
||
| // Drift note: plist interval vs configured hours is a real misconfig signal. | ||
| if info.IntervalSeconds > 0 && info.ConfiguredHours > 0 && info.IntervalSeconds != info.ConfiguredHours*3600 { | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf( | ||
| "plist StartInterval=%ds disagrees with config scan_frequency_hours=%d (%ds)", | ||
| info.IntervalSeconds, info.ConfiguredHours, info.ConfiguredHours*3600)) | ||
| } | ||
|
|
||
| return info | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| //go:build linux | ||
|
|
||
| package schedinfo | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/step-security/dev-machine-guard/internal/executor" | ||
| "github.com/step-security/dev-machine-guard/internal/systemd" | ||
| ) | ||
|
|
||
| // gather is best-effort on Linux: it confirms the systemd user timer footprint | ||
| // and captures `systemctl --user list-timers` output (logged at Debug) for the | ||
| // NEXT/LAST columns. Detailed per-field parsing is intentionally skipped — the | ||
| // table is locale/width-dependent; the agent.log mtime serves as the last-run | ||
| // proxy. macOS and Windows are the richly-parsed targets. | ||
| func gather(ctx context.Context, exec executor.Executor) Info { | ||
| info := Info{ | ||
| Platform: "linux", | ||
| Manager: "systemd", | ||
| Label: "stepsecurity-dev-machine-guard.timer", | ||
| ConfiguredHours: configuredHours(), | ||
| Management: ManagementUnknown, | ||
| LogMtime: logMtime(), | ||
| } | ||
| if info.ConfiguredHours > 0 { | ||
| info.IntervalSeconds = info.ConfiguredHours * 3600 | ||
| } | ||
|
|
||
| unitPath := systemd.TimerUnitPath() | ||
| info.UnitPath = unitPath | ||
| info.Scheduled = exec.FileExists(unitPath) | ||
|
|
||
| out, stderr, code, err := exec.RunWithTimeout(ctx, queryTimeout, | ||
| "systemctl", "--user", "list-timers", "--all", "--no-pager") | ||
| switch { | ||
| case err != nil: | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("systemctl list-timers: %v", err)) | ||
| case code != 0: | ||
| info.Warnings = append(info.Warnings, fmt.Sprintf("systemctl list-timers exited %d: %s", code, firstLine(stderr))) | ||
| default: | ||
| info.Raw = out | ||
| if strings.Contains(out, "stepsecurity-dev-machine-guard") { | ||
| info.Loaded = true | ||
| } | ||
| } | ||
| return info | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we can use constants that we have defined for Darwin (same for linux and windows) to keep the codebase consistent.