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
5 changes: 4 additions & 1 deletion docs/API-Endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ All read-only. fleet-plan never writes to your Fleet server.
| Method | Endpoint | Purpose |
|--------|----------|---------|
| `GET` | `/api/v1/fleet/config` | Global config (org_settings, agent_options, controls) |
| `GET` | `/api/v1/fleet/certificate_authorities` | CA list, to find the NDES SCEP proxy (CAs are no longer in `/config`) |
| `GET` | `/api/v1/fleet/certificate_authorities/{id}` | NDES SCEP proxy `url`, `admin_url`, `username` (password is write-only) |
| `GET` | `/api/v1/fleet/setup_experience/eula/metadata` | Uploaded EULA file name (404 when none is uploaded) |
| `GET` | `/api/v1/fleet/teams` | Team list + embedded software config + team settings (`webhook_settings`, `host_expiry_settings`, `integrations`, `features`) |
| `GET` | `/api/v1/fleet/labels` | Label definitions (diffed against `default.yml` labels), validation, and host counts |
| `GET` | `/api/v1/fleet/teams/{id}/policies` | Per-team policies |
Expand All @@ -19,7 +22,7 @@ All read-only. fleet-plan never writes to your Fleet server.
| `GET` | `/api/v1/fleet/scripts/{id}?alt=media` | Script content download |
| `GET` | `/api/v1/fleet/software/titles/{id}` | Software title detail: install/uninstall scripts and categories for Fleet-maintained apps. `/teams` can carry these, but returns an empty `fleet_maintained_apps` in practice, so the apps are inferred from software titles and enriched here. **A `gitops` role token gets 403 here**, in which case categories and scripts are reported as not diffed rather than compared against an unknown value |

Global endpoints (`/config`, `/global/policies`, `/queries` with teamID=0) are only called when `default.yml` defines global sections.
Global endpoints (`/config`, `/certificate_authorities`, `/setup_experience/eula/metadata`, `/global/policies`, `/queries` with teamID=0) are only called when `default.yml` defines global sections.

The "hosts on no team" bucket is fetched only when the repo has a no-team file (`teams/no-team.yml` or `fleets/unassigned.yml`). Its resources live behind `team_id=0` on `/configuration_profiles` and `/scripts`, and behind `/teams/0/policies` for policies — note that `/global/policies` is a *different* set. Fleet does not report configured software for this bucket, so software is not diffed there.

Expand Down
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). 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). 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
81 changes: 81 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,84 @@ func (c *Client) GetConfig(ctx context.Context) (map[string]any, error) {
return result, nil
}

// AddMovedConfig adds settings Fleet serves from their own endpoints rather
// than /config, at the paths default.yml configures them under, so they can
// be diffed like the rest of org_settings:
//
// - certificate_authorities.ndes_scep_proxy: url, admin_url, username (the
// password is write-only). The other CA types are lists whose entries
// carry secrets, so they are left out.
// - mdm.end_user_license_agreement: the uploaded file's name, or "" when
// none is uploaded (Fleet answers 404).
//
// A setting the token cannot read is left out, and the diff reports it as
// not diffed.
func (c *Client) AddMovedConfig(ctx context.Context, cfg map[string]any) error {
var cas struct {
CertificateAuthorities []struct {
ID uint `json:"id"`
Type string `json:"type"`
} `json:"certificate_authorities"`
}
err := c.get(ctx, "/api/v1/fleet/certificate_authorities", nil, &cas)
switch {
case err == nil:
// Read, so a missing NDES proxy diffs as one being added.
cfg["certificate_authorities"] = map[string]any{}
case !unreadable(err):
return fmt.Errorf("fetching certificate authorities: %w", err)
}
for _, ca := range cas.CertificateAuthorities {
if ca.Type != "ndes_scep_proxy" {
continue
}
var ndes struct {
URL string `json:"url"`
AdminURL string `json:"admin_url"`
Username string `json:"username"`
}
err := c.get(ctx, fmt.Sprintf("/api/v1/fleet/certificate_authorities/%d", ca.ID), nil, &ndes)
if err != nil {
if unreadable(err) {
delete(cfg, "certificate_authorities")
break
}
return fmt.Errorf("fetching certificate authority %d: %w", ca.ID, err)
}
cfg["certificate_authorities"] = map[string]any{"ndes_scep_proxy": map[string]any{
"url": ndes.URL, "admin_url": ndes.AdminURL, "username": ndes.Username,
}}
}

var eula struct {
Name string `json:"name"`
}
err = c.get(ctx, "/api/v1/fleet/setup_experience/eula/metadata", nil, &eula)
var httpErr *HTTPError
switch {
case err == nil, errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound:
case unreadable(err):
return nil
default:
return fmt.Errorf("fetching EULA metadata: %w", err)
}
mdm, _ := cfg["mdm"].(map[string]any)
if mdm == nil {
mdm = map[string]any{}
cfg["mdm"] = mdm
}
mdm["end_user_license_agreement"] = eula.Name
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 @@ -1020,6 +1098,9 @@ func (c *Client) FetchAll(ctx context.Context, opts ...FetchOptions) (*FleetStat
if err != nil {
return err
}
if err := c.AddMovedConfig(gctx, cfg); err != nil {
return err
}
globalConfig = cfg
return nil
})
Expand Down
76 changes: 76 additions & 0 deletions internal/api/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -859,6 +860,81 @@ func TestGetConfig(t *testing.T) {
}
}

