Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
23 changes: 23 additions & 0 deletions cmd/fleetctl/fleetctl/generate_gitops.go
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,21 @@ func generateFilename(name string) string {
return fileName
}

// uniqueFilename numbers fileName ("a-b-2.xml") when it's already taken:
// distinct names can sanitize alike ("A B" and "a-b"), and since each YAML
// entry carries its own name, a shared file would apply one profile's
// contents under both names.
func uniqueFilename(fileName string, taken map[string]bool) string {
ext := filepath.Ext(fileName)
base := strings.TrimSuffix(fileName, ext)
candidate := fileName
for i := 2; taken[candidate]; i++ {
candidate = fmt.Sprintf("%s-%d%s", base, i, ext)
}
taken[candidate] = true
return candidate
}

func scriptExtensionForPlatform(platform string) string {
if platform == "windows" {
return ".ps1"
Expand Down Expand Up @@ -1623,6 +1638,7 @@ func (cmd *GenerateGitopsCommand) generateProfiles(teamId *uint, teamName string
appleProfilesSlice := make([]map[string]interface{}, 0)
windowsProfilesSlice := make([]map[string]interface{}, 0)
androidProfilesSlice := make([]map[string]interface{}, 0)
usedFilenames := make(map[string]bool, len(profiles))
for _, profile := range profiles {
profileSpec := map[string]interface{}{}
// Parse any labels.
Expand Down Expand Up @@ -1660,6 +1676,7 @@ func (cmd *GenerateGitopsCommand) generateProfiles(teamId *uint, teamName string
if generatedFilename == "" {
continue // Error logged inside generateProfileFilename
}
generatedFilename = uniqueFilename(generatedFilename, usedFilenames)

fileName := fmt.Sprintf("profiles/%s", generatedFilename)
if teamId == nil {
Expand All @@ -1677,6 +1694,12 @@ func (cmd *GenerateGitopsCommand) generateProfiles(teamId *uint, teamName string
}

profileSpec["path"] = path
// Always emitted: the file name is a sanitized copy of the name, so
// omitting it would rename profiles whose name the file can't carry.
profileSpec["name"] = profile.Name
Comment thread
qodo-free-for-open-source-projects[bot] marked this conversation as resolved.
Resolved
if profile.Description != "" {
profileSpec["description"] = profile.Description
}

// Only declarations can carry one, and the list endpoint doesn't return
// activations, so it takes a second call.
Expand Down
48 changes: 48 additions & 0 deletions cmd/fleetctl/fleetctl/generate_gitops_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ type MockClient struct {
WithoutVPP bool
WithAssets bool
WithActivations bool
// adds two Windows profiles whose names sanitize to the same file name
WithCollidingProfileNames bool
}

func (c MockClient) GetProfileActivation(profileID string) ([]byte, error) {
Expand Down Expand Up @@ -163,6 +165,7 @@ func (c MockClient) ListConfigurationProfiles(teamID *uint) ([]*fleet.MDMConfigP
{
ProfileUUID: "global-windows-profile-uuid",
Name: "Global Windows Profile",
Description: "Blocks inbound connections",
Platform: "windows",
LabelsIncludeAny: []fleet.ConfigurationProfileLabel{{
LabelName: "Label D",
Expand Down Expand Up @@ -192,6 +195,12 @@ func (c MockClient) ListConfigurationProfiles(teamID *uint) ([]*fleet.MDMConfigP
Identifier: "com.example.team-declaration",
})
}
if c.WithCollidingProfileNames {
profiles = append(profiles,
&fleet.MDMConfigProfilePayload{ProfileUUID: "team-win-uuid", Name: "Team Win", Platform: "windows"},
&fleet.MDMConfigProfilePayload{ProfileUUID: "team-dash-win-uuid", Name: "Team-Win", Platform: "windows"},
)
}
return profiles, nil
}
if *teamID == 0 || *teamID == 2 || *teamID == 3 || *teamID == 4 || *teamID == 5 || *teamID == 6 {
Expand Down Expand Up @@ -250,6 +259,10 @@ func (MockClient) GetProfileContents(profileID string) ([]byte, error) {
return []byte("<xml>test mobileconfig profile</xml>"), nil
case "team-declaration-profile-uuid":
return []byte(`{"Type":"com.apple.configuration.passcode.settings","Identifier":"com.example.team-declaration","Payload":{}}`), nil
case "team-win-uuid":
return []byte("<xml>team win</xml>"), nil
case "team-dash-win-uuid":
return []byte("<xml>team-win</xml>"), nil
}
return nil, errors.New("profile not found")
}
Expand Down Expand Up @@ -3601,3 +3614,38 @@ func TestGeneratePoliciesPatchPolicyOrphanedFromFleetMaintainedApp(t *testing.T)
require.Error(t, err)
require.ErrorContains(t, err, "Team patch policy")
}

func TestGenerateProfilesFilenameCollision(t *testing.T) {
// "Team Win" and "Team-Win" sanitize to the same file name, so each needs
// its own file or one profile's contents would apply under both names
fleetClient := &MockClient{WithCollidingProfileNames: true}
appConfig, err := fleetClient.GetAppConfig()
require.NoError(t, err)
cmd := &GenerateGitopsCommand{
Client: fleetClient,
CLI: cli.NewContext(cli.NewApp(), nil, nil),
Messages: Messages{},
FilesToWrite: make(map[string]any),
AppConfig: appConfig,
ScriptList: make(map[uint]string),
}

got, err := cmd.generateProfiles(new(uint(1)), "team-a")
require.NoError(t, err)
windows, ok := got["windows_profiles"].([]map[string]any)
require.True(t, ok)
require.Len(t, windows, 2)
require.Equal(t, "../lib/team-a/profiles/team-win.xml", windows[0]["path"])
require.Equal(t, "../lib/team-a/profiles/team-win-2.xml", windows[1]["path"])

contentsByName := make(map[string]any, len(windows))
for _, p := range windows {
path, _ := p["path"].(string)
name, _ := p["name"].(string)
contentsByName[name] = cmd.FilesToWrite[strings.TrimPrefix(path, "../")]
}
require.Equal(t, map[string]any{
"Team Win": "<xml>team win</xml>",
"Team-Win": "<xml>team-win</xml>",
}, contentsByName)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,27 @@ apple_settings:
- labels_include_all:
- Label A
- Label B
name: Global MacOS MobileConfig Profile
path: ./lib/profiles/global-macos-mobileconfig-profile.mobileconfig
- labels_exclude_any:
- Label C
name: Global MacOS JSON Profile
path: ./lib/profiles/global-macos-json-profile.json
enable_disk_encryption: false
enable_escrow_disk_encryption_key: true
windows_settings:
configuration_profiles:
- labels_include_any:
- description: Blocks inbound connections
labels_include_any:
- Label D
name: Global Windows Profile
path: ./lib/profiles/global-windows-profile.xml
enable_disk_encryption: true
require_bitlocker_pin: false
android_settings:
configuration_profiles:
- path: ./lib/profiles/global-android-profile.json
- name: Global Android Profile
path: ./lib/profiles/global-android-profile.json
macos_updates:
minimum_version: "15.1"
deadline: "2024-12-31"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ android_settings:
subject_name: CN=OU=$FLEET_VAR_HOST_UUID/ST=$FLEET_VAR_HOST_HARDWARE_SERIAL
apple_settings:
configuration_profiles:
- path: ../lib/some_team/profiles/team-macos-mobileconfig-profile.mobileconfig
- name: Team MacOS MobileConfig Profile
path: ../lib/some_team/profiles/team-macos-mobileconfig-profile.mobileconfig
enable_disk_encryption: true
enable_escrow_disk_encryption_key: true
enable_recovery_lock_password: false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,25 @@ agent_options:
controls:
android_settings:
configuration_profiles:
- path: ./lib/profiles/global-android-profile.json
- name: Global Android Profile
path: ./lib/profiles/global-android-profile.json
apple_settings:
configuration_profiles:
- labels_include_all:
- Label A
- Label B
name: Global MacOS MobileConfig Profile
path: ./lib/profiles/global-macos-mobileconfig-profile.mobileconfig
- labels_exclude_any:
- Label C
name: Global MacOS JSON Profile
path: ./lib/profiles/global-macos-json-profile.json
windows_settings:
configuration_profiles:
- labels_include_any:
- description: Blocks inbound connections
labels_include_any:
- Label D
name: Global Windows Profile
path: ./lib/profiles/global-windows-profile.xml
custom_host_vitals:
- name: Asset tag
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ controls:
subject_name: CN=OU=$FLEET_VAR_HOST_UUID/ST=$FLEET_VAR_HOST_HARDWARE_SERIAL
apple_settings:
configuration_profiles:
- path: "../lib/team-a-👍/profiles/team-macos-mobileconfig-profile.mobileconfig"
- name: Team MacOS MobileConfig Profile
path: "../lib/team-a-👍/profiles/team-macos-mobileconfig-profile.mobileconfig"
enable_disk_encryption: true
enable_escrow_disk_encryption_key: true
enable_recovery_lock_password: false
Expand Down
60 changes: 51 additions & 9 deletions pkg/spec/gitops.go
Original file line number Diff line number Diff line change
Expand Up @@ -1406,10 +1406,12 @@ func parseControls(top map[string]json.RawMessage, result *GitOps, logFn Logf, y

// Expand globs in profile paths.
var errs []error
macOSSettings.CustomSettings, errs = expandBaseItems(macOSSettings.CustomSettings, controlsDir, "profile", GlobExpandOptions{
macGlobOpts := GlobExpandOptions{
AllowedExtensions: map[string]bool{".mobileconfig": true, ".json": true},
LogFn: logFn,
})
}
multiError = multierror.Append(multiError, validateProfileSpecNames(macOSSettings.CustomSettings, controlsDir, "apple_settings", macGlobOpts)...)
macOSSettings.CustomSettings, errs = expandBaseItems(macOSSettings.CustomSettings, controlsDir, "profile", macGlobOpts)
multiError = multierror.Append(multiError, errs...)
// Then resolve the paths to absolute and find Fleet secrets in the profile files.
for i := range macOSSettings.CustomSettings {
Expand Down Expand Up @@ -1450,11 +1452,12 @@ func parseControls(top map[string]json.RawMessage, result *GitOps, logFn Logf, y

if windowsSettings.CustomSettings.Valid {
var errs []error
windowsSettings.CustomSettings.Value, errs = expandBaseItems(windowsSettings.CustomSettings.Value, controlsDir, "profile", GlobExpandOptions{
winGlobOpts := GlobExpandOptions{
AllowedExtensions: map[string]bool{".xml": true},

LogFn: logFn,
})
LogFn: logFn,
}
multiError = multierror.Append(multiError, validateProfileSpecNames(windowsSettings.CustomSettings.Value, controlsDir, "windows_settings", winGlobOpts)...)
windowsSettings.CustomSettings.Value, errs = expandBaseItems(windowsSettings.CustomSettings.Value, controlsDir, "profile", winGlobOpts)
multiError = multierror.Append(multiError, errs...)

for i := range windowsSettings.CustomSettings.Value {
Expand Down Expand Up @@ -1484,10 +1487,12 @@ func parseControls(top map[string]json.RawMessage, result *GitOps, logFn Logf, y

if androidSettings.CustomSettings.Valid {
var errs []error
androidSettings.CustomSettings.Value, errs = expandBaseItems(androidSettings.CustomSettings.Value, controlsDir, "profile", GlobExpandOptions{
androidGlobOpts := GlobExpandOptions{
AllowedExtensions: map[string]bool{".json": true},
LogFn: logFn,
})
}
multiError = multierror.Append(multiError, validateProfileSpecNames(androidSettings.CustomSettings.Value, controlsDir, "android_settings", androidGlobOpts)...)
androidSettings.CustomSettings.Value, errs = expandBaseItems(androidSettings.CustomSettings.Value, controlsDir, "profile", androidGlobOpts)
multiError = multierror.Append(multiError, errs...)
for i := range androidSettings.CustomSettings.Value {
err := resolveAndUpdateProfilePath(&androidSettings.CustomSettings.Value[i], result)
Expand Down Expand Up @@ -1681,6 +1686,31 @@ func resolveAndUpdateActivationPath(profile *fleet.MDMProfileSpec, baseDir strin
return LookupEnvSecrets(string(fileBytes), result.FleetSecrets)
}

// validateProfileSpecNames rejects a "name" on a "paths" glob that matches
// more than one file: the glob expands to one profile per file and names are
// unique per fleet, so a single name can't cover them. A description can, like
// labels. Runs before expansion, which is the last point the pattern is known.
func validateProfileSpecNames(specs []fleet.MDMProfileSpec, baseDir, settingsKey string, opts GlobExpandOptions) []error {
// the expansion that follows logs the same skipped files
opts.LogFn = func(string, ...any) {}
var errs []error
for _, spec := range specs {
if strings.TrimSpace(spec.Name) == "" || spec.Paths == "" || !containsGlobMeta(spec.Paths) {
continue
}
matches, err := expandGlobPattern(spec.Paths, baseDir, "profile", opts)
if err != nil {
// reported again, with context, by the expansion that follows
continue
}
if len(matches) > 1 {
errs = append(errs, fmt.Errorf(`controls.%s.configuration_profiles[]: "name" can't be used with a "paths" glob that matches more than one file (%q matched %d); use "path" for a single profile`,
settingsKey, spec.Paths, len(matches)))
}
}
return errs
}

func resolveAndUpdateProfilePath(profile *fleet.MDMProfileSpec, result *GitOps) error {
// Path has already been resolved by expandBaseItems; just ensure it's absolute.
var err error
Expand Down Expand Up @@ -2057,6 +2087,13 @@ func parsePolicies(top map[string]json.RawMessage, result *GitOps, baseDir strin
continue
}

// an explicit name replaces the PayloadDisplayName, as on apply,
// where it is stored trimmed
if n := strings.TrimSpace(item.Name); n != "" {
definedProfileNames[n] = struct{}{}
continue
}

// parse the file into XML .mobileconfig struct and lookup `PayloadDisplayName`
mc := mobileconfig.Mobileconfig(expanded)
parsed, err := mc.ParseConfigProfile()
Expand Down Expand Up @@ -2085,7 +2122,12 @@ func parsePolicies(top map[string]json.RawMessage, result *GitOps, baseDir strin
continue
}

// windows profile names come from the file name without the extension
// windows profile names come from the file name without the
// extension, unless the YAML names the profile
if n := strings.TrimSpace(item.Name); n != "" {
definedProfileNames[n] = struct{}{}
continue
}
base := filepath.Base(item.Path)
definedProfileNames[strings.TrimSuffix(base, filepath.Ext(base))] = struct{}{}
}
Expand Down
Loading
Loading