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.

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). Two `org_settings` keys Fleet serves outside `/config` are fetched and merged in first: `certificate_authorities.ndes_scep_proxy` (from `/certificate_authorities`) and `mdm.end_user_license_agreement` (compared by file name, since Fleet stores the upload by name). Controls Fleet keeps on global config only (`windows_migration_enabled`, `apple_require_hardware_attestation`, ...) are flagged with a warning when a fleet file sets them, since Fleet accepts them there but ignores them. 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).
A resource Fleet refuses is skipped, never diffed as empty. Only a 403 is reported as the token lacking access; a 404 or 402 is reported as the HTTP status Fleet returned, since it can just as well be a server without the endpoint or a Fleet Free license. 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). Two `org_settings` keys Fleet serves outside `/config` are fetched and merged in first: `certificate_authorities.ndes_scep_proxy` (from `/certificate_authorities`) and `mdm.end_user_license_agreement` (compared by file name, since Fleet stores the upload by name). Controls Fleet keeps on global config only (`windows_migration_enabled`, `apple_require_hardware_attestation`, ...) are flagged with a warning when a fleet file sets them, since Fleet accepts them there but ignores them. 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
77 changes: 43 additions & 34 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,30 @@ func (e *HTTPError) Error() string {
return fmt.Sprintf("HTTP %d from %s: %s", e.StatusCode, e.URL, body)
}

// isPermissionError returns true if err is an HTTP 403 or 404, which indicates
// the API token lacks access to this endpoint (e.g. gitops role restrictions).
// refusedStatus returns the HTTP status of err.
func refusedStatus(err error) int {
var httpErr *HTTPError
if errors.As(err, &httpErr) {
return httpErr.StatusCode
}
return 0
}

// isPermissionError returns true if err is an HTTP 402, 403, or 404: Fleet
// refused the resource, and the plan skips it instead of failing. Only a 403
// is certainly the token (e.g. gitops role restrictions); a 404 can be a
// server without the endpoint, and a 402 a Premium-only endpoint on Fleet
// Free.
func isPermissionError(err error) bool {
var httpErr *HTTPError
if !errors.As(err, &httpErr) {
return false
}
return httpErr.StatusCode == http.StatusForbidden || httpErr.StatusCode == http.StatusNotFound
switch httpErr.StatusCode {
case http.StatusPaymentRequired, http.StatusForbidden, http.StatusNotFound:
return true
}
return false
}

