Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
b0579b4
Add macos settings custom settings to appconfig and team config
mna Feb 8, 2023
ec2775c
Adjust tests
mna Feb 8, 2023
6162a7f
Add skeleton of tests for extracting the custom settings
mna Feb 8, 2023
90e538f
Add tests and fix implementation of extraction of custom settings
mna Feb 13, 2023
66458e6
Ensure the team macossettings behave properly with absent vs empty, v…
mna Feb 13, 2023
740c904
Fix panic in team spec payload validation, adjust tests
mna Feb 13, 2023
d1d5354
Start implementation of batch-set mdm profiles
mna Feb 13, 2023
c387131
Implement endpoint and validate profiles
mna Feb 13, 2023
4bf0362
Document new batch endpoint, start work on datastore method
mna Feb 14, 2023
9e21cf2
Fix pointer to team id
mna Feb 14, 2023
264a4a6
Add tests for service layer
mna Feb 14, 2023
a172fb9
Add datastore layer tests
mna Feb 14, 2023
8eb01e4
Add integration tests for batch-set profiles
mna Feb 14, 2023
08aa354
Add call to batch-apply profiles from fleetctl apply, validate that m…
mna Feb 14, 2023
500fcfe
Add test for endpoint called without mdm enabled
mna Feb 14, 2023
fe0f7f5
Add changes file
mna Feb 14, 2023
9194018
Fix error message on duplicate name/identifier
mna Feb 14, 2023
6d20099
Fix message in test
mna Feb 14, 2023
91009e1
Add the dry_run parameter to the documentation
mna Feb 14, 2023
20e9e94
Fix formatting
mna Feb 14, 2023
e97f292
Add fleet MDM enabled check when macos custom settings are provided, …
mna Feb 15, 2023
bc7bfad
Make the batch profiles endpoint return 204 no content
mna Feb 15, 2023
c46a256
Fix handling of success codes in fleetctl client
mna Feb 15, 2023
0356870
Extract loading team by name to an enterprise extension function
mna Feb 15, 2023
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
1 change: 1 addition & 0 deletions changes/issue-9587-add-fleetctl-apply-macos-profiles
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Added support for providing `macos_settings.custom_settings` profiles for team (with Fleet Premium) and no-team levels via `fleetctl apply`.
4 changes: 3 additions & 1 deletion cmd/fleetctl/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"path/filepath"

"github.com/fleetdm/fleet/v4/pkg/spec"
"github.com/fleetdm/fleet/v4/server/fleet"
Expand Down Expand Up @@ -68,7 +69,8 @@ func applyCommand() *cli.Command {
Force: flForce,
DryRun: flDryRun,
}
err = fleetClient.ApplyGroup(c.Context, specs, logf, opts)
baseDir := filepath.Dir(flFilename)
err = fleetClient.ApplyGroup(c.Context, specs, baseDir, logf, opts)
if err != nil {
return err
}
Expand Down
27 changes: 24 additions & 3 deletions cmd/fleetctl/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/ghodss/yaml"

