Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Config file supports multiple contexts:

## Parser

Walks `teams/*.yml`, resolves `path:` references, produces `ParsedRepo`. Also parses `default.yml` for labels, `org_settings`, `agent_options`, `controls`, and global policies/queries. A team's `settings:` block (or the older `team_settings:` spelling) is kept as a nested map for field-level diffing. All path references are validated against the repo root to prevent traversal.
Walks `teams/*.yml`, resolves `path:` references, produces `ParsedRepo`. Also parses `default.yml` for labels, `org_settings`, `agent_options`, `controls`, and global policies/queries. A team's `settings:` block (or the older `team_settings:` spelling) and its `controls:` block are kept as nested maps for field-level diffing. An `agent_options: path:` reference, in a team file or `default.yml`, is replaced by the file it points to. All path references are validated against the repo root to prevent traversal.

---

Expand All @@ -95,6 +95,8 @@ Fleet's "hosts on no team" bucket is absent from `GET /teams`, so it is fetched
|----------|-----------|-------------|
| Config sections (global) | dot-path key | old/new value (skips `$VAR` placeholders) |
| Team `settings:` | dot-path key | old/new value vs the team object from `GET /teams`; `secrets:` is never diffed |
| Team `controls:` | dot-path key | old/new value vs the team's `mdm` object (`setup_experience` vs its legacy `macos_setup` names); for the no-team file, vs global `config.mdm`. Scripts and profiles are diffed separately |
| Team `agent_options:` | dot-path key | old/new value vs the team's `agent_options` |
| Policies | `name` | query, description, resolution, platform, critical, labels_include_any, labels_exclude_any |
| Queries | `name` | query, interval, platform, logging |
| Software packages | `referenced_yaml_path` | url, hash, self_service, categories |
Expand All @@ -111,6 +113,8 @@ Label scoping lists (`labels_include_any` etc.) are compared as sets: order is i

Category names are normalized before comparison. Fleet reports them as display names with an emoji prefix (`🔐 Security`), while fleet-gitops YAML writes them plainly (`Security`); only leading symbols are stripped, so a category starting with a letter or digit (`1Password`) is untouched.

Numbers are compared in plain decimal: JSON decodes every number as float64, which `fmt` would print as `2.62144e+07`. In JSON values, a `teams` key is treated as the legacy spelling of `fleets` (Fleet 4.92 returns both on VPP tokens).

Whitespace is normalized before comparison to avoid false positives from YAML vs API newline differences. Per-field diffs are stored in `ResourceChange.Fields` for both added and modified resources.

---
Expand Down
261 changes: 187 additions & 74 deletions internal/diff/differ.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"regexp"
"slices"
"sort"
"strconv"
"strings"
"unicode"