// maxProfileContentSize caps a downloaded configuration profile. It matches
Expand Down Expand Up @@ -189,12 +205,13 @@ type FleetState struct {
// absent too — Fleet only reports configured packages through the teams list,
// which excludes this bucket.
type NoTeam struct {
Policies []Policy
Profiles []Profile
Scripts []Script
PoliciesUnavailable bool
ProfilesUnavailable bool
ScriptsUnavailable bool
Policies []Policy
Profiles []Profile
Scripts []Script
// HTTP status (403 or 404) that refused each resource; 0 when it was read.
PoliciesUnavailable int
ProfilesUnavailable int
ScriptsUnavailable int
}

// FetchOptions selects the optional scopes FetchAll retrieves. Both cost extra
Expand All @@ -218,9 +235,9 @@ type Team struct {
Profiles []Profile // populated by GetProfiles
Scripts []Script `json:"-"` // populated by GetScripts
SoftwareTitles []SoftwareTitle
SoftwareUnavailable bool // true when GetSoftware returned 403/404 (token lacks permission)
ProfilesUnavailable bool // true when GetProfiles returned 403/404 (token lacks permission)
ScriptsUnavailable bool // true when GetScripts returned 403/404 (token lacks permission)
SoftwareUnavailable int // HTTP status (403/404) that refused GetSoftware; 0 when read
ProfilesUnavailable int // HTTP status (403/404) that refused GetProfiles; 0 when read
ScriptsUnavailable int // HTTP status (403/404) that refused GetScripts; 0 when read

// Settings holds the raw team object as returned by the API, so the
// settings blocks a team YAML configures (webhook_settings,
Expand Down Expand Up @@ -545,7 +562,7 @@ func (c *Client) AddMovedConfig(ctx context.Context, cfg map[string]any) error {
case err == nil:
// Read, so a missing NDES proxy diffs as one being added.
cfg["certificate_authorities"] = map[string]any{}
case !unreadable(err):
case !isPermissionError(err):
return fmt.Errorf("fetching certificate authorities: %w", err)
}
for _, ca := range cas.CertificateAuthorities {
Expand All @@ -559,7 +576,7 @@ func (c *Client) AddMovedConfig(ctx context.Context, cfg map[string]any) error {
}
err := c.get(ctx, fmt.Sprintf("/api/v1/fleet/certificate_authorities/%d", ca.ID), nil, &ndes)
if err != nil {
if unreadable(err) {
if isPermissionError(err) {
delete(cfg, "certificate_authorities")
break
}
Expand All @@ -577,7 +594,7 @@ func (c *Client) AddMovedConfig(ctx context.Context, cfg map[string]any) error {
var httpErr *HTTPError
switch {
case err == nil, errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound:
case unreadable(err):
case isPermissionError(err):
return nil
default:
return fmt.Errorf("fetching EULA metadata: %w", err)
Expand All @@ -591,14 +608,6 @@ func (c *Client) AddMovedConfig(ctx context.Context, cfg map[string]any) error {
return nil
}

// unreadable reports whether err means the setting cannot be read: no
// permission, an endpoint this server lacks, or a Premium-only endpoint on
// Fleet Free (402).
func unreadable(err error) bool {
var httpErr *HTTPError
return isPermissionError(err) || errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusPaymentRequired
}

// GetTeams fetches all teams with pagination.
func (c *Client) GetTeams(ctx context.Context) ([]Team, error) {
var all []Team
Expand Down Expand Up @@ -1133,7 +1142,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
noTeam.PoliciesUnavailable = true
noTeam.PoliciesUnavailable = refusedStatus(err)
return nil
}
noTeam.Policies = policies
Expand All @@ -1145,7 +1154,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
noTeam.ProfilesUnavailable = true
noTeam.ProfilesUnavailable = refusedStatus(err)
return nil
}
noTeam.Profiles = profiles
Expand All @@ -1157,7 +1166,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
noTeam.ScriptsUnavailable = true
noTeam.ScriptsUnavailable = refusedStatus(err)
return nil
}
noTeam.Scripts = scripts
Expand All @@ -1171,11 +1180,11 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
policies []Policy
queries []Query
profiles []Profile
profilesUnavailable bool
profilesUnavailable int
softwareTitles []SoftwareTitle
softwareUnavailable bool
softwareUnavailable int
scripts []Script
scriptsUnavailable bool
scriptsUnavailable int
}
teamPartials := make([]teamPartial, len(teams))

Expand Down Expand Up @@ -1209,7 +1218,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
teamPartials[idx].profilesUnavailable = true
teamPartials[idx].profilesUnavailable = refusedStatus(err)
profiles = nil
}
teamPartials[idx].profiles = profiles
Expand All @@ -1222,7 +1231,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
teamPartials[idx].softwareUnavailable = true
teamPartials[idx].softwareUnavailable = refusedStatus(err)
softwareTitles = nil
}
teamPartials[idx].softwareTitles = softwareTitles
Expand All @@ -1235,7 +1244,7 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if !isPermissionError(err) {
return err
}
teamPartials[idx].scriptsUnavailable = true
teamPartials[idx].scriptsUnavailable = refusedStatus(err)
scripts = nil
}
teamPartials[idx].scripts = scripts
Expand Down Expand Up @@ -1268,15 +1277,15 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
}

if noTeam != nil {
if !noTeam.ScriptsUnavailable && len(noTeam.Scripts) > 0 {
if noTeam.ScriptsUnavailable == 0 && len(noTeam.Scripts) > 0 {
c.EnrichScriptContents(ctx, noTeam.Scripts)
}
state.NoTeam = noTeam
}

// Enrich script contents (second pass, needs script IDs from first pass)
for i := range teamResults {
if !teamResults[i].ScriptsUnavailable && len(teamResults[i].Scripts) > 0 {
if teamResults[i].ScriptsUnavailable == 0 && len(teamResults[i].Scripts) > 0 {
c.EnrichScriptContents(ctx, teamResults[i].Scripts)
}
}
Expand Down
8 changes: 5 additions & 3 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,7 @@ func TestFetchAllNoTeamPermissionErrors(t *testing.T) {
fmt.Fprint(w, `{"fleet_maintained_apps":[]}`)
})
mux.HandleFunc("/api/v1/fleet/teams/0/policies", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.WriteHeader(http.StatusPaymentRequired) // Premium-only on Fleet Free
})
mux.HandleFunc("/api/v1/fleet/configuration_profiles", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
Expand All @@ -1296,8 +1296,10 @@ func TestFetchAllNoTeamPermissionErrors(t *testing.T) {
if state.NoTeam == nil {
t.Fatal("NoTeam: got nil")
}
if !state.NoTeam.PoliciesUnavailable || !state.NoTeam.ProfilesUnavailable || !state.NoTeam.ScriptsUnavailable {
t.Errorf("unavailable flags: got %+v, want all true", state.NoTeam)
// The refusing status is kept: only a 403 is certainly the token.
nt := state.NoTeam
if nt.PoliciesUnavailable != 402 || nt.ProfilesUnavailable != 403 || nt.ScriptsUnavailable != 404 {
t.Errorf("unavailable statuses: got %+v, want 402/403/404", nt)
}
}

Expand Down
52 changes: 31 additions & 21 deletions internal/diff/differ.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/json"
"fmt"
"maps"
"net/http"
"os"
"reflect"
"regexp"
Expand Down Expand Up @@ -213,22 +214,22 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, globalMDM map[string]an
return
}

if current.PoliciesUnavailable {
result.Errors = append(result.Errors, "policies diff skipped: API token lacks permission to read no-team policies")
if current.PoliciesUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("policies", current.PoliciesUnavailable, "no-team policies"))
} else {
result.Policies = diffPolicies(current.Policies, proposed.Policies)
}