func TestAddMovedConfig(t *testing.T) {
// Fleet serves CAs and the EULA from their own endpoints, not /config;
// AddMovedConfig puts them where default.yml configures them.
tests := []struct {
name string
caStatus int
eulaStatus int
wantNDES map[string]any // nil: certificate_authorities absent
wantEULA any // nil: key absent
}{
{
name: "both reported",
caStatus: 200, eulaStatus: 200,
wantNDES: map[string]any{"url": "https://ca/scep", "admin_url": "https://ca/admin", "username": "fleet"},
wantEULA: "eula.pdf",
},
{
name: "no EULA uploaded is empty", caStatus: 200, eulaStatus: 404,
wantNDES: map[string]any{"url": "https://ca/scep", "admin_url": "https://ca/admin", "username": "fleet"},
wantEULA: "",
},
{name: "unreadable stays unreported", caStatus: 403, eulaStatus: 403},
{name: "Fleet Free (402) stays unreported", caStatus: 402, eulaStatus: 402},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
status := map[string]int{
"/api/v1/fleet/certificate_authorities": tt.caStatus,
"/api/v1/fleet/certificate_authorities/7": tt.caStatus,
"/api/v1/fleet/setup_experience/eula/metadata": tt.eulaStatus,
}[r.URL.Path]
if status == 0 {
t.Errorf("unexpected path: %s", r.URL.Path)
status = 500
}
if status != 200 {
w.WriteHeader(status)
return
}
switch r.URL.Path {
case "/api/v1/fleet/certificate_authorities":
w.Write([]byte(`{"certificate_authorities":[{"id":3,"name":"S","type":"smallstep"},{"id":7,"name":"NDES","type":"ndes_scep_proxy"}]}`))
case "/api/v1/fleet/certificate_authorities/7":
w.Write([]byte(`{"id":7,"type":"ndes_scep_proxy","name":"NDES","url":"https://ca/scep","admin_url":"https://ca/admin","username":"fleet"}`))
default:
w.Write([]byte(`{"name":"eula.pdf","sha256":"x"}`))
}
}))
defer ts.Close()