Expand Down Expand Up @@ -202,7 +203,7 @@ func noTeamSummary(t parser.ParsedTeam) string {
// When the bucket was not fetched (older Fleet, or the caller did not ask for
// it), it falls back to reporting what the repo configures, so nothing
// silently disappears from the plan.
func diffNoTeam(result *DiffResult, current *api.NoTeam, proposed parser.ParsedTeam, changedFiles []string, cfg diffOptions) {
func diffNoTeam(result *DiffResult, current *api.NoTeam, globalMDM map[string]any, proposed parser.ParsedTeam, changedFiles []string, cfg diffOptions) {
if current == nil {
if summary := noTeamSummary(proposed); summary != "" {
result.Errors = append(result.Errors,
Expand Down Expand Up @@ -231,6 +232,9 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, proposed parser.ParsedT
result.Scripts = diffScripts(current.Scripts, proposed.Scripts)
}

// The no-team file's controls are Fleet's global MDM settings.
result.Config = diffControls(globalMDM, proposed.Controls, nil)

// Fleet reports configured software only through the teams list, which
// excludes this bucket, so there is nothing to compare against. Say so
// rather than reporting every configured item as an addition.
Expand Down Expand Up @@ -266,6 +270,7 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, proposed parser.ParsedT
result.Policies = markDrift(result.Policies, base.Policies)
result.Profiles = markDrift(result.Profiles, base.Profiles)
result.Scripts = markDrift(result.Scripts, base.Scripts)
result.Config = markConfigDrift(result.Config, diffControls(globalMDM, baseTeam.Controls, nil))
vlog(cfg.verbose, "[%s] after baseline drift marking: policies=%s profiles=%s scripts=%s",
proposed.Name, rdSummary(result.Policies), rdSummary(result.Profiles), rdSummary(result.Scripts))
} else {
Expand Down Expand Up @@ -392,7 +397,8 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st
// returned by the /teams API endpoint. Skip the "will be created"
// warning for it, and don't list its resources as additions.
if parser.IsNoTeam(proposedTeam.Name, proposedTeam.SourceFile) {
diffNoTeam(&result, current.NoTeam, proposedTeam, changedFiles, cfg)
globalMDM, _ := current.Config["mdm"].(map[string]any)
diffNoTeam(&result, current.NoTeam, globalMDM, proposedTeam, changedFiles, cfg)
} else {
// Genuinely new team. Diffing against nothing lists every
// policy and query as added, with fields for drift matching.
Expand All @@ -416,7 +422,7 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st

result.Policies = diffPolicies(currentTeam.Policies, proposedTeam.Policies)
result.Queries = diffQueries(currentTeam.Queries, proposedTeam.Queries)
result.Config, result.SkippedConfigSections = diffTeamSettings(currentTeam.Settings, proposedTeam.Settings)
result.Config, result.SkippedConfigSections = diffTeamConfig(currentTeam.Settings, proposedTeam)

// enrichedSoftware holds the API software state with fleet-maintained
// app scripts populated. Hoisted here so the baseline drift pass
Expand Down Expand Up @@ -473,7 +479,7 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st
baseDiff := DiffResult{}
baseDiff.Policies = diffPolicies(currentTeam.Policies, baseTeam.Policies)
baseDiff.Queries = diffQueries(currentTeam.Queries, baseTeam.Queries)
baseDiff.Config, _ = diffTeamSettings(currentTeam.Settings, baseTeam.Settings)
baseDiff.Config, _ = diffTeamConfig(currentTeam.Settings, baseTeam)
if !currentTeam.SoftwareUnavailable {
baseDiff.Software, _ = diffSoftware(enrichedSoftware, baseTeam.Software)
}
Expand Down Expand Up @@ -1840,11 +1846,11 @@ func diffConfig(apiConfig map[string]any, proposed *parser.ParsedGlobal) ([]Conf
sections := map[string]map[string]any{
"org_settings": proposed.OrgSettings,
"agent_options": proposed.AgentOptions,
"controls": proposed.Controls,
"controls": settingsControls(proposed.Controls),
}

for section, proposedMap := range sections {
if proposedMap == nil {
if len(proposedMap) == 0 {
continue
}

Expand All @@ -1871,36 +1877,7 @@ func diffConfig(apiConfig map[string]any, proposed *parser.ParsedGlobal) ([]Conf
continue
}

// Recursive key-by-key comparison.
// Only report a diff when the API actually has a value for this key.
// If getNestedValue returns "" the API doesn't expose the field (e.g.
// agent_options sub-keys, sso_settings) and we can't determine whether
// the proposed value differs from what Fleet already has.
flattenMap(proposedMap, "", func(key, proposedVal string) {
if containsEnvVar(proposedVal) {
return
}
if proposedVal == "<nil>" || proposedVal == "" {
return
}
apiVal := getNestedValue(apiSection, key)
if apiVal == "<nil>" || apiVal == "" {
return
}
compareAPI, compareProposed := apiVal, proposedVal
if looksLikeJSON(apiVal) && looksLikeJSON(proposedVal) {
compareAPI = normalizeJSON(apiVal)
compareProposed = normalizeJSON(proposedVal)
}
if compareAPI != compareProposed {
changes = append(changes, ConfigChange{
Section: section,
Key: key,
Old: apiVal,
New: proposedVal,
})
}
})
changes = append(changes, diffFlat(section, "", proposedMap, apiSection, nil, false)...)
}

return changes, skipped
Expand Down Expand Up @@ -1956,31 +1933,7 @@ func diffTeamSettings(current, proposed map[string]any) ([]ConfigChange, []strin
continue
}

// Same guards as diffConfig: skip env var placeholders Fleet
// substitutes, and skip keys the API does not expose a value for,
// since "" cannot be distinguished from "not reported".
flattenMap(proposedMap, section, func(key, proposedVal string) {
if containsEnvVar(proposedVal) || proposedVal == "<nil>" || proposedVal == "" {
return
}
apiVal := getNestedValue(apiSection, strings.TrimPrefix(key, section+"."))
if apiVal == "<nil>" || apiVal == "" {
return
}
compareAPI, compareProposed := apiVal, proposedVal
if looksLikeJSON(apiVal) && looksLikeJSON(proposedVal) {
compareAPI = normalizeJSON(apiVal)
compareProposed = normalizeJSON(proposedVal)
}
if compareAPI != compareProposed {
changes = append(changes, ConfigChange{
Section: "settings",
Key: key,
Old: apiVal,
New: proposedVal,
})
}
})
changes = append(changes, diffFlat("settings", section+".", proposedMap, apiSection, nil, false)...)
}

// flattenMap walks maps in random order; sort so output is stable.
Expand All @@ -1990,6 +1943,155 @@ func diffTeamSettings(current, proposed map[string]any) ([]ConfigChange, []strin
return changes, skipped
}

// diffFlat compares every leaf of proposed with the value at the same
// dot-path in apiSection (renamed by apiKey when set), and reports each
// difference under section with keyPrefix prepended to the key.
//
// Leaves that reference an env var are skipped: Fleet substitutes them, so the
// stored value never matches. So are keys the API reports no value for, since
// "" cannot be told apart from "not reported" (agent_options sub-keys,
// sso_settings, ...). With reportEmpty, a key Fleet reports as "" is instead
// an unset value being set (first-time macos_updates enforcement), unless the
// proposed value is a file path, which Fleet stores by name and reports as "".
//
// Values under a secret-looking key are compared but rendered as (redacted):
// the output is posted to MRs.
func diffFlat(section, keyPrefix string, proposed, apiSection map[string]any, apiKey func(string) string, reportEmpty bool) []ConfigChange {
var changes []ConfigChange
flattenMap(proposed, "", func(key, proposedVal string) {
if containsEnvVar(proposedVal) || proposedVal == "<nil>" || proposedVal == "" {
return
}
lookup := key
if apiKey != nil {
lookup = apiKey(key)
}
apiVal, found := lookupNested(apiSection, lookup)
if !found || apiVal == "<nil>" {
return
}
if apiVal == "" && (!reportEmpty || strings.ContainsAny(proposedVal, `/\`)) {
return
}
compareAPI, compareProposed := apiVal, proposedVal
if looksLikeJSON(apiVal) && looksLikeJSON(proposedVal) {
compareAPI = normalizeJSON(apiVal)
compareProposed = normalizeJSON(proposedVal)
}
if compareAPI != compareProposed {
if isSecretKey(key) {
apiVal, proposedVal = redact(apiVal), redact(proposedVal)
}
changes = append(changes, ConfigChange{
Section: section,
Key: keyPrefix + key,
Old: apiVal,
New: proposedVal,
})
}
})
// flattenMap walks maps in random order; sort so output is stable.
sort.Slice(changes, func(i, j int) bool { return changes[i].Key < changes[j].Key })
return changes
}

// secretKeyPattern matches any segment of a settings key path that names a
// credential (aws_secret_access_key, enroll_secret, api_token, ...), so
// leaves nested under a credential block are covered too.
var secretKeyPattern = regexp.MustCompile(`(?i)(secret|password|passwd|token|credential|private_key|access_key|api_key)`)

func isSecretKey(key string) bool {
return secretKeyPattern.MatchString(key)
}

// redact hides a secret value, keeping "" so an unset value still reads as one.
func redact(v string) string {
if v == "" {
return ""
}
return "(redacted)"
}

// controlsDiffedElsewhere are controls keys resolved into the profile and
// script diffs, so the settings diff leaves them alone.
var controlsDiffedElsewhere = map[string]bool{
"scripts": true,
"apple_settings": true,
"macos_settings": true,
"windows_settings": true,
"android_settings": true,
}

// teamMacOSSetupKeys maps setup_experience sub-keys to the legacy names a
// team's mdm.macos_setup still uses. Global config reports setup_experience
// under its modern names, so only teams need this.
var teamMacOSSetupKeys = map[string]string{
"apple_setup_assistant": "macos_setup_assistant",
"apple_enable_release_device_manually": "enable_release_device_manually",
"macos_script": "script",
"macos_bootstrap_package": "bootstrap_package",
"macos_manual_agent_install": "manual_agent_install",
"enable_create_local_admin_account": "enable_managed_local_account",
}

// teamControlsAPIKey maps a team controls dot-path to where the team's mdm
// object reports it.
func teamControlsAPIKey(key string) string {
sub, ok := strings.CutPrefix(key, "setup_experience.")
if !ok {
return key
}
if legacy, ok := teamMacOSSetupKeys[sub]; ok {
sub = legacy
}
return "macos_setup." + sub
}

// diffControls compares a team file's controls (minus scripts and profiles)
// with an mdm object: the team's for a real team, global config's for the
// no-team bucket. apiKey renames keys for the team API; nil for global.
func diffControls(mdm, controls map[string]any, apiKey func(string) string) []ConfigChange {
rest := settingsControls(controls)
if len(rest) == 0 || mdm == nil {
return nil
}
return diffFlat("controls", "", rest, mdm, apiKey, true)
}

// settingsControls returns controls without the keys diffed elsewhere.
func settingsControls(controls map[string]any) map[string]any {
rest := make(map[string]any, len(controls))
for k, v := range controls {
if !controlsDiffedElsewhere[k] {
rest[k] = v
}
}
return rest
}

// diffTeamConfig returns a team's settings, controls, and agent_options
// changes against the raw team object from GET /teams, plus the settings
// sub-keys that could not be diffed.
func diffTeamConfig(current map[string]any, team parser.ParsedTeam) ([]ConfigChange, []string) {
changes, skipped := diffTeamSettings(current, team.Settings)
if len(settingsControls(team.Controls)) > 0 {
if mdm, ok := current["mdm"].(map[string]any); ok {
changes = append(changes, diffControls(mdm, team.Controls, teamControlsAPIKey)...)
} else {
skipped = append(skipped, "controls")
}
}
if len(team.AgentOptions) > 0 {
if agent, ok := current["agent_options"].(map[string]any); ok {
changes = append(changes, diffFlat("agent_options", "", team.AgentOptions, agent, nil, false)...)
} else {
skipped = append(skipped, "agent_options")
}
}
sort.Strings(skipped)
return changes, skipped
}

// containsEnvVar returns true if the string contains a $ (env var placeholder).
func containsEnvVar(s string) bool {
return strings.Contains(s, "$")
Expand Down Expand Up @@ -2099,38 +2201,49 @@ func flattenMap(m map[string]any, prefix string, fn func(key, val string)) {
fn(fullKey, string(b))
}
default:
fn(fullKey, fmt.Sprint(v))
fn(fullKey, formatLeaf(v))
}
}
}

// getNestedValue retrieves a value from a nested map using a dot-separated key.
// Slices are JSON-serialized to match flattenMap's output format.
func getNestedValue(m map[string]any, key string) string {
// formatLeaf renders a scalar for comparison. JSON decodes every number as
// float64, and fmt prints a large one in exponent form (2.62144e+07) that
// never equals the YAML integer, so floats are printed in plain decimal.
func formatLeaf(v any) string {
if f, ok := v.(float64); ok {
return strconv.FormatFloat(f, 'f', -1, 64)
}
return fmt.Sprint(v)
}

// lookupNested retrieves a value from a nested map using a dot-separated key,
// and reports whether the key exists. Slices are JSON-serialized to match
// flattenMap's output format.
func lookupNested(m map[string]any, key string) (string, bool) {
parts := strings.Split(key, ".")
current := m
for i, part := range parts {
v, ok := current[part]
if !ok {
return ""
return "", false
}
if i == len(parts)-1 {
if slice, ok := v.([]any); ok {
b, err := json.Marshal(slice)
if err != nil {
return fmt.Sprint(v)
return fmt.Sprint(v), true
}
return string(b)
return string(b), true
}
return fmt.Sprint(v)
return formatLeaf(v), true
}
if next, ok := v.(map[string]any); ok {
current = next
} else {
return ""
next, ok := v.(map[string]any)
if !ok {
return "", false
}
current = next
}
return ""
return "", false
}

// ---------- Helpers ----------
Expand Down
Loading
Loading