if current.ProfilesUnavailable {
result.Errors = append(result.Errors, "profiles diff skipped: API token lacks permission to read profiles")
if current.ProfilesUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("profiles", current.ProfilesUnavailable, "profiles"))
} else {
var warnings []string
result.Profiles, warnings = diffProfiles(current.Profiles, proposed.Profiles, changedFiles, cfg.profileEnricher)
result.Errors = append(result.Errors, warnings...)
}

if current.ScriptsUnavailable {
result.Errors = append(result.Errors, "scripts diff skipped: API token lacks permission to read scripts")
if current.ScriptsUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("scripts", current.ScriptsUnavailable, "scripts"))
} else {
result.Scripts = diffScripts(current.Scripts, proposed.Scripts)
}
Expand Down Expand Up @@ -259,13 +260,13 @@ func diffNoTeam(result *DiffResult, current *api.NoTeam, globalMDM map[string]an
if cfg.baseline != nil {
if baseTeam, ok := findBaselineNoTeam(cfg.baseline); ok {
base := DiffResult{}
if !current.PoliciesUnavailable {
if current.PoliciesUnavailable == 0 {
base.Policies = diffPolicies(current.Policies, baseTeam.Policies)
}
if !current.ProfilesUnavailable {
if current.ProfilesUnavailable == 0 {
base.Profiles, _ = diffProfiles(current.Profiles, baseTeam.Profiles, nil, cfg.profileEnricher)
}
if !current.ScriptsUnavailable {
if current.ScriptsUnavailable == 0 {
base.Scripts = diffScripts(current.Scripts, baseTeam.Scripts)
}
result.Policies = markDrift(result.Policies, base.Policies)
Expand Down Expand Up @@ -431,8 +432,8 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st
// can reuse the same enriched state.
enrichedSoftware := currentTeam.Software

if currentTeam.SoftwareUnavailable {
result.Errors = append(result.Errors, "software diff skipped: API token lacks permission to read software titles")
if currentTeam.SoftwareUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("software", currentTeam.SoftwareUnavailable, "software titles"))
} else {
// Fleet's /teams API may return fleet_maintained_apps: null, or
// return a partial list (e.g., only macOS FMAs while Windows FMAs
Expand All @@ -451,16 +452,16 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st
result.Errors = append(result.Errors, softwareWarnings...)
}

if currentTeam.ProfilesUnavailable {
result.Errors = append(result.Errors, "profiles diff skipped: API token lacks permission to read profiles")
if currentTeam.ProfilesUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("profiles", currentTeam.ProfilesUnavailable, "profiles"))
} else {
var profileWarnings []string
result.Profiles, profileWarnings = diffProfiles(currentTeam.Profiles, proposedTeam.Profiles, changedFiles, cfg.profileEnricher)
result.Errors = append(result.Errors, profileWarnings...)
}

if currentTeam.ScriptsUnavailable {
result.Errors = append(result.Errors, "scripts diff skipped: API token lacks permission to read scripts")
if currentTeam.ScriptsUnavailable != 0 {
result.Errors = append(result.Errors, skippedDiff("scripts", currentTeam.ScriptsUnavailable, "scripts"))
} else {
result.Scripts = diffScripts(currentTeam.Scripts, proposedTeam.Scripts)
}
Expand All @@ -482,13 +483,13 @@ func Diff(current *api.FleetState, proposed *parser.ParsedRepo, teamFilters []st
baseDiff.Policies = diffPolicies(currentTeam.Policies, baseTeam.Policies)
baseDiff.Queries = diffQueries(currentTeam.Queries, baseTeam.Queries)
baseDiff.Config, _, _ = diffTeamConfig(currentTeam.Settings, baseTeam)
if !currentTeam.SoftwareUnavailable {
if currentTeam.SoftwareUnavailable == 0 {
baseDiff.Software, _ = diffSoftware(enrichedSoftware, baseTeam.Software)
}
if !currentTeam.ProfilesUnavailable {
if currentTeam.ProfilesUnavailable == 0 {
baseDiff.Profiles, _ = diffProfiles(currentTeam.Profiles, baseTeam.Profiles, nil, cfg.profileEnricher)
}
if !currentTeam.ScriptsUnavailable {
if currentTeam.ScriptsUnavailable == 0 {
baseDiff.Scripts = diffScripts(currentTeam.Scripts, baseTeam.Scripts)
}
vlog(cfg.verbose, "[%s] baseline diff: policies=%s queries=%s software=%s",
Expand Down Expand Up @@ -1953,6 +1954,16 @@ func diffNDESAdded(apiConfig, orgSettings map[string]any) ([]ConfigChange, map[s
return changes, orgSettings
}

// skippedDiff says why a resource diff was skipped. Only a 403 is certainly
// the token; a 404 can be a server without the endpoint, so for anything
// else it states what Fleet returned and does not guess.
func skippedDiff(kind string, status int, what string) string {
if status == http.StatusForbidden {
return kind + " diff skipped: API token lacks permission to read " + what
}
return fmt.Sprintf("%s diff skipped: Fleet returned HTTP %d for %s", kind, status, what)
}

// teamSettingsSections maps a sub-key of a team's `settings:` block to the
// field on the Fleet team object that holds its live value. Everything Fleet
// exposes on GET /teams is listed here; a sub-key that is not is reported as
Expand Down Expand Up @@ -1996,9 +2007,8 @@ func diffTeamSettings(current, proposed map[string]any) ([]ConfigChange, []strin
}
apiSection, ok := current[apiKey].(map[string]any)
if !ok {
// Fleet did not return this section (older server, or a token
// without permission to see it): say so rather than reporting
// every proposed key as a change.
// Fleet did not return this section: say so rather than
// reporting every proposed key as a change.
skipped = append(skipped, "settings."+section)
continue
}
Expand Down
27 changes: 24 additions & 3 deletions internal/diff/differ_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2812,9 +2812,9 @@ func TestDiffNoTeamUnavailableResources(t *testing.T) {
Teams: []api.Team{},
Labels: []api.Label{},
NoTeam: &api.NoTeam{
PoliciesUnavailable: true,
ProfilesUnavailable: true,
ScriptsUnavailable: true,
PoliciesUnavailable: 403,
ProfilesUnavailable: 403,
ScriptsUnavailable: 403,
},
}
proposed := &parser.ParsedRepo{Teams: []parser.ParsedTeam{{
Expand Down Expand Up @@ -2844,6 +2844,27 @@ func TestDiffNoTeamUnavailableResources(t *testing.T) {
}
}

func TestDiffUnavailableBlamesTokenOnlyOn403(t *testing.T) {
// A 404 or 402 is as likely the server or its license as the token, so
// only a 403 may be reported as a token permission problem.
current := &api.FleetState{
Teams: []api.Team{},
Labels: []api.Label{},
NoTeam: &api.NoTeam{PoliciesUnavailable: 403, ProfilesUnavailable: 404, ScriptsUnavailable: 402},
}
proposed := &parser.ParsedRepo{Teams: []parser.ParsedTeam{{Name: "No team", SourceFile: "teams/no-team.yml"}}}
got := Diff(current, proposed, nil, nil)[0].Errors
for _, want := range []string{
"policies diff skipped: API token lacks permission to read no-team policies",
"profiles diff skipped: Fleet returned HTTP 404 for profiles",
"scripts diff skipped: Fleet returned HTTP 402 for scripts",
} {
if !slices.Contains(got, want) {
t.Errorf("missing %q in %v", want, got)
}
}
}

func TestDiffNoTeamSoftwareIsReportedAsSkipped(t *testing.T) {
current := &api.FleetState{Teams: []api.Team{}, Labels: []api.Label{}, NoTeam: &api.NoTeam{}}
proposed := &parser.ParsedRepo{Teams: []parser.ParsedTeam{{
Expand Down
Loading
Loading