devicepolicy

package
v1.13.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 19 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 devicepolicy implements the dev-machine-guard agent side of Developer MDM on-device policy enforcement (PRD: "Dev Machine Guard Agent: IDE Extension Enforcement"). It is a thin agent: each scheduled cycle it fetches the backend-compiled policy and converges the `extensions.allowed` key in the user-scope VS Code settings.json to it (format-preserving single-key JSONC merge), reads it back to verify, and reports a compliance state. VS Code itself performs the disabling — the agent never uninstalls extensions, never installs anything, and never touches non-VS-Code IDEs.

This subsystem shares NO code or state with the AI-agent hook-policy feature in internal/aiagents (PRD N11). The backend computes the compiled extensions.allowed object and a content hash; the agent applies it verbatim (compacted for canonical comparison) and never re-implements allow/deny merging, so on-device and exported enforcement stay at parity.

Scope: Windows, macOS, and Linux, all through the same settings.json writer — only the per-OS path differs (%APPDATA%\Code\User, ~/Library/Application Support/Code/User, ~/.config/Code/User). Devices whose VS Code is already governed by a real MDM/admin policy at the OS policy location (HKLM/HKCU registry, /etc/vscode/policy.json, macOS managed preferences) are detected by a read-only probe and reported mdm_managed — such a policy outranks user settings inside VS Code, so the agent yields rather than writing a value that would be ignored.

Seams (highest first), each independently testable:

  • Verify (verify.go): pure {write_ok, readback_match} → state.
  • Writer (settings_writer.go): injected; manages only the extensions.allowed key, preserving the rest of the user's settings.
  • Probe (probe.go + per-OS files): read-only managed-policy presence.
  • Fetcher / Reporter (api.go): the two dedicated endpoints on the existing developer-mdm-agent auth channel.
  • Reconciler (reconcile.go): orchestrates fetch → probe → idempotency → drift → ownership-safe write → verify → report, with malformed-→-no-op.

Index

Constants

View Source
const (
	StateCompliant          = "compliant"
	StatePending            = "pending"
	StatePolicyNotApplied   = "policy_not_applied"
	StateDriftDetected      = "drift_detected"
	StateMDMManaged         = "mdm_managed"
	StateWriteFailed        = "write_failed"
	StateVerificationFailed = "verification_failed"
)

Compliance states the agent may report. These mirror the agent-reportable subset of agent-api's policies.State* enum byte-for-byte — the backend rejects any value outside its agentReportableStates set, so these strings MUST stay in sync with internal/developer-mdm/policies/models.go. The backend-derived states (not_assigned, agent_unsupported, agent_stale) are never reported by the agent.

View Source
const CacheFilename = "device-policy-state.json"

CacheFilename is the basename of the enforcement state file. It lives under ~/.stepsecurity/ alongside config.json and hooks-state.json, and is distinct from the AI-agent hook cache (this is a separate subsystem — no shared state).

View Source
const CacheSchemaVersion = 1

CacheSchemaVersion is the on-disk version of the state file. Bump only on a breaking shape change.

View Source
const CategoryIDEExtension = "ide_extension"

CategoryIDEExtension is the only policy category enforced in v1. It matches agent-api's CategoryIDEExtension and is the value passed as ?category= on the run-config fetch and echoed in the compliance report.

View Source
const DefaultHTTPTimeout = 5 * time.Second

DefaultHTTPTimeout caps a single fetch or report round-trip. Enforcement runs off the scheduled tick, not a hot path, so a 5s ceiling is comfortable and matches the hook fetcher's budget.

View Source
const TargetVSCode = "vscode"

TargetVSCode is the only IDE target enforced in v1. Policy identity is (category, target); an empty target defaults to vscode for ide_extension, so future IDE families (jetbrains, …) become a new target rather than a new category or a state migration. Matches agent-api's TargetVSCode and is the value passed as ?target= on the run-config fetch and echoed in the compliance report.

Variables

This section is empty.

Functions

func AgentVersion

func AgentVersion() string

AgentVersion returns the running agent version reported in compliance payloads. Centralized here so the report and any diagnostics agree.

func CachePath

func CachePath() string

CachePath returns the absolute state-file path, honoring the test override. Empty string means the home directory could not be resolved.

