devicepolicy

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: 27 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 (
	CategoryPackageConfig = "package_config"
	TargetNPM             = "npm"
)

CategoryPackageConfig / TargetNPM identify the second policy category: the managed StepSecurity secure-registry block inside the console user's ~/.npmrc (see npmrc.go). They mirror agent-api's package_config / npm identifiers and, like the IDE pair, are passed as ?category=/?target= on the run-config fetch and echoed in the compliance report. The Verify() states are shared verbatim; this category adds no new state.

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

CacheFilename is the basename of the enforcement state file — the ONE file holding every category's ownership record, keyed by category then target. It lives under ~/.stepsecurity/ alongside config.json and hooks-state.json, and is distinct from the AI-agent hook cache (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 NPMOwnedKey = "npmrc"

NPMOwnedKey is the WrittenSettings key the npm lane records ownership under. The managed block is ONE atomic unit (its BEGIN/END markers bound it), so the lane owns exactly one entry — value = the rendered block body — where the VS Code lane owns one entry per setting id. Wired as Reconciler.OwnershipKey so drift, adoption, persistence, and the value-based clear all read the same key.

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

View Source
var (
	ErrTargetUnusable  = errors.New("npmrc: target unusable")
	ErrNoTargetUser    = errors.New("npmrc: no enforceable target user")
	ErrAbsoluteSymlink = fmt.Errorf("npmrc: .npmrc is an absolute symlink: %w", ErrTargetUnusable)
	ErrSymlinkLoop     = fmt.Errorf("npmrc: .npmrc symlink chain too deep: %w", ErrTargetUnusable)
	ErrDanglingSymlink = fmt.Errorf("npmrc: .npmrc symlink target does not exist: %w", ErrTargetUnusable)
)

Structural errors. Every "this target cannot be enforced" condition wraps ErrTargetUnusable so the reconciler can classify the whole class as write_failed regardless of whether a read or a write surfaced it, while a plain permission-denied / transient I/O error (which does not wrap it) stays verification_failed. ErrNoTargetUser is separate: it means there is no enforceable user on this machine state (LocalSystem, a non-interactive Windows session, or root with no resolvable GUI user), which the reconciler reports as policy_not_applied, not write_failed.

View Source
var ErrWriteUnverified = errors.New("npmrc: write could not be verified or rolled back")

ErrWriteUnverified means a mutating op landed new bytes it could then neither verify NOR roll back — the post-rename identity re-check failed and the restore to the pre-state also failed. On-disk state is therefore indeterminate (not the clean "write failed, disk untouched" case), which the reconciler classifies as verification_failed rather than write_failed. It deliberately does NOT wrap ErrTargetUnusable, so the write-path classifier routes it to verification_failed.

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 and same cacheMu + cross-process locking as WriteAppliedState. An already-absent category/target is a no-op (nothing recorded to drop).

