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
2 changes: 1 addition & 1 deletion docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ 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).
Configured keys the API does not report at all are not guessed at: they are listed in a "Not diffed" note (keys that are present but empty are still skipped silently). 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
46 changes: 31 additions & 15 deletions internal/diff/differ.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type DiffResult struct {
LabelChanges ResourceDiff // label definitions (global scope only)
Config []ConfigChange // org_settings, agent_options, controls diffs
Errors []string
SkippedConfigSections []string // config sections absent from API (e.g. "agent_options")
SkippedConfigSections []string // configured sections or keys the API does not report (e.g. "agent_options", "controls.windows_migration_enabled")
}

// ConfigChange represents a change in a top-level config section.
Expand Down Expand Up @@ -233,7 +233,7 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, globalMDM map[string]an
}

// The no-team file's controls are Fleet's global MDM settings.
result.Config = diffControls(globalMDM, proposed.Controls, nil)
result.Config, result.SkippedConfigSections = 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
Expand Down Expand Up @@ -270,7 +270,8 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, globalMDM map[string]an
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))
baseConfig, _ := diffControls(globalMDM, baseTeam.Controls, nil)
result.Config = markConfigDrift(result.Config, baseConfig)
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 @@ -1877,7 +1878,9 @@ func diffConfig(apiConfig map[string]any, proposed *parser.ParsedGlobal) ([]Conf
continue
}

changes = append(changes, diffFlat(section, "", proposedMap, apiSection, nil, false)...)
c, nr := diffFlat(section, "", proposedMap, apiSection, nil, false)
changes = append(changes, c...)
skipped = append(skipped, nr...)
}

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

changes = append(changes, diffFlat("settings", section+".", proposedMap, apiSection, nil, false)...)
c, nr := diffFlat("settings", section+".", proposedMap, apiSection, nil, false)
changes = append(changes, c...)
skipped = append(skipped, nr...)
}