"github.com/fleetdm/fleet/v4/pkg/spec"
"github.com/fleetdm/fleet/v4/server/config"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/fleetdm/fleet/v4/server/ptr"
"github.com/fleetdm/fleet/v4/server/service"
Expand Down Expand Up @@ -182,6 +183,8 @@ spec:
macos_updates:
minimum_version: ""
deadline: ""
macos_settings:
custom_settings:
name: team1
---
apiVersion: v1
Expand All @@ -204,10 +207,12 @@ spec:
macos_updates:
minimum_version: "12.3.1"
deadline: "2021-12-14"
macos_settings:
custom_settings:
name: team2
`
expectedJson := `{"kind":"team","apiVersion":"v1","spec":{"team":{"id":42,"created_at":"1999-03-10T02:45:06.371Z","name":"team1","description":"team1 description","webhook_settings":{"failing_policies_webhook":{"enable_failing_policies_webhook":false,"destination_url":"","policy_ids":null,"host_batch_size":0}},"integrations":{"jira":null,"zendesk":null},"features":{"enable_host_users":true,"enable_software_inventory":true},"mdm":{"macos_updates":{"minimum_version":"","deadline":""}},"user_count":99,"host_count":42}}}
{"kind":"team","apiVersion":"v1","spec":{"team":{"id":43,"created_at":"1999-03-10T02:45:06.371Z","name":"team2","description":"team2 description","agent_options":{"config":{"foo":"bar"},"overrides":{"platforms":{"darwin":{"foo":"override"}}}},"webhook_settings":{"failing_policies_webhook":{"enable_failing_policies_webhook":false,"destination_url":"","policy_ids":null,"host_batch_size":0}},"integrations":{"jira":null,"zendesk":null},"features":{"enable_host_users":false,"enable_software_inventory":false,"additional_queries":{"foo":"bar"}},"mdm":{"macos_updates":{"minimum_version":"12.3.1","deadline":"2021-12-14"}},"user_count":87,"host_count":43}}}
expectedJson := `{"kind":"team","apiVersion":"v1","spec":{"team":{"id":42,"created_at":"1999-03-10T02:45:06.371Z","name":"team1","description":"team1 description","webhook_settings":{"failing_policies_webhook":{"enable_failing_policies_webhook":false,"destination_url":"","policy_ids":null,"host_batch_size":0}},"integrations":{"jira":null,"zendesk":null},"features":{"enable_host_users":true,"enable_software_inventory":true},"mdm":{"macos_updates":{"minimum_version":"","deadline":""}},"macos_settings":{"custom_settings":null},"user_count":99,"host_count":42}}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rant: curious if this test (and others in this file) is as annoying to you as it is to me to modify. Obviously not for now! but I have seen we use golden files for other tests, I wonder if we're at the same point here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah eventually we should make them all golden files, nicer to maintain!

{"kind":"team","apiVersion":"v1","spec":{"team":{"id":43,"created_at":"1999-03-10T02:45:06.371Z","name":"team2","description":"team2 description","agent_options":{"config":{"foo":"bar"},"overrides":{"platforms":{"darwin":{"foo":"override"}}}},"webhook_settings":{"failing_policies_webhook":{"enable_failing_policies_webhook":false,"destination_url":"","policy_ids":null,"host_batch_size":0}},"integrations":{"jira":null,"zendesk":null},"features":{"enable_host_users":false,"enable_software_inventory":false,"additional_queries":{"foo":"bar"}},"mdm":{"macos_updates":{"minimum_version":"12.3.1","deadline":"2021-12-14"}},"macos_settings":{"custom_settings":null},"user_count":87,"host_count":43}}}
`