A CORRUPT file is removed rather than left in place. Its bytes can still hold a token-bearing written_settings entry (the ~/.npmrc block records the device's auth token), and a clear is an unassignment or offboarding — reporting it done while those bytes survive on disk is what removal prevents. Nothing interpretable is lost: an unparseable file already reads as "owns nothing" for every category, so no sibling record could have been recovered from it. An absent file is left alone (there is nothing to remove).

An UNREADABLE file is neither removed nor rewritten — the read error is returned. On POSIX a file with no read permission is still unlinkable through a writable parent, so removing it here would destroy sibling categories' live ownership records sight unseen; a surfaced error keeps the operation honest and leaves the file for the next cycle (or an admin) to deal with.

func ProbeManagedContent added in v1.15.0

func ProbeManagedContent(expected string) (bool, map[string]json.RawMessage, error)

ProbeManagedContent reads the values of the Linux VS Code managed-policy file for the verify-only path. expected is unused — the backend compares observed against desired, so reading the managed values needs nothing from the policy (see ProbeContentNPM for a probe that does).

func ProbeManagedPolicy

func ProbeManagedPolicy() (bool, string)

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

func RenderNPMRCBlock added in v1.15.0

func RenderNPMRCBlock(policy json.RawMessage, serial string) (string, error)

RenderNPMRCBlock validates a policy and returns the two content lines the writer wraps in its markers: the `registry=` line and the `//host/path/:_authToken=` line, '\n'-joined with no markers and no trailing newline. It fully validates the policy (the HTTP layer only checks "is a JSON object"): the token line's host and path derive from registry_url, and the composed device token is `<api_key>::dev:<serial>`. Any validation failure returns an error the reconciler reports as policy_not_applied; error messages never echo the key or the policy.

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, and likewise refuses (returning the read error) when the file is present but unreadable — recreating it there would silently drop live sibling records whose content was never seen. A missing or corrupt file IS recreated: neither holds anything a read could have recovered.

The whole read-modify-write runs under cacheMu and the cross-process file lock, so a concurrent write for a different category — an npm reconcile in one process against an IDE reconcile in another — cannot drop this one's record, or have its own dropped. That holds unconditionally: a lock that cannot be taken fails the write (errStateLockBusy and friends) instead of proceeding unlocked.

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 every category and target shares ONE file without forcing a future migration. This is the only state file the subsystem keeps — a category does not get its own, and writing or clearing one (category, target) preserves every other one.

{
  "schema_version": 1,
  "categories": {
    "ide_extension": {
      "targets": {
        "vscode": { "applied_hash": …, "written_settings": …, "fetched_at": … }
      }
    },
    "package_config": {
      "targets": {
        "npm": { "applied_hash": …, "written_settings": …, "fetched_at": … }
      }
    }
  }
}

type AppliedTargetState

type AppliedTargetState struct {
	AppliedHash     string            `json:"applied_hash"`
	WrittenSettings map[string]string `json:"written_settings,omitempty"`
	FetchedAt       time.Time         `json:"fetched_at"`
}

AppliedTargetState records what the agent last wrote to the user-scope settings for one (category, target). Value-based ownership drives both drift and clear: a key is converged or removed only while its on-disk value still equals what the agent recorded writing (a differing value — e.g. the user's own — is left untouched).

  • AppliedHash is the backend's content hash, stored VERBATIM (never recomputed). Compared against the freshly-fetched hash for idempotency.
  • WrittenSettings is the ONLY ownership field, for every lane: the managed multi-key path records setting id → the exact compacted value the agent wrote for each managed key (the VS Code allowlist and the gallery service URL), and a single-value path records exactly one entry under its own ownership key (npmOwnedKey for the ~/.npmrc block, the allowlist setting id for a degraded VS Code writer). A key absent from the map is one the agent does not own.

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

AppliedHash and WrittenSettings are persisted as one struct in one write, so a record whose AppliedHash equals the freshly-fetched hash always carries the complete ownership map for that policy. Convergence checks rely on that: a cycle that finds the target converged with an unchanged hash short-circuits without persisting, which is only safe because a matching hash cannot coexist with partial ownership. A record hand-edited to break that pairing is outside the supported inputs — the value-based clear would leave those keys in place.

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/unreadable 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. Only the MUTATING accessors distinguish unreadable from absent, because only they can destroy what they could not read.

It takes no file lock: a lone read modifies nothing, and every write lands by atomic rename, so a reader sees one complete generation of the file or another — never a half-written one.

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"`
	Observed             json.RawMessage `json:"observed,omitempty"`
	EvaluatedEnforcement string          `json:"evaluated_enforcement,omitempty"`
}

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. In verify-only (mdm) mode AppliedHash is empty and Observed instead carries the OS-managed policy the agent read, keyed by VS Code setting id (the same keys as the desired policy) so the backend can diff like-for-like and decide drift — the agent does not judge match. EvaluatedEnforcement names the canonical channel the cycle actually ran — "dmg" or "mdm" (an empty or unrecognized request resolves to "dmg") — so the backend can gate on an exact match. Observed is omitted when empty.

type EffectivePolicy

type EffectivePolicy struct {
	Category    string
	Target      string
	Clear       bool
	Policy      json.RawMessage
	Hash        string
	GeneratedAt string
	Enforcement 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 policy object as canonical JSON — the exact bytes the backend hashed — kept RAW because its shape is per-category: for ide_extension it is the settings map (VS Code setting id, e.g. "extensions.allowed" / "extensions.gallery.serviceUrl", → that setting's compiled value), for package_config it is the npm registry object. Each category decodes what it needs; the agent writes the compiled values 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. Enforcement selects the channel: "mdm" is verify-only (probe and report, never a write), "dmg" or "" is the write-and-verify path. 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");
  • a non-clear ide_extension policy whose settings map does not carry an extensions.allowed object → error (validateCategoryPolicy). The check is category-gated: a package_config policy legitimately has no such key.

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 NPMRCWriter added in v1.15.0

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

NPMRCWriter converges the managed block in one user's ~/.npmrc. It satisfies the Writer interface (Read/Write/Clear/Location) and adds the concrete-type methods the reconciler seams need — Converged, ProbeExpected, RestoreSnapshot — none of which fit the settings.json-shaped interface.

Threat model: the agent can run as root (macOS LaunchDaemon) against a home directory the target user controls. A user who can plant symlinks or swap directory entries mid-operation must not be able to steer a root-owned write, a root read, or a token-bearing backup outside their own regular .npmrc. The writer therefore anchors every operation to a directory file descriptor via os.Root, resolves the .npmrc symlink chain explicitly, pins the resolved parent with a second os.Root, re-verifies file identity after every open, and performs all metadata changes on open handles (never by path). It never uses atomicfile, whose predictable, symlink-following backup names are exactly the attack this design closes.

func NewNPMRCWriter added in v1.15.0

func NewNPMRCWriter(exec executor.Executor) (*NPMRCWriter, error)

NewNPMRCWriter resolves the console user and opens a directory fd over their home. It returns ErrNoTargetUser when this machine state has no enforceable user (Windows LocalSystem or a non-interactive session, root with no GUI user); any other error is an infrastructure failure (home unresolvable or unopenable). The caller defers Close to release the directory fd.

func (*NPMRCWriter) Clear added in v1.15.0

func (w *NPMRCWriter) Clear() (bool, error)

Clear removes the managed block and restores the user's commented-out `registry=` lines. It carries the same transactional and metadata guarantees as Write and never deletes the file. The returned bool reports whether the file actually changed; the two no-op paths below return false.

func (*NPMRCWriter) Close added in v1.15.0

func (w *NPMRCWriter) Close() error

Close releases the home directory fd. Safe to call more than once.

func (*NPMRCWriter) Converged added in v1.15.0

func (w *NPMRCWriter) Converged(expected string) (bool, error)

Converged reports whether the file already reflects the desired block with no further work needed. It is stronger than block-body equality: the block must be present with body == expected, effective (nothing active overrides its registry/token after it, END marker intact, no displaced duplicate), and carry sane metadata (0600, target-user-owned on POSIX). A `registry=` line appended below an unchanged block (e.g. `aws codeartifact login`) leaves the body equal but defeats precedence — so body equality alone would report converged forever without ever re-running the transform.

func (*NPMRCWriter) Location added in v1.15.0

func (w *NPMRCWriter) Location() string

Location is a human-readable target description for logs. It never includes file contents or key material.

func (*NPMRCWriter) ProbeContentNPM added in v1.15.0

func (w *NPMRCWriter) ProbeContentNPM(expected string) (bool, map[string]json.RawMessage, error)

ProbeContentNPM is the MDM verify-only reader. It reports whether a StepSecurity MDM-managed block is present in ~/.npmrc and, if so, the effective (last-wins) configuration as the observed bag {ecosystem, registry_url, auth_token_status}. It NEVER writes, patches, or clears — in MDM mode the agent owns nothing on this file — and it never touches the ownership state store.

expected is the rendered desired block. Only its tenant key (the api_key before `::dev:<serial>`) is used, to decide auth_token_status here on the device; no token, hash, or fingerprint is ever returned or logged.

The three outcomes are deliberately distinct:

  • genuinely absent file, or present with no MDM marker → (false, nil, nil) → policy_not_applied. Nothing is managing this file.
  • unreadable file — permission failure, a leaf that became a symlink or changed across the open, a non-regular leaf, an ownership mismatch, the size cap — or a construct we cannot reason about → error → verification_failed. We could not establish the effective config, so we must not report the clean policy_not_applied.
  • MDM marker present and the file parses → (true, bag, nil) → mdm_managed.

Unlike the DMG-mode ProbeExpected this does NOT require 0600: perms are outside the locked observed contract, so a correctly-deployed-but-lax file must still report its real registry and auth status rather than be hidden behind a synthetic failure. Ownership IS still enforced — readCurrent refuses a leaf the target user does not own, because another user's file is not this user's effective npm config.

func (*NPMRCWriter) ProbeExpected added in v1.15.0

func (w *NPMRCWriter) ProbeExpected(expected string) (bool, string)

ProbeExpected reports whether the MDM lane has actually achieved the current desired state for this device — not merely that an MDM marker exists. Because ~/.npmrc is user-writable (unlike the privileged VS Code policy locations), trusting a marker alone would let a user pin permanent mdm_managed while pointing npm anywhere. Managed requires all of: the MDM marker outside our block, the MDM block's own registry/token lines equal to the expected rendered content, those keys effective (last-wins) with nothing overriding them, and sane metadata (0600, target-user-owned on POSIX).

func (*NPMRCWriter) Read added in v1.15.0

func (w *NPMRCWriter) Read() (string, bool, error)

Read returns the managed block body (canonicalized) and whether it is present. It satisfies the Writer interface; the reconciler uses Converged (not this) for the real idempotency decision.

func (*NPMRCWriter) RestoreSnapshot added in v1.15.0

func (w *NPMRCWriter) RestoreSnapshot() error

RestoreSnapshot reverts the last successful Write/Clear. It re-resolves the chain and refuses to write if the leaf now differs from the snapshot's — either by relative path (the user re-pointed .npmrc) or by identity (the parent or leaf inode was swapped under an unchanged path) — surfacing that as an error the reconciler maps to verification_failed. The snapshot is CONSUMED: a restore is attempted at most once, so a second call cannot re-run against a stale leaf. Calling it with no pending snapshot is an error.

func (*NPMRCWriter) SetLogf added in v1.15.0

func (w *NPMRCWriter) SetLogf(logf func(format string, args ...any))

SetLogf installs an optional diagnostic sink for non-fatal events (a missing END marker stripped to EOF, a backup-rotation prune failure, a snapshot restore that aborted). It is never handed file contents or key material.

func (*NPMRCWriter) Write added in v1.15.0

func (w *NPMRCWriter) Write(value string) (string, error)

Write applies the rewrite transform for the given rendered block body and returns the block body read back from disk. The op is transactional: it snapshots the pre-state first, and any failure after the rename self-restores before returning. On success the snapshot is retained for a later RestoreSnapshot.

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)

	// ProbeContent reads the effective externally-managed configuration for the
	// verify-only path and returns it as the observed bag. expected is this
	// cycle's rendered desired value: the VS Code probe ignores it (the backend
	// compares OS-managed values), while the ~/.npmrc probe needs it to decide
	// auth_token_status on-device — the desired tenant key must never leave the
	// machine, so only the verdict is reported. nil → the per-OS
	// ProbeManagedContent for ide_extension, and an error (→ verification_failed)
	// for any other category: falling back to the VS Code probe would report
	// another category's policy. The DMG path never calls it.
	ProbeContent func(expected string) (present bool, observed map[string]json.RawMessage, err error)

	// OwnershipKey is the WrittenSettings key the single-value paths record
	// ownership under (drift, adopt, persist, and the value-based clear all read
	// the same one). The managed multi-key path keys by real setting id and
	// ignores this. Empty → allowedExtensionsSettingKey, the only key a plain VS
	// Code Writer manages; the npm lane sets NPMOwnedKey.
	OwnershipKey string

	// Converged, when set, REPLACES the generic body-equality idempotency test
	// (present && on-disk == desired) with a target-specific full-state check —
	// e.g. the ~/.npmrc writer also verifies its block is effective (nothing
	// overrides it below) and carries sane metadata (0600, owned by the target
	// user). Body equality alone is a hole there: a `registry=` line appended
	// below an unchanged block leaves the body equal but defeats precedence.
	Converged func(expected string) (bool, error)

	// Render, when set, derives the value to write/compare from the raw policy —
	// e.g. rendering the two ~/.npmrc content lines from the npm policy object
	// and the device serial. nil → the value is the compacted policy JSON
	// (settings.json). A render failure is a malformed backend payload and is
	// reported as policy_not_applied.
	Render func(policy json.RawMessage) (string, error)

	// ProbeExpected, when set, REPLACES Probe for this cycle and receives the
	// rendered value so a content-aware probe can decide whether the MDM lane has
	// achieved the SAME desired state (the ~/.npmrc file is user-writable, so a
	// bare marker is not proof). nil → Probe.
	ProbeExpected func(expected string) (managed bool, detail string)

	// RestoreSnapshot, when set, is the rollback used after a post-write ownership
	// persist fails: the writer reverts its whole-file transformation from a
	// snapshot and its RESULT is classified — restore succeeded → write_failed
	// (the enforce write was undone), restore failed/aborted → verification_failed
	// (on-disk state now unknown). nil → the generic best-effort re-write of the
	// previous value (always write_failed), which suits a single settings key.
	RestoreSnapshot func() error

	// OwnsByMarker switches handleClear from value-based ownership (clear only
	// when on-disk still equals the recorded written value) to marker-based:
	// always call Writer.Clear() and drop the state record unconditionally. It
	// suits a writer whose Clear is intrinsically scoped to its own markers, so a
	// lost/drifted/empty record must not strand a token-bearing block on disk.
	OwnsByMarker bool

	// WriterInitErr carries a writer-construction failure (Writer is then nil).
	// The reconciler classifies it AFTER the fetch: absent policy → silent no-op,
	// clear → retain all state (no target to act against), enforce →
	// policy_not_applied for ErrNoTargetUser else write_failed. nil with a nil
	// Writer is the ordinary unsupported-platform silent no-op.
	WriterInitErr error

	// 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.
  • MDM enforcement (ep.Enforcement=="mdm") → verify-only: probe the externally-managed configuration and report what was observed; never writes, patches, or clears. Checked right after fetch, before the gates below, so it runs even with a nil Writer, a WriterInitErr, or a clear directive.
  • platform not enforceable (nil Writer, nil WriterInitErr) → silent no-op.
  • writer could not be constructed (nil Writer, WriterInitErr set) → classified AFTER the fetch by what run-config asked for: absent → silent; clear → no-op retaining ALL state (no resolved target to act against); enforce → policy_not_applied (ErrNoTargetUser) or write_failed (other).
  • 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 value; a value the agent has no record of writing is left untouched (value-based ownership) or the block is removed and the record dropped (marker-based ownership, OwnsByMarker). 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.
	//
	// changed reports whether anything was actually removed. Callers must keep
	// calling Clear unconditionally — that is what stops a lost ownership record
	// from stranding a live block — and use changed only to describe what
	// happened, so a clean device does not report a removal every cycle.
	Clear() (changed bool, err 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