// flattenMap walks maps in random order; sort so output is stable.
Expand All @@ -1950,14 +1955,15 @@ func diffTeamSettings(current, proposed map[string]any) ([]ConfigChange, []strin
// 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
// sso_settings, ...). Keys the API does not report at all are returned as
// notReported ("section.key"), so callers can say they were not diffed.
// 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
func diffFlat(section, keyPrefix string, proposed, apiSection map[string]any, apiKey func(string) string, reportEmpty bool) (changes []ConfigChange, notReported []string) {
flattenMap(proposed, "", func(key, proposedVal string) {
if containsEnvVar(proposedVal) || proposedVal == "<nil>" || proposedVal == "" {
return
Expand All @@ -1967,7 +1973,11 @@ func diffFlat(section, keyPrefix string, proposed, apiSection map[string]any, ap
lookup = apiKey(key)
}
apiVal, found := lookupNested(apiSection, lookup)
if !found || apiVal == "<nil>" {
if !found {
notReported = append(notReported, section+"."+keyPrefix+key)
return
}
if apiVal == "<nil>" {
return
}
if apiVal == "" && (!reportEmpty || strings.ContainsAny(proposedVal, `/\`)) {
Expand All @@ -1992,7 +2002,8 @@ func diffFlat(section, keyPrefix string, proposed, apiSection map[string]any, ap
})
// 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
sort.Strings(notReported)
return changes, notReported
}

// secretKeyPattern matches any segment of a settings key path that names a
Expand Down Expand Up @@ -2050,10 +2061,13 @@ func teamControlsAPIKey(key string) string {
// 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 {
func diffControls(mdm, controls map[string]any, apiKey func(string) string) ([]ConfigChange, []string) {
rest := settingsControls(controls)
if len(rest) == 0 || mdm == nil {
return nil
if len(rest) == 0 {
return nil, nil
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if mdm == nil {
return nil, []string{"controls"}
}
return diffFlat("controls", "", rest, mdm, apiKey, true)
}
Expand All @@ -2076,14 +2090,16 @@ func diffTeamConfig(current map[string]any, team parser.ParsedTeam) ([]ConfigCha
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)...)
c, nr := diffControls(mdm, team.Controls, teamControlsAPIKey)
changes, skipped = append(changes, c...), append(skipped, nr...)
} 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)...)
c, nr := diffFlat("agent_options", "", team.AgentOptions, agent, nil, false)
changes, skipped = append(changes, c...), append(skipped, nr...)
} else {
skipped = append(skipped, "agent_options")
}
Expand Down
26 changes: 18 additions & 8 deletions internal/diff/differ_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2542,13 +2542,13 @@ func TestDiffTeamSettings(t *testing.T) {
},
},
{
// The API does not report a value for this key, so "" cannot be
// told apart from "Fleet has no opinion" -- reporting it would be
// a guess.
name: "key absent from the API section is not reported",
// The API does not report this key at all: not a change, but
// listed as not diffed rather than dropped without a word.
name: "key absent from the API section is listed as not diffed",
proposed: map[string]any{
"features": map[string]any{"enable_future_thing": true},
},
wantSkipped: []string{"settings.features.enable_future_thing"},
},
{
// List values are compared as serialized JSON, element order
Expand Down Expand Up @@ -3989,11 +3989,11 @@ func TestDiffNoTeamControls(t *testing.T) {
func TestDiffFlatLargeNumbers(t *testing.T) {
api := map[string]any{"command_line_flags": map[string]any{"logger_rotate_size": float64(26214400), "ratio": 0.5}}
proposed := map[string]any{"command_line_flags": map[string]any{"logger_rotate_size": 26214400, "ratio": 0.5}}
if got := diffFlat("agent_options", "", proposed, api, nil, false); len(got) != 0 {
if got, _ := diffFlat("agent_options", "", proposed, api, nil, false); len(got) != 0 {
t.Errorf("got %+v, want no changes", got)
}
proposed["command_line_flags"].(map[string]any)["logger_rotate_size"] = 10485760
got := diffFlat("agent_options", "", proposed, api, nil, false)
got, _ := diffFlat("agent_options", "", proposed, api, nil, false)
if len(got) != 1 || got[0].Old != "26214400" || got[0].New != "10485760" {
t.Errorf("got %+v, want 26214400 -> 10485760", got)
}
Expand All @@ -4011,7 +4011,7 @@ func TestDiffControlsEmptyAPIValue(t *testing.T) {
// Fleet keeps setup scripts by name and reports "" here: not a change.
"setup_experience": map[string]any{"macos_script": "../lib/setup.sh"},
}
got := diffControls(mdm, controls, teamControlsAPIKey)
got, _ := diffControls(mdm, controls, teamControlsAPIKey)
if len(got) != 1 || got[0].Key != "macos_updates.minimum_version" || got[0].Old != "" || got[0].New != "27.0.1" {
t.Errorf("got %+v, want only macos_updates.minimum_version \"\" -> 27.0.1", got)
}
Expand All @@ -4035,7 +4035,7 @@ func TestDiffFlatRedactsSecrets(t *testing.T) {
proposed := map[string]any{"config": map[string]any{"options": map[string]any{
"aws_secret_access_key": "new-secret", "logger_tls_period": 20,
}}}
got := diffFlat("agent_options", "", proposed, api, nil, false)
got, _ := diffFlat("agent_options", "", proposed, api, nil, false)
for _, c := range got {
if strings.Contains(c.Old+c.New, "secret") && c.Key != "config.options.aws_secret_access_key" {
t.Errorf("leaked: %+v", c)
Expand Down Expand Up @@ -4074,3 +4074,13 @@ func TestIsSecretKey(t *testing.T) {
}
}
}

func TestDiffControlsWithoutMDM(t *testing.T) {
_, skipped := diffControls(nil, map[string]any{"enable_disk_encryption": true}, nil)
if !slices.Equal(skipped, []string{"controls"}) {
t.Errorf("skipped: got %v, want [controls]", skipped)
}
if _, skipped := diffControls(nil, map[string]any{"scripts": []any{}}, nil); skipped != nil {
t.Errorf("only scripts/profiles configured: got skipped %v, want none", skipped)
}
}
30 changes: 27 additions & 3 deletions internal/output/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ func RenderDiffMarkdown(results []diff.DiffResult, opts MarkdownOptions) string

if !HasChanges(results) {
sb.WriteString("No changes detected. Your branch matches the current Fleet state.\n")
if note := buildNotDiffedNote(results); note != "" {
fmt.Fprintf(&sb, "\nℹ️ %s\n", note)
}
writeMarker(&sb, opts)
return sb.String()
}
Expand Down Expand Up @@ -193,6 +196,9 @@ func RenderDiffMarkdown(results []diff.DiffResult, opts MarkdownOptions) string
if warning := buildPermissionWarning(results); warning != "" {
fmt.Fprintf(&sb, "\n⚠️ %s\n", warning)
}
if note := buildNotDiffedNote(results); note != "" {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
fmt.Fprintf(&sb, "\nℹ️ %s\n", note)
}

if totalDrift > 0 {
fmt.Fprintf(&sb, "\n> **NOTE:** %d %s marked _not from this change_ already %s between the base branch and Fleet: made outside gitops, or merged but not yet deployed. Merging this applies %s too.\n",
Expand Down Expand Up @@ -342,6 +348,27 @@ func mdSummaryLine(added, modified, deleted int) string {
return "**" + strings.Join(parts, ", ") + "**"
}

// buildNotDiffedNote lists configured settings the plan could not compare:
// keys Fleet does not report, and settings sections it did not return.
// Either can be a rename on the Fleet side or a token that cannot read them,
// so the note does not claim which.
func buildNotDiffedNote(results []diff.DiffResult) string {
seen := make(map[string]bool)
for _, r := range results {
for _, s := range r.SkippedConfigSections {
seen[s] = true
}
}
if len(seen) == 0 {
return ""
}
keys := sortedKeys(seen)
for i, k := range keys {
keys[i] = mdCodeSpan(k)
}
return "Not diffed (Fleet does not report these, or the token cannot read them): " + strings.Join(keys, ", ")
}

func buildPermissionWarning(results []diff.DiffResult) string {
unavailable := make(map[string]bool)

Expand All @@ -351,9 +378,6 @@ func buildPermissionWarning(results []diff.DiffResult) string {
unavailable[resource] = true
}
}
for _, s := range r.SkippedConfigSections {
unavailable[s] = true
}
}

hasLabels, hasLabelCounts := false, false
Expand Down
19 changes: 19 additions & 0 deletions internal/output/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,25 @@ func TestRenderDiffMarkdown(t *testing.T) {
},
wantNone: []string{"No changes detected"},
},
{
// The note must not be hidden by a plan with nothing else in it,
// and must not turn such a plan into one with changes.
name: "not diffed note shows on a plan with no changes",
results: []diff.DiffResult{
{Team: "(global)", SkippedConfigSections: []string{"controls.windows_migration_enabled"}},
},
wantAll: []string{"No changes detected", "ℹ️ Not diffed (Fleet does not report these, or the token cannot read them): `controls.windows_migration_enabled`"},
wantNone: []string{"| Change | Team"},
},
{
name: "settings Fleet does not report are listed as not diffed, not blamed on the token",
results: []diff.DiffResult{
{Team: "Workstations", SkippedConfigSections: []string{"controls.windows_migration_enabled"}, Policies: diff.ResourceDiff{Added: []diff.ResourceChange{{Name: "P"}}}},
{Team: "(global)", SkippedConfigSections: []string{"org_settings.mdm.end_user_license_agreement", "controls.windows_migration_enabled"}},
},
wantAll: []string{"ℹ️ Not diffed (Fleet does not report these, or the token cannot read them): `controls.windows_migration_enabled`, `org_settings.mdm.end_user_license_agreement`"},
wantNone: []string{"Token lacks read access"},
},
{
name: "single drifted label uses singular note",
results: []diff.DiffResult{{
Expand Down
Loading