func ClearAppliedState

func ClearAppliedState(category, target string) error

ClearAppliedState drops one (category, target) ownership record, PRESERVING every other category AND every sibling target, then atomically rewrites the file. An empty target defaults to vscode. When the cleared target was the category's last, the now-empty category is dropped too. Same future-schema refusal as WriteAppliedState. A missing or corrupt file — or an already-absent category/target — is a no-op (nothing recorded to drop).

func ProbeManagedPolicy

func ProbeManagedPolicy() (bool, string)

ProbeManagedPolicy reports whether an AllowedExtensions policy exists in the Linux policy file.

func SetCachePathForTest

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

SetCachePathForTest redirects CachePath() to the given absolute path and returns a restore function. Test-only.

func Verify

func Verify(in VerifyInput) string

Verify maps a write/readback result to the compliance state, with a fixed precedence:

  1. Write failed → write_failed.
  2. Write succeeded but the readback differs → policy_not_applied.
  3. Otherwise → compliant.

`compliant` means exactly what the PRD's weak-verification model allows: the desired policy is present in the user-scope settings.json (readback-confirmed) — NOT a per-extension disabled confirmation.

The remaining agent states are decided by the reconciler's ladder, not here, because none is derivable from these two inputs alone: mdm_managed (a real managed policy found by the probe), drift_detected (the on-disk value diverged from the recorded written value and was re-applied — it upgrades a would-be compliant), and verification_failed (the read itself errored).

func WriteAppliedState

func WriteAppliedState(category, target string, s AppliedTargetState) error

WriteAppliedState records ownership for one (category, target), PRESERVING every other category AND every sibling target already in the file (read-modify-write), then atomically replaces the file (temp + sync + rename). An empty target defaults to vscode. It REFUSES to overwrite a file written by a newer agent (errFutureSchema) rather than clobber metadata it cannot interpret. A missing or corrupt file is recreated.

Types

type AppliedCategoryState

type AppliedCategoryState struct {
	Targets map[string]AppliedTargetState `json:"targets"`
}

AppliedCategoryState wraps the per-target ownership records for one category. The category is the map key in AppliedStateFile; the target is the map key in Targets. An absent category key, an absent target key, or a nil Targets map all mean "the agent owns nothing on disk" for that category/target.

type AppliedStateFile

type AppliedStateFile struct {
	SchemaVersion int                             `json:"schema_version"`
	Categories    map[string]AppliedCategoryState `json:"categories"`
}

AppliedStateFile is the on-disk shape: a schema-versioned wrapper keyed by category and then by target, so multiple categories and IDE targets share one file without forcing a future migration. Exactly one pair (ide_extension/vscode) is populated today.

{
  "schema_version": 1,
  "categories": {
    "ide_extension": {
      "targets": {
        "vscode": { "applied_hash": …, "written_value": …, "fetched_at": … }
      }
    }
  }
}

type AppliedTargetState

type AppliedTargetState struct {
	AppliedHash  string    `json:"applied_hash"`
	WrittenValue string    `json:"written_value"`
	FetchedAt    time.Time `json:"fetched_at"`
}

AppliedTargetState records what the agent last wrote to the user-scope VS Code settings.json for one (category, target). Two fields drive correctness:

  • AppliedHash is the backend's content hash, stored VERBATIM (never recomputed). Compared against the freshly-fetched hash for idempotency.
  • WrittenValue is the exact compacted extensions.allowed value the agent wrote. It drives value-based ownership and drift: on a clear, the agent removes the settings key only if the on-disk value still equals WrittenValue (a differing value — e.g. the user's own — is left untouched); on enforce, an on-disk value differing from WrittenValue is drift and is converged back.

A zero-value entry means "the agent owns nothing on disk" for that category/target.

func ReadAppliedState

func ReadAppliedState(category, target string) (AppliedTargetState, bool)

ReadAppliedState returns the agent's recorded ownership for one (category, target): (state, true) when a record exists, else (zero, false). An empty target defaults to vscode. It never surfaces an error — a missing/corrupt file, or one written by a newer agent (schema_version beyond this build's CacheSchemaVersion), simply means "no recorded ownership". The reconciler treats that as owning nothing: safe, because it then refuses to clear a value it has no record of writing and re-applies the policy.