cfg := map[string]any{"mdm": map[string]any{"enable_disk_encryption": true}}
if err := testClient(t, ts, "tok").AddMovedConfig(context.Background(), cfg); err != nil {
t.Fatalf("AddMovedConfig: %v", err)
}
cas, _ := cfg["certificate_authorities"].(map[string]any)
if tt.wantNDES == nil {
if cas != nil {
t.Errorf("certificate_authorities: got %v, want absent", cas)
}
} else if got := cas["ndes_scep_proxy"]; !reflect.DeepEqual(got, tt.wantNDES) {
t.Errorf("ndes_scep_proxy: got %v, want %v", got, tt.wantNDES)
}
eula, found := cfg["mdm"].(map[string]any)["end_user_license_agreement"]
if tt.wantEULA == nil {
if found {
t.Errorf("EULA: got %v, want absent", eula)
}
} else if eula != tt.wantEULA {
t.Errorf("EULA: got %v, want %v", eula, tt.wantEULA)
}
})
}
}

func keys(m map[string]any) []string {
var ks []string
for k := range m {
Expand Down
115 changes: 103 additions & 12 deletions internal/diff/differ.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ type DiffResult struct {
LabelChanges ResourceDiff // label definitions (global scope only)
Config []ConfigChange // org_settings, agent_options, controls diffs
Errors []string
SkippedConfigSections []string // configured sections or keys the API does not report (e.g. "agent_options", "controls.windows_migration_enabled")
SkippedConfigSections []string // configured sections or keys the API does not report (e.g. "agent_options", "settings.features.foo")
GlobalOnlyControls []string // global-only controls a fleet file sets, which Fleet ignores there (e.g. "controls.windows_migration_enabled")
}

// ConfigChange represents a change in a top-level config section.
Expand Down Expand Up @@ -423,7 +424,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 = diffTeamConfig(currentTeam.Settings, proposedTeam)
result.Config, result.SkippedConfigSections, result.GlobalOnlyControls = 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 @@ -480,7 +481,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, _ = diffTeamConfig(currentTeam.Settings, baseTeam)
baseDiff.Config, _, _ = diffTeamConfig(currentTeam.Settings, baseTeam)
if !currentTeam.SoftwareUnavailable {
baseDiff.Software, _ = diffSoftware(enrichedSoftware, baseTeam.Software)
}
Expand Down Expand Up @@ -1841,11 +1842,12 @@ func validateLabels(team parser.ParsedTeam, labelMap map[string]api.Label, chang
// global config sections from default.yml. Returns a list of config changes.
// Skips values containing "$" (env var placeholders that Fleet substitutes).
func diffConfig(apiConfig map[string]any, proposed *parser.ParsedGlobal) ([]ConfigChange, []string) {
var changes []ConfigChange
var skipped []string
changes, skipped, orgSettings := diffEULA(apiConfig, proposed.OrgSettings)
ndesAdded, orgSettings := diffNDESAdded(apiConfig, orgSettings)
changes = append(changes, ndesAdded...)

sections := map[string]map[string]any{
"org_settings": proposed.OrgSettings,
"org_settings": orgSettings,
"agent_options": proposed.AgentOptions,
"controls": settingsControls(proposed.Controls),
}
Expand Down Expand Up @@ -1886,6 +1888,71 @@ func diffConfig(apiConfig map[string]any, proposed *parser.ParsedGlobal) ([]Conf
return changes, skipped
}

// diffEULA compares org_settings.mdm.end_user_license_agreement on its own:
// default.yml gives a path, Fleet reports the uploaded file's name, and ""
// there means no EULA is uploaded rather than "not reported". It returns
// orgSettings without the key, for the generic diff of the rest.
func diffEULA(apiConfig, orgSettings map[string]any) ([]ConfigChange, []string, map[string]any) {
const key = "mdm.end_user_license_agreement"
mdm, _ := orgSettings["mdm"].(map[string]any)
p, _ := mdm["end_user_license_agreement"].(string)
if containsEnvVar(p) || len(orgSettings) == 0 {
return nil, nil, orgSettings
}
if p == "" {
// fleetctl gitops deletes the uploaded EULA when none is configured.
apiMDM, _ := apiConfig["mdm"].(map[string]any)
if name, _ := apiMDM["end_user_license_agreement"].(string); name != "" {
return []ConfigChange{{Section: "org_settings", Key: key, Old: name, New: ""}}, nil, orgSettings
}
return nil, nil, orgSettings
}
rest := maps.Clone(mdm)
delete(rest, "end_user_license_agreement")
orgSettings = maps.Clone(orgSettings)
orgSettings["mdm"] = rest

apiMDM, _ := apiConfig["mdm"].(map[string]any)
name, found := apiMDM["end_user_license_agreement"].(string)
if !found {
return nil, []string{"org_settings." + key}, orgSettings
}
want := p[strings.LastIndexAny(p, `/\`)+1:]
if name == want {
return nil, nil, orgSettings
}
return []ConfigChange{{Section: "org_settings", Key: key, Old: name, New: want}}, nil, orgSettings
}

// diffNDESAdded reports a configured NDES SCEP proxy that Fleet does not
// have yet. The CA list was read (certificate_authorities is present) but
// holds no NDES proxy, so every configured leaf is an addition rather than
// "not reported". It returns orgSettings without the proxy in that case.
func diffNDESAdded(apiConfig, orgSettings map[string]any) ([]ConfigChange, map[string]any) {
cas, _ := orgSettings["certificate_authorities"].(map[string]any)
ndes, _ := cas["ndes_scep_proxy"].(map[string]any)
apiCAs, read := apiConfig["certificate_authorities"].(map[string]any)
if ndes == nil || !read || apiCAs["ndes_scep_proxy"] != nil {
return nil, orgSettings
}
var changes []ConfigChange
flattenMap(ndes, "certificate_authorities.ndes_scep_proxy", func(key, val string) {
if val == "" || val == "<nil>" || containsEnvVar(val) {
return
}
if isSecretKey(key) {
val = redact(val)
}
changes = append(changes, ConfigChange{Section: "org_settings", Key: key, New: val})
})
sort.Slice(changes, func(i, j int) bool { return changes[i].Key < changes[j].Key })
rest := maps.Clone(cas)
delete(rest, "ndes_scep_proxy")
orgSettings = maps.Clone(orgSettings)
orgSettings["certificate_authorities"] = rest
return changes, orgSettings
}

// 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 @@ -2083,14 +2150,38 @@ func settingsControls(controls map[string]any) map[string]any {
return rest
}

// globalOnlyControls are controls keys Fleet stores on global config only
// (AppConfig.MDM; a team's mdm object has no such field). A fleet file may
// set them without error, but they have no effect there.
var globalOnlyControls = map[string]bool{
"windows_enabled_and_configured": true,
"windows_migration_enabled": true,
"enable_turn_on_windows_mdm_manually": true,
"windows_entra_tenant_ids": true,
"windows_entra_client_ids": true,
"android_enabled_and_configured": true,
"apple_require_hardware_attestation": true,
"apple_account_provisioning": true,
}

// 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 against the raw team object from GET /teams, the settings
// sub-keys that could not be diffed, and the global-only controls the team
// file sets ("controls.<key>").
func diffTeamConfig(current map[string]any, team parser.ParsedTeam) ([]ConfigChange, []string, []string) {
changes, skipped := diffTeamSettings(current, team.Settings)
if len(settingsControls(team.Controls)) > 0 {
var globalOnly []string
controls := maps.Clone(team.Controls)
for k := range controls {
if globalOnlyControls[k] {
globalOnly = append(globalOnly, "controls."+k)
delete(controls, k)
}
}
sort.Strings(globalOnly)
if len(settingsControls(controls)) > 0 {
if mdm, ok := current["mdm"].(map[string]any); ok {
c, nr := diffControls(mdm, team.Controls, teamControlsAPIKey)
c, nr := diffControls(mdm, controls, teamControlsAPIKey)
changes, skipped = append(changes, c...), append(skipped, nr...)
} else {
skipped = append(skipped, "controls")
Expand All @@ -2105,7 +2196,7 @@ func diffTeamConfig(current map[string]any, team parser.ParsedTeam) ([]ConfigCha
}
}
sort.Strings(skipped)
return changes, skipped
return changes, skipped, globalOnly
}

// containsEnvVar returns true if the string contains a $ (env var placeholder).
Expand Down
Loading
Loading