if tt.shouldHaveExpiredBanner {
Expand Down Expand Up @@ -476,6 +481,8 @@ spec:
macos_updates:
minimum_version: ""
deadline: ""
macos_settings:
custom_settings:
org_info:
org_logo_url: ""
org_name: ""
Expand Down Expand Up @@ -562,6 +569,9 @@ spec:
"enable_host_users": true,
"enable_software_inventory": false
},
"macos_settings": {
"custom_settings": null
},
"mdm": {
"macos_updates": {
"minimum_version": "",
Expand Down Expand Up @@ -636,6 +646,8 @@ spec:
integrations:
jira: null
zendesk: null
macos_settings:
custom_settings:
mdm:
apple_bm_default_team: ""
apple_bm_terms_expired: false
Expand Down Expand Up @@ -775,6 +787,9 @@ spec:
"enable_host_users": true,
"enable_software_inventory": false
},
"macos_settings": {
"custom_settings": null
},
"mdm": {
"macos_updates": {
"minimum_version": "",
Expand Down Expand Up @@ -1651,8 +1666,11 @@ func TestGetCarveWithError(t *testing.T) {
// TestGetTeamsYAMLAndApply checks that the output of `get teams --yaml` can be applied
// via the `apply` command.
func TestGetTeamsYAMLAndApply(t *testing.T) {
cfg := config.TestConfig()
cfg.MDMApple.Enable = true
_, ds := runServerWithMockedDS(t, &service.TestServerOpts{
License: &fleet.LicenseInfo{Tier: fleet.TierPremium, Expiration: time.Now().Add(24 * time.Hour)},
License: &fleet.LicenseInfo{Tier: fleet.TierPremium, Expiration: time.Now().Add(24 * time.Hour)},
FleetConfig: &cfg,
})

created_at, err := time.Parse(time.RFC3339, "1999-03-10T02:45:06.371Z")
Expand Down Expand Up @@ -1730,6 +1748,9 @@ func TestGetTeamsYAMLAndApply(t *testing.T) {
}
return nil, fmt.Errorf("team not found: %s", name)
}
ds.BatchSetMDMAppleProfilesFunc = func(ctx context.Context, teamID *uint, profiles []*fleet.MDMAppleConfigProfile) error {
return nil
}

actualYaml := runAppForTest(t, []string{"get", "teams", "--yaml"})
yamlFilePath := writeTmpYml(t, actualYaml)
Expand Down
4 changes: 3 additions & 1 deletion cmd/fleetctl/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,9 @@ Use the stop and reset subcommands to manage the server and dependencies once st
logf := func(format string, a ...interface{}) {
fmt.Fprintf(c.App.Writer, format, a...)
}
err = client.ApplyGroup(c.Context, specs, logf, fleet.ApplySpecOptions{})
// this only applies standard queries, the base directory is not used,
// so pass in the current working directory.
err = client.ApplyGroup(c.Context, specs, ".", logf, fleet.ApplySpecOptions{})
if err != nil {
return err
}
Expand Down
24 changes: 24 additions & 0 deletions docs/Contributing/API-for-contributors.md
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,7 @@ The MDM endpoints exist to support the related command-line interface sub-comman
- [Unenroll host from Fleet MDM](#unenroll-host-from-fleet-mdm)
- [Generate Apple DEP Key Pair](#generate-apple-dep-key-pair)
- [Request Certificate Signing Request (CSR)](#request-certificate-signing-request-csr)
- [Batch-apply Apple MDM custom settings](#batch-apply-apple-mdm-custom-settings)


### Get Apple MDM
Expand Down Expand Up @@ -652,6 +653,29 @@ Note that the `public_key` and `private_key` are base64 encoded and should be de

Note that the response fields are base64 encoded and should be decoded before writing them to files. Once base64-decoded, they are PEM-encoded certificate and keys.

### Batch-apply Apple MDM custom settings

`POST /api/v1/fleet/mdm/apple/profiles/batch`

#### Parameters

| Name | Type | In | Description |
| ------------- | ------ | ---- | -------------------------------------------------------------------------------------- |
| team_id | number | query | _Available in Fleet Premium_ The team ID to apply the custom settings to. Only one of team_name/team_id can be provided. |
| team_name | string | query | _Available in Fleet Premium_ The name of the team to apply the custom settings to. Only one of team_name/team_id can be provided. |
| dry_run | bool | query | Validate the provided profiles and return any validation errors, but do not apply the changes. |
| profiles | json | body | An array of strings, the base64-encoded .mobileconfig files to apply. |

If no team (id or name) is provided, the profiles are applied for all hosts (for _Fleet Free_) or for hosts that are not part of a team (for _Fleet Premium_). After the call, the provided list of `profiles` will be the active profiles for that team (or no team) - that is, any existing profile that is not part of that list will be removed, and an existing profile with the same payload identifier as a new profile will be edited. If the list of provided `profiles` is empty, all profiles are removed for that team (or no team).

#### Example

`POST /api/v1/fleet/mdm/apple/profiles/batch`

##### Default response

`204`

## Get or apply configuration files

These API routes are used by the `fleetctl` CLI tool. Users can manage Fleet with `fleetctl` and [configuration files in YAML syntax](https://fleetdm.com/docs/using-fleet/configuration-files/).
Expand Down
1 change: 1 addition & 0 deletions ee/server/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func NewService(
// embedding.
svc.SetEnterpriseOverrides(fleet.EnterpriseOverrides{
HostFeatures: eeservice.HostFeatures,
TeamByName: eeservice.teamByName,
})

return eeservice, nil
Expand Down
68 changes: 57 additions & 11 deletions ee/server/service/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"

Expand Down Expand Up @@ -414,6 +415,25 @@ func (svc *Service) ModifyTeamEnrollSecrets(ctx context.Context, teamID uint, se
return newSecrets, nil
}

func (svc *Service) teamByName(ctx context.Context, name string) (*fleet.Team, error) {
if err := svc.authz.Authorize(ctx, &fleet.Team{}, fleet.ActionRead); err != nil {
return nil, err
}
tm, err := svc.ds.TeamByName(ctx, name)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// this should really be handled in TeamByName so that it returns a
// notFound error as is usually the case for this scenario, but
// changing it causes a number of test failures that indicates this
// might be tricky and even maybe a breaking change in some places. For
// now, handling it here.
return nil, notFoundError{}
}
return nil, err
}
return tm, nil
}

var jsonNull = json.RawMessage(`null`)

func (svc *Service) ApplyTeamSpecs(ctx context.Context, specs []*fleet.TeamSpec, applyOpts fleet.ApplySpecOptions) error {
Expand Down Expand Up @@ -489,12 +509,8 @@ func (svc *Service) ApplyTeamSpecs(ctx context.Context, specs []*fleet.TeamSpec,
return ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("macos_updates", err.Error()))
}

if applyOpts.DryRun {
continue
}

if create {
team, err := svc.createTeamFromSpec(ctx, spec, appConfig, secrets)
team, err := svc.createTeamFromSpec(ctx, spec, appConfig, secrets, applyOpts.DryRun)
if err != nil {
return ctxerr.Wrap(ctx, err, "creating team from spec")
}
Expand All @@ -505,7 +521,7 @@ func (svc *Service) ApplyTeamSpecs(ctx context.Context, specs []*fleet.TeamSpec,
continue
}

if err := svc.editTeamFromSpec(ctx, team, spec, secrets); err != nil {
if err := svc.editTeamFromSpec(ctx, team, spec, secrets, applyOpts.DryRun); err != nil {
return ctxerr.Wrap(ctx, err, "editing team from spec")
}

Expand All @@ -515,6 +531,10 @@ func (svc *Service) ApplyTeamSpecs(ctx context.Context, specs []*fleet.TeamSpec,
})
}

if applyOpts.DryRun {
return nil
}

if len(details) > 0 {
// TODO(mna): we don't create separate activities for e.g. edited agent
// options when applying team specs, so I didn't create explicit activities
Expand All @@ -532,7 +552,7 @@ func (svc *Service) ApplyTeamSpecs(ctx context.Context, specs []*fleet.TeamSpec,
return nil
}

func (svc Service) createTeamFromSpec(ctx context.Context, spec *fleet.TeamSpec, defaults *fleet.AppConfig, secrets []*fleet.EnrollSecret) (*fleet.Team, error) {
func (svc Service) createTeamFromSpec(ctx context.Context, spec *fleet.TeamSpec, defaults *fleet.AppConfig, secrets []*fleet.EnrollSecret, dryRun bool) (*fleet.Team, error) {
agentOptions := &spec.AgentOptions
if len(spec.AgentOptions) == 0 {
agentOptions = defaults.AgentOptions
Expand All @@ -549,18 +569,32 @@ func (svc Service) createTeamFromSpec(ctx context.Context, spec *fleet.TeamSpec,
}
}

var macOSSettings fleet.MacOSSettings
if macOSSettings.CustomSettingsFromMap(spec.MacOSSettings) && len(macOSSettings.CustomSettings) > 0 {
if !svc.config.MDMApple.Enable {
// TODO(mna): eventually we should detect the minimum config required for
// this to be allowed, probably just SCEP/APNs?
return nil, ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("macos_settings.custom_settings", "cannot set custom settings: Fleet MDM is not enabled"))
}
}

if dryRun {
return &fleet.Team{Name: spec.Name}, nil
}

return svc.ds.NewTeam(ctx, &fleet.Team{
Name: spec.Name,
Config: fleet.TeamConfig{
AgentOptions: agentOptions,
Features: features,
MDM: spec.MDM,
AgentOptions: agentOptions,
Features: features,
MDM: spec.MDM,
MacOSSettings: macOSSettings,
},
Secrets: secrets,
})
}

func (svc Service) editTeamFromSpec(ctx context.Context, team *fleet.Team, spec *fleet.TeamSpec, secrets []*fleet.EnrollSecret) error {
func (svc Service) editTeamFromSpec(ctx context.Context, team *fleet.Team, spec *fleet.TeamSpec, secrets []*fleet.EnrollSecret, dryRun bool) error {
team.Name = spec.Name

// if agent options are not provided, do not change them
Expand All @@ -581,11 +615,23 @@ func (svc Service) editTeamFromSpec(ctx context.Context, team *fleet.Team, spec
}
team.Config.Features = features
team.Config.MDM = spec.MDM
if team.Config.MacOSSettings.CustomSettingsFromMap(spec.MacOSSettings) &&
len(team.Config.MacOSSettings.CustomSettings) > 0 {
if !svc.config.MDMApple.Enable {
// TODO(mna): eventually we should detect the minimum config required for
// this to be allowed, probably just SCEP/APNs?
return ctxerr.Wrap(ctx, fleet.NewInvalidArgumentError("macos_settings.custom_settings", "cannot set custom settings: Fleet MDM is not enabled"))
}
}

if len(secrets) > 0 {
team.Secrets = secrets
}

if dryRun {
return nil
}

if _, err := svc.ds.SaveTeam(ctx, team); err != nil {
return err
}
Expand Down
Loading