type ComplianceReport

type ComplianceReport struct {
	Category     string `json:"category"`
	Target       string `json:"target"`
	State        string `json:"state"`
	AppliedHash  string `json:"applied_hash"`
	AgentVersion string `json:"agent_version"`
	Platform     string `json:"platform"`
}

ComplianceReport is the agent's POST body: the verification result it computed on-device. It is the agent-side mirror of agent-api's complianceReport. AppliedHash is the backend's hash echoed verbatim — never recomputed locally — so the backend's byte-exact applied==desired check (which gates the `compliant` verdict) can succeed.

type EffectivePolicy

type EffectivePolicy struct {
	Category    string
	Target      string
	Clear       bool
	Policy      json.RawMessage
	Hash        string
	GeneratedAt string
}

EffectivePolicy is the parsed device-policy directive, lifted from the `policy` sub-object of the run-config response (it mirrors agent-api's EffectivePolicyResponse). Policy carries the compiled VS Code extensions.allowed object as canonical JSON (sorted keys) — the exact bytes the backend hashed — so the agent writes it verbatim and never re-serializes (re-serialization could reorder keys and break the backend's byte-exact applied==desired check). Policy identity is (Category, Target); Target defaults to vscode for ide_extension. A zero EffectivePolicy (present()==false) means run-config carried no directive for this category/target → reconciler no-op.

type Fetcher

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

Fetcher returns the effective policy for one device + category + target.

type HTTPFetcher

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

HTTPFetcher is the production Fetcher. Safe for concurrent use.

func NewHTTPFetcher

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

NewHTTPFetcher builds a Fetcher from the same strict enterprise-config gate the upload path uses (ingest.Config). ok=false on incomplete config — the caller treats that as "skip enforcement", matching the hook reconciler.

func (*HTTPFetcher) Fetch

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

Fetch issues GET /v1/:customer/developer-mdm-agent/run-config?device_id=…&category=…&target=… over the existing agent auth channel (Bearer tenant key) and lifts the device-policy directive from the response's `policy` sub-object. An empty category defaults to ide_extension and an empty target to vscode. It returns a parsed EffectivePolicy or an error. Any error is the reconciler's signal to NO-OP (never wipe enforcement on a transient failure or malformed payload):

  • transport / non-200 status → error;
  • body that is not valid JSON → error;
  • a non-clear result missing policy or hash → error (a malformed policy must not be written, and must not be mistaken for a clear);
  • a non-clear policy that is not itself a JSON object → error (a string or array written verbatim could even read back "compliant").

An omitted/null `policy` is NOT an error: it means run-config carried no directive for this category/target (a degraded/rules-only response, an older backend not yet emitting policy, or an unknown category/target). Fetch returns a zero EffectivePolicy (present()==false) and a nil error, and the reconciler no-ops. Unassignment is signaled by the explicit clear:true directive, never by absence. A response whose `policy` omits `target` defaults to the requested target.

type HTTPReporter

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

HTTPReporter is the production Reporter.

func NewHTTPReporter

func NewHTTPReporter(cfg ingest.Config, h *http.Client) (*HTTPReporter, bool)

NewHTTPReporter builds a Reporter from the strict enterprise-config gate. ok=false on incomplete config.

func (*HTTPReporter) Report

func (c *HTTPReporter) Report(ctx context.Context, customerID, deviceID string, r ComplianceReport) error

Report issues POST /v1/:customer/developer-mdm-agent/devices/:device_id/compliance over the existing agent auth channel — a dedicated endpoint, NOT the telemetry payload. The backend rejects an unregistered device_id (400) and records the per-device state; it computes desired_hash itself and decides compliant vs pending. A non-2xx is returned as an error for the caller to log.

type Reconciler

