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
1 change: 1 addition & 0 deletions changes/55539-gitops-fma-name-title-deletion
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Fixed GitOps listing a Fleet-maintained app or package as deleted on every run when it was attached to an existing software title by name, such as a macOS title without a bundle identifier.
20 changes: 20 additions & 0 deletions ee/server/service/software_installers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4085,19 +4085,39 @@ func (svc *Service) softwareBatchUpload(
// delete): the installers on the team whose title matches no incoming
// payload, mirroring the title-based deletion in ds.BatchSetSoftwareInstallers.
incoming := make([]fleet.SoftwareTitleIdentifier, 0, len(installers))
var uploads []*fleet.UploadSoftwareInstallerPayload
for _, payloadWithExtras := range installers {
for _, p := range append([]*fleet.UploadSoftwareInstallerPayload{payloadWithExtras.UploadSoftwareInstallerPayload}, payloadWithExtras.ExtraInstallers...) {
incoming = append(incoming, fleet.SoftwareTitleIdentifier{
UniqueIdentifier: p.UniqueIdentifier(),
Source: p.Source,
})
uploads = append(uploads, p)
}
}
deletedPackages, err := svc.ds.GetSoftwareInstallersPendingDeletion(ctx, teamID, incoming)
if err != nil {
batchErr = fmt.Errorf("computing software packages pending deletion: %w", err)
return
}
if len(deletedPackages) > 0 {
// The apply resolves a payload by bundle id or upgrade code, else by name, so it can keep a
// title whose unique identifier differs from the payload's, which the match above does not see.
var keptTitleIDs []uint
for _, p := range uploads {
titleID, err := svc.ds.GetExistingSoftwareInstallerTitleID(ctxdb.RequirePrimary(ctx, true), p)
switch {
case err == nil:
keptTitleIDs = append(keptTitleIDs, titleID)
case !fleet.IsNotFound(err):
batchErr = fmt.Errorf("resolving software title for %q: %w", p.Filename, err)
return
}
}
deletedPackages = slices.DeleteFunc(deletedPackages, func(d fleet.DeletedSoftwarePackage) bool {
return slices.Contains(keptTitleIDs, d.TitleID)
})
}
if len(deletedPackages) > 0 {
deletedJSON, err := json.Marshal(deletedPackages)
if err != nil {
Expand Down
71 changes: 71 additions & 0 deletions ee/server/service/software_installers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/fleetdm/fleet/v4/server/authz"
"github.com/fleetdm/fleet/v4/server/config"
authz_ctx "github.com/fleetdm/fleet/v4/server/contexts/authz"
"github.com/fleetdm/fleet/v4/server/contexts/ctxdb"
"github.com/fleetdm/fleet/v4/server/contexts/license"
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
"github.com/fleetdm/fleet/v4/server/datastore/s3"
Expand Down Expand Up @@ -3941,6 +3942,76 @@ func TestSoftwareBatchUploadMSIReuseUninstallScript(t *testing.T) {
}
}

func TestSoftwareBatchUploadKeepsTitleAttachedByName(t *testing.T) {
run := func(t *testing.T, dryRun bool, resolveErr error) (status string, deleted *string) {
ds := new(mock.Store)
ds.TeamLiteFunc = func(ctx context.Context, tmID uint) (*fleet.TeamLite, error) {
return &fleet.TeamLite{ID: tmID}, nil
}
ds.GetTeamsWithInstallerByHashFunc = func(ctx context.Context, sha256, url string) (map[uint][]*fleet.ExistingSoftwareInstaller, error) {
title, bundle := "ForkLift", "com.example.forklift"
if sha256 == "new-hash" {
title, bundle = "New App", "com.example.new"
}
return map[uint][]*fleet.ExistingSoftwareInstaller{1: {{
Title: title, Extension: "pkg", Filename: title + ".pkg", Platform: "darwin", Source: "apps",
BundleIdentifier: &bundle, PackageIDs: []string{bundle},
}}}, nil
}
ds.GetExistingSoftwareInstallerTitleIDFunc = func(ctx context.Context, payload *fleet.UploadSoftwareInstallerPayload) (uint, error) {
require.True(t, ctxdb.IsPrimaryRequired(ctx))
switch {
case payload.Title == "New App":
return 0, &notFoundError{}
case resolveErr != nil:
return 0, resolveErr
case payload.Title == "ForkLift" && payload.BundleIdentifier == "com.example.forklift":
return 20, nil
}
return 99, nil
}
// Title 20 came from inventory (lowercase name); title 5 is another title displayed as "ForkLift".
ds.GetSoftwareInstallersPendingDeletionFunc = func(ctx context.Context, tmID *uint, incoming []fleet.SoftwareTitleIdentifier) ([]fleet.DeletedSoftwarePackage, error) {
return []fleet.DeletedSoftwarePackage{{TitleID: 20, DisplayName: "forklift"}, {TitleID: 5, DisplayName: "ForkLift"}}, nil
}
ds.BatchSetSoftwareInstallersFunc = func(context.Context, *uint, []*fleet.UploadSoftwareInstallerPayload) ([]uint, error) { return nil, nil }
ds.BatchSetInHouseAppsInstallersFunc = func(context.Context, *uint, []*fleet.UploadSoftwareInstallerPayload) error { return nil }
ds.ReconcileWindowsMaintainedAppSoftwareTitlesFunc = func(context.Context) error { return nil }

svc := newTestService(t, ds)
svc.keyValueStore, _ = inMemoryKeyValueStore()
svc.softwareInstallStore = &mocksoftware.SoftwareInstallerStore{
ExistsFunc: func(ctx context.Context, id string) (bool, error) { return true, nil },
}
svc.softwareBatchUpload("req-uuid", new(uint(1)), 1, []*fleet.SoftwareInstallerPayload{{SHA256: "new-hash"}, {SHA256: "forklift-hash"}}, dryRun)

got, err := svc.keyValueStore.Get(t.Context(), batchSoftwarePrefix+"req-uuid")
require.NoError(t, err)
require.NotNil(t, got)
deleted, err = svc.keyValueStore.Get(t.Context(), batchSoftwarePrefix+"req-uuid"+batchSoftwareDeletedSuffix)
require.NoError(t, err)
return *got, deleted
}

for _, dryRun := range []bool{true, false} {
t.Run(fmt.Sprintf("dry run %t reports only the title no payload resolves to", dryRun), func(t *testing.T) {
status, deleted := run(t, dryRun, nil)
require.Equal(t, batchSetCompleted, status)
require.NotNil(t, deleted)
var got []fleet.DeletedSoftwarePackage
require.NoError(t, json.Unmarshal([]byte(*deleted), &got))
require.Equal(t, []fleet.DeletedSoftwarePackage{{TitleID: 5, DisplayName: "ForkLift"}}, got)
})
}

t.Run("a resolver error fails the batch", func(t *testing.T) {
status, deleted := run(t, true, errors.New("boom"))
require.Contains(t, status, batchSetFailedPrefix)
require.Contains(t, status, "boom")
require.Nil(t, deleted)
})
}

func TestSoftwareBatchUploadWindowsFMAKeepsManifestUninstallScript(t *testing.T) {
const (
code = "{B681CB20-107E-428A-9B14-2D3C1AFED244}"
Expand Down
9 changes: 4 additions & 5 deletions server/datastore/mysql/software_installers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4584,11 +4584,10 @@ func (ds *Datastore) GetSoftwareInstallersPendingDeletion(ctx context.Context, t
globalOrTeamID = *tmID
}

// An installer survives a batch set iff its title matches an incoming
// (unique_identifier, source) key with extension_for = '' — the same
// matching BatchSetSoftwareInstallers uses to upsert titles before
// deleting installers with title_id NOT IN the upserted set. DISTINCT
// collapses multiple installer rows (cached FMA versions) of one title.
// Reports the team's installers whose title matches no incoming
// (unique_identifier, source) key with extension_for = ''. BatchSetSoftwareInstallers
// also keeps a title a payload attaches to by name; the caller drops those.
// DISTINCT collapses multiple installer rows (cached FMA versions) of one title.
stmt := `
SELECT DISTINCT
si.team_id,
Expand Down
7 changes: 3 additions & 4 deletions server/fleet/datastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -3628,10 +3628,9 @@ type Datastore interface {
BatchSetInHouseAppsInstallers(ctx context.Context, tmID *uint, installers []*UploadSoftwareInstallerPayload) error
GetSoftwareInstallers(ctx context.Context, tmID uint) ([]SoftwarePackageResponse, error)
// GetSoftwareInstallersPendingDeletion returns the software installers on the given team
// whose title matches none of the incoming title identifiers, i.e. the installers that a
// batch-set operation with those incoming titles will delete. It uses the same
// (unique_identifier, source) title-matching semantics as BatchSetSoftwareInstallers'
// deletion. An empty incoming list returns all installers on the team.
// whose title matches none of the incoming (unique_identifier, source) title identifiers.
// BatchSetSoftwareInstallers also keeps a title a payload attaches to by name, so the
// caller filters those out. An empty incoming list returns all installers on the team.
GetSoftwareInstallersPendingDeletion(ctx context.Context, tmID *uint, incoming []SoftwareTitleIdentifier) ([]DeletedSoftwarePackage, error)

// HasSelfServiceSoftwareInstallers returns true if self-service software installers are available for the team or globally.
Expand Down
54 changes: 54 additions & 0 deletions server/service/integration_enterprise_software_batch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1129,6 +1129,60 @@ func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersMSIReuseP
mu.Unlock()
}

func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersKeepsTitleAttachedByName() {
t := s.T()
ctx := t.Context()

tm, err := s.ds.NewTeam(ctx, &fleet.Team{Name: t.Name()})
require.NoError(t, err)

// A title from inventory with no bundle ID. The lookup prefers a title with the package's bundle ID, so drop any left by other tests.
var titleID uint
mysqltest.ExecAdhocSQL(t, s.ds, func(q sqlx.ExtContext) error {
if _, err := q.ExecContext(ctx, `DELETE FROM software_titles WHERE name = 'DummyApp' OR bundle_identifier = 'com.example.dummy'`); err != nil {
return err
}
res, err := q.ExecContext(ctx, `INSERT INTO software_titles (name, source) VALUES ('dummyapp', 'apps')`)
if err != nil {
return err
}
id, err := res.LastInsertId()
titleID = uint(id) //nolint:gosec // dismiss G115
return err
})

srv := httptest.NewServer(http.FileServer(http.Dir(filepath.Join("testdata", "software-installers"))))
t.Cleanup(srv.Close)
pkg := []*fleet.SoftwareInstallerPayload{{URL: srv.URL + "/dummy_installer.pkg"}}
batchDeleted := func(payloads []*fleet.SoftwareInstallerPayload, dryRun bool) []fleet.DeletedSoftwarePackage {
var resp batchSetSoftwareInstallersResponse
s.DoJSON("POST", "/api/latest/fleet/software/batch",
batchSetSoftwareInstallersRequest{Software: payloads},
http.StatusAccepted, &resp, "team_name", tm.Name, "dry_run", strconv.FormatBool(dryRun))
result := waitBatchSetSoftwareInstallers(t, &s.withServer, tm.Name, resp.RequestUUID)
require.Equal(t, fleet.BatchSetSoftwareInstallersStatusCompleted, result.Status, result.Message)
return result.DeletedPackages
}

// The apply attaches the package to the inventory title by name.
require.Empty(t, batchDeleted(pkg, false))
var installerTitleID uint
mysqltest.ExecAdhocSQL(t, s.ds, func(q sqlx.ExtContext) error {
return sqlx.GetContext(ctx, q, &installerTitleID, `SELECT title_id FROM software_installers WHERE global_or_team_id = ?`, tm.ID)
})
require.Equal(t, titleID, installerTitleID)

// Batching it again reports nothing, dry run or not.
for _, dryRun := range []bool{true, false} {
require.Empty(t, batchDeleted(pkg, dryRun))
}

// Removing the package from the payload still reports it.
deleted := batchDeleted([]*fleet.SoftwareInstallerPayload{}, true)
require.Len(t, deleted, 1)
require.Equal(t, titleID, deleted[0].TitleID)
}

func (s *integrationEnterpriseTestSuite) TestBatchSetSoftwareInstallersConditionalDownload() {
t := s.T()

Expand Down
Loading