type Reconciler struct {
	Fetcher  Fetcher
	Reporter Reporter
	// Writer is the settings.json writer, or nil when the platform has no
	// resolvable settings path. A nil Writer makes Reconcile a no-op.
	Writer Writer

	CustomerID string
	DeviceID   string
	Platform   string // reported in compliance; e.g. "windows", "linux", "darwin"
	Category   string // defaults to ide_extension
	Target     string // defaults to vscode

	// Probe reports whether a real MDM/admin-managed AllowedExtensions policy
	// exists at this OS's policy location (registry / policy.json / managed
	// preferences). Such a policy outranks user settings inside VS Code, so the
	// agent yields (mdm_managed) instead of writing a value VS Code would
	// ignore. nil → ProbeManagedPolicy (the per-OS implementation); tests
	// inject a stub so results never depend on the host machine.
	Probe func() (managed bool, detail string)

	// Now and Logf are optional seams. Now defaults to time.Now().UTC; Logf to a
	// no-op.
	Now  func() time.Time
	Logf func(format string, args ...any)
	// contains filtered or unexported fields
}

Reconciler converges the user-scope VS Code settings.json to the backend's effective policy for one device, once per scheduled cycle. It is OS-agnostic: the settings Writer, the managed-policy Probe, the policy Fetcher, and the compliance Reporter are all injected, so the whole flow is fake-testable with no real I/O.

func (*Reconciler) Reconcile

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

Reconcile runs one enforcement cycle. It NEVER panics into the caller's hot path; failures are returned for logging. The contract:

  • fetch error (transport / non-200 / malformed) → NO-OP, error returned. Enforcement on disk is never wiped on a transient or malformed response.
  • platform not enforceable (nil Writer) → silent no-op.
  • absent policy (run-config carried no `policy` directive for this category/target) → silent no-op; the on-disk value and ownership record stand. This is NOT a clear — removal happens only on an explicit clear.
  • clear result → remove ONLY the agent-owned settings key; a value the agent has no record of writing is left untouched. No compliance report (an unassigned device is backend-derived).
  • policy result → probe → ownership/drift-checked write + readback + verify + report (handleEnforce).

type Reporter

type Reporter interface {
	Report(ctx context.Context, customerID, deviceID string, r ComplianceReport) error
}

Reporter submits a compliance report for one device.

type VerifyInput

type VerifyInput struct {
	// WriteOK is true when the settings write returned no error.
	WriteOK bool
	// ReadbackMatch is true when the value read back after the write equals the
	// value the agent intended to write. A false value here (with WriteOK true)
	// is the on-device signal that the write did not actually take.
	ReadbackMatch bool
}

VerifyInput is the result set the verifier reasons over. It is intentionally pure data: the writer performs the I/O (write + readback), so Verify itself touches nothing.

type Writer

type Writer interface {
	// Read returns the current extensions.allowed value (compacted) and
	// whether it is present. (present=false, err=nil) means the file is
	// missing or readable-but-without-the-key. An unparseable settings.json
	// is an error — the writer refuses to reason about a file it cannot
	// understand.
	Read() (value string, present bool, err error)

	// Write upserts extensions.allowed to value, then reads it back and
	// returns the read-back value. The reconciler compares it to value to
	// detect a silent non-apply (policy_not_applied). An error means the
	// write itself failed or the file is unsalvageable → write_failed.
	Write(value string) (readback string, err error)

	// Clear removes the extensions.allowed key, leaving the rest of the file
	// (and the file itself) intact. A missing file or absent key is a no-op.
	Clear() error

	// Location is a human-readable description of the target, for logs.
	Location() string
}

Writer reads, upserts, and removes the `extensions.allowed` key in the user-scope VS Code settings.json. It is a thin primitive: it manages ONLY that one top-level key — every other key, comment, and formatting detail in the file is preserved (single-key JSONC merge), which is what makes editing a file the user also owns safe. Ownership and drift decisions (whether the agent may overwrite or remove) live in the reconciler, not here, so the writer stays pure and fake-testable.

Values are compact JSON object strings — the backend's compiled extensions.allowed object, compacted. Read returns the on-disk value re-compacted, so equality against a recorded written value is canonical regardless of how the file is formatted on disk.

The production implementation is settingsWriter below; the reconciler is exercised against fakes.

func NewWriter

func NewWriter() (Writer, bool)

NewWriter returns the user-scope settings.json writer for this OS. ok=false when settingsPath cannot resolve the target (unsupported OS, no home dir or %APPDATA%) — the reconciler treats that as not agent-enforceable and no-ops.

Jump to

Keyboard shortcuts

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