Files
Lucas Manuel Rodriguez 58a7679144 Add support for nested Entra groups in IdP vitals (#50469)
Resolves #48886.

- [X] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files)
for more information.

## Testing

- [X] Added/updated automated tests
- [x] QA'd all new/changed functionality manually

## Database migrations

- [X] Checked schema for all modified table for columns that will
auto-update timestamps during migration.
- [X] Confirmed that updating the timestamps is acceptable, and will not
cause unwanted side effects.
- [X] Ensured the correct collation is explicitly set for character
columns (`COLLATE utf8mb4_unicode_ci`).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
  * Added support for nested groups in Entra IDP vitals.
* SCIM groups can now include child groups and resolve membership across
multiple levels.
* Host filters and group-based access now account for inherited group
memberships.
* Added validation and duplicate prevention for nested group membership
updates.

* **Bug Fixes**
* Corrected membership updates and removals to keep nested group
relationships synchronized.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-06 11:28:43 -03:00

1769 lines
63 KiB
Go

package service
import (
"context"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"testing"
"time"
activity_api "github.com/fleetdm/fleet/v4/server/activity/api"
authz_ctx "github.com/fleetdm/fleet/v4/server/contexts/authz"
"github.com/fleetdm/fleet/v4/server/contexts/ctxerr"
"github.com/fleetdm/fleet/v4/server/contexts/license"
"github.com/fleetdm/fleet/v4/server/contexts/viewer"
"github.com/fleetdm/fleet/v4/server/datastore/mysql"
"github.com/fleetdm/fleet/v4/server/datastore/mysql/mysqltest"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/fleetdm/fleet/v4/server/mock"
"github.com/fleetdm/fleet/v4/server/platform/mysql/testing_utils"
"github.com/fleetdm/fleet/v4/server/ptr"
"github.com/fleetdm/fleet/v4/server/test"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestWhenCreatingNewLabelsPlatformIsValidated(t *testing.T) {
t.Parallel()
ds := new(mock.Store)
user := &fleet.User{
ID: 3,
Email: "foo@bar.com",
GlobalRole: ptr.String(fleet.RoleAdmin),
}
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
// Stubs
expectedNewLabel := fleet.Label{Name: "newly created label"}
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
return &expectedNewLabel, nil
}
ds.HostIDsByIdentifierFunc = func(ctx context.Context, filter fleet.TeamFilter, hostnames []string) ([]uint, error) {
return nil, nil
}
ds.UpdateLabelMembershipByHostIDsFunc = func(ctx context.Context, label fleet.Label, hostIds []uint, teamFilter fleet.TeamFilter) (*fleet.Label, []uint, error) {
return nil, nil, nil
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{}, nil
}
ds.SetAsideLabelsFunc = func(ctx context.Context, notOnTeamID *uint, names []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorId *uint) error {
return nil
}
testCases := []struct {
Name string
Platforms []string
ShouldFail bool
}{
{
Name: "valid platforms",
Platforms: slices.Collect(maps.Keys(fleet.ValidLabelPlatformVariants)),
},
{
Name: "empty platforms",
Platforms: []string{""},
},
{
Name: "invalid platforms",
Platforms: []string{"biscuits_with_gravy"},
ShouldFail: true,
},
}
name := t.Name()
description := "bar"
query := "select * from foo;"
labelType := fleet.LabelTypeRegular
labelMembershipType := fleet.LabelMembershipTypeDynamic
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
for _, platform := range tc.Platforms {
actualNewLabel, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: name,
Query: query,
Description: description,
Platform: platform,
})
if tc.ShouldFail {
require.Contains(t, err.Error(), fmt.Sprintf("invalid platform: %q", platform))
} else {
require.NoError(t, err)
require.NotNil(t, actualNewLabel)
}
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{{
Name: name,
Description: description,
Query: query,
LabelType: labelType,
LabelMembershipType: labelMembershipType,
Platform: platform,
}}, nil, nil)
if tc.ShouldFail {
require.Contains(t, err.Error(), fmt.Sprintf("invalid platform: %q", platform))
} else {
require.NoError(t, err)
}
}
})
}
}
func TestLabelsAuth(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
lbl.ID = 1
if lbl.Name == "Other label" {
lbl.ID = 2
}
return lbl, nil
}
ds.SaveLabelFunc = func(ctx context.Context, lbl *fleet.Label, hostIDs []uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{Label: *lbl}, nil, nil
}
ds.DeleteLabelFunc = func(ctx context.Context, nm string, filter fleet.TeamFilter) error {
return nil
}
ds.ApplyLabelSpecsFunc = func(ctx context.Context, specs []*fleet.LabelSpec) error {
return nil
}
team1ID := uint(1)
team2ID := uint(2)
team1LabelID := uint(3)
team2LabelID := uint(4)
team1Label := fleet.Label{ID: team1LabelID, Name: "team1-label", TeamID: &team1ID}
team2Label := fleet.Label{ID: team2LabelID, Name: "team2-label", TeamID: &team2ID}
// Update LabelFunc to handle team labels
ds.LabelFunc = func(ctx context.Context, id uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
switch id {
case uint(1):
return &fleet.LabelWithTeamName{Label: fleet.Label{ID: id, AuthorID: &filter.User.ID}}, nil, nil
case uint(2):
return &fleet.LabelWithTeamName{Label: fleet.Label{ID: id}}, nil, nil
case team1LabelID: // team1 label
return &fleet.LabelWithTeamName{Label: team1Label}, nil, nil
case team2LabelID: // team2 label
return &fleet.LabelWithTeamName{Label: team2Label}, nil, nil
}
return nil, nil, ctxerr.Wrap(ctx, &notFoundErr{Msg: "label"})
}
ds.LabelByNameFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) (*fleet.Label, error) {
switch name {
case "team1-label":
return &team1Label, nil
case "team2-label":
return &team2Label, nil
default:
return &fleet.Label{ID: 2, Name: name}, nil
}
}
ds.ListLabelsFunc = func(ctx context.Context, filter fleet.TeamFilter, opts fleet.ListOptions, includeHostCounts bool) ([]*fleet.Label, error) {
return nil, nil
}
ds.LabelsSummaryFunc = func(ctx context.Context, filter fleet.TeamFilter) ([]*fleet.LabelSummary, error) {
return nil, nil
}
ds.ListHostsInLabelFunc = func(ctx context.Context, filter fleet.TeamFilter, lid uint, opts fleet.HostListOptions) ([]*fleet.Host, error) {
return nil, nil
}
ds.GetLabelSpecsFunc = func(ctx context.Context, filter fleet.TeamFilter) ([]*fleet.LabelSpec, error) {
return nil, nil
}
ds.GetLabelSpecFunc = func(ctx context.Context, filter fleet.TeamFilter, name string) (*fleet.LabelSpec, error) {
return &fleet.LabelSpec{}, nil
}
ds.TeamLiteFunc = func(ctx context.Context, tid uint) (*fleet.TeamLite, error) {
return &fleet.TeamLite{ID: tid, Name: fmt.Sprintf("team-%d", tid)}, nil
}
testCases := []struct {
name string
user *fleet.User
shouldFailGlobalWrite bool
shouldFailGlobalRead bool
shouldFailGlobalWriteIfAuthor bool
shouldFailTeam1Write bool
shouldFailTeam1Read bool
shouldFailTeam2Write bool
shouldFailTeam2Read bool
}{
{
"global admin",
&fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)},
false,
false,
false,
false,
false,
false,
false,
},
{
"global maintainer",
&fleet.User{GlobalRole: ptr.String(fleet.RoleMaintainer)},
false,
false,
false,
false,
false,
false,
false,
},
{
"global observer",
&fleet.User{GlobalRole: ptr.String(fleet.RoleObserver)},
true,
false,
true,
true,
false,
true,
false,
},
{
"team 1 maintainer",
&fleet.User{Teams: []fleet.UserTeam{{Team: fleet.Team{ID: 1}, Role: fleet.RoleMaintainer}}},
true,
false,
false,
false,
false,
true,
true,
},
{
"team 1 observer",
&fleet.User{Teams: []fleet.UserTeam{{Team: fleet.Team{ID: 1}, Role: fleet.RoleObserver}}},
true,
false,
true,
true,
false,
true,
true,
},
}
// add a new label authored by no one so we can check writes for labels that aren't authored by the user
otherLabel, _, err := svc.NewLabel(viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{ID: 1, GlobalRole: ptr.String(fleet.RoleMaintainer)}}), fleet.LabelPayload{Name: "Other label", Query: "SELECT 0"})
require.NoError(t, err)
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
ctx := viewer.NewContext(ctx, viewer.Viewer{User: tt.user})
myLabel, _, err := svc.NewLabel(ctx, fleet.LabelPayload{Name: t.Name(), Query: `SELECT 1`})
checkAuthErr(t, tt.shouldFailGlobalWriteIfAuthor, err) // team write users can still create global labels
if myLabel != nil {
_, _, err = svc.ModifyLabel(ctx, myLabel.ID, fleet.ModifyLabelPayload{})
checkAuthErr(t, tt.shouldFailGlobalWriteIfAuthor, err)
}
if myLabel != nil {
err = svc.DeleteLabelByID(ctx, myLabel.ID)
checkAuthErr(t, tt.shouldFailGlobalWriteIfAuthor, err)
}
for _, tc := range []struct {
label fleet.Label
shouldFailWrite bool
shouldFailRead bool
}{
{*otherLabel, tt.shouldFailGlobalWrite, tt.shouldFailGlobalRead},
{team1Label, tt.shouldFailTeam1Write, tt.shouldFailTeam1Read},
{team2Label, tt.shouldFailTeam2Write, tt.shouldFailTeam2Read},
} {
t.Run(tc.label.Name, func(t *testing.T) {
ctx2 := ctx
if tc.label.TeamID != nil {
// license check is after auth check
if !tc.shouldFailRead {
_, err = svc.GetLabelSpecs(ctx2, tc.label.TeamID)
require.ErrorIs(t, err, fleet.ErrMissingLicense)
_, err = svc.ListLabels(ctx2, fleet.ListOptions{}, tc.label.TeamID, true)
require.ErrorIs(t, err, fleet.ErrMissingLicense)
_, err = svc.LabelsSummary(ctx2, tc.label.TeamID)
require.ErrorIs(t, err, fleet.ErrMissingLicense)
}
if !tc.shouldFailWrite {
require.ErrorIs(t, svc.ApplyLabelSpecs(ctx2, []*fleet.LabelSpec{}, tc.label.TeamID, nil), fleet.ErrMissingLicense)
// We'll let global admins clean up team labels if they downgraded to Free
require.NoError(t, svc.DeleteLabel(ctx2, tc.label.Name))
require.NoError(t, svc.DeleteLabelByID(ctx2, tc.label.ID))
}
ctx2 = license.NewContext(ctx2, &fleet.LicenseInfo{Tier: fleet.TierPremium})
}
err = svc.ApplyLabelSpecs(ctx2, []*fleet.LabelSpec{}, tc.label.TeamID, nil)
checkAuthErr(t, tc.shouldFailWrite, err)
_, err = svc.GetLabelSpecs(ctx2, tc.label.TeamID)
checkAuthErr(t, tc.shouldFailRead, err)
_, err = svc.ListLabels(ctx2, fleet.ListOptions{}, tc.label.TeamID, true)
checkAuthErr(t, tc.shouldFailRead, err)
_, err = svc.LabelsSummary(ctx2, tc.label.TeamID)
checkAuthErr(t, tc.shouldFailRead, err)
err = svc.DeleteLabel(ctx2, tc.label.Name)
checkAuthErr(t, tc.shouldFailWrite, err)
err = svc.DeleteLabelByID(ctx2, tc.label.ID)
checkAuthErr(t, tc.shouldFailWrite, err)
})
}
// filtering is done in the data store for these; NOT enforcing premium license checks here
_, err = svc.GetLabelSpec(ctx, "abc")
checkAuthErr(t, tt.shouldFailGlobalRead, err)
_, err = svc.ListHostsInLabel(ctx, 1, fleet.HostListOptions{})
checkAuthErr(t, tt.shouldFailGlobalRead, err)
_, _, err = svc.GetLabel(ctx, 1)
checkAuthErr(t, tt.shouldFailGlobalRead, err)
_, _, err = svc.ModifyLabel(ctx, otherLabel.ID, fleet.ModifyLabelPayload{})
checkAuthErr(t, tt.shouldFailGlobalWrite, err)
// global label listing should work if you can read global labels
_, err = svc.GetLabelSpecs(ctx, ptr.Uint(0))
checkAuthErr(t, tt.shouldFailGlobalRead, err)
_, err = svc.ListLabels(ctx, fleet.ListOptions{}, ptr.Uint(0), true)
checkAuthErr(t, tt.shouldFailGlobalRead, err)
})
}
}
func TestListLabelsHostCountOptions(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
ds.ListLabelsFunc = func(ctx context.Context, filter fleet.TeamFilter, opts fleet.ListOptions, includeHostCounts bool) ([]*fleet.Label, error) {
// Expect host counts not to be requested
require.False(t, includeHostCounts)
return nil, nil
}
// Test explicitly setting include_host_counts to false
_, err := svc.ListLabels(ctx, fleet.ListOptions{}, nil, false)
require.NoError(t, err)
ds.ListLabelsFunc = func(ctx context.Context, filter fleet.TeamFilter, opts fleet.ListOptions, includeHostCounts bool) ([]*fleet.Label, error) {
// Expect host counts to be requested
require.True(t, includeHostCounts)
// Expect the team filter to be set
require.Equal(t, filter.User, user)
return nil, nil
}
// Test explicitly setting include_host_counts to true
_, err = svc.ListLabels(ctx, fleet.ListOptions{}, nil, true)
require.NoError(t, err)
}
func TestLabelsWithDS(t *testing.T) {
ds := mysqltest.CreateMySQLDS(t)
cases := []struct {
name string
fn func(t *testing.T, ds *mysql.Datastore)
}{
{"GetLabel", testLabelsGetLabel},
{"ListLabels", testLabelsListLabels},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
defer mysqltest.TruncateTables(t, ds)
c.fn(t, ds)
})
}
}
func testLabelsGetLabel(t *testing.T, ds *mysql.Datastore) {
svc, ctx := newTestService(t, ds, nil, nil)
label := &fleet.Label{
Name: "foo",
Query: "select * from foo;",
}
label, err := ds.NewLabel(ctx, label)
assert.Nil(t, err)
assert.NotZero(t, label.ID)
labelVerify, _, err := svc.GetLabel(test.UserContext(ctx, test.UserAdmin), label.ID)
assert.Nil(t, err)
assert.Equal(t, label.ID, labelVerify.ID)
assert.Nil(t, label.AuthorID)
}
func testLabelsListLabels(t *testing.T, ds *mysql.Datastore) {
svc, ctx := newTestService(t, ds, nil, nil)
require.NoError(t, ds.MigrateData(context.Background()))
labels, err := svc.ListLabels(test.UserContext(ctx, test.UserAdmin), fleet.ListOptions{Page: 0, PerPage: 1000}, nil, true)
require.NoError(t, err)
require.Len(t, labels, 8)
labelsSummary, err := svc.LabelsSummary(test.UserContext(ctx, test.UserAdmin), nil)
require.NoError(t, err)
require.Len(t, labelsSummary, 8)
}
func TestApplyLabelSpecsWithBuiltInLabels(t *testing.T) {
t.Parallel()
ds := new(mock.Store)
user := &fleet.User{
ID: 3,
Email: "foo@bar.com",
GlobalRole: ptr.String(fleet.RoleAdmin),
}
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
name := "foo"
description := "bar"
query := "select * from foo;"
platform := ""
labelType := fleet.LabelTypeBuiltIn
labelMembershipType := fleet.LabelMembershipTypeDynamic
spec := &fleet.LabelSpec{
Name: name,
Description: description,
Query: query,
LabelType: labelType,
LabelMembershipType: labelMembershipType,
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{
name: {
Name: name,
Description: description,
Query: query,
Platform: platform,
LabelType: labelType,
LabelMembershipType: labelMembershipType,
},
}, nil
}
// all good
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
require.NoError(t, err)
// trying to add a regular label with the same name as a built-in label should fail
for name := range fleet.ReservedLabelNames() {
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: name,
Description: description,
Query: query,
LabelType: fleet.LabelTypeRegular,
},
}, nil, nil)
assert.ErrorContains(t, err,
fmt.Sprintf("cannot add label '%s' because it conflicts with the name of a built-in label", name))
}
const errorMessage = "cannot modify or add built-in label"
// not ok -- built-in label name doesn't exist
name = "not-foo"
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorContains(t, err, errorMessage)
name = "foo"
// not ok -- description does not match
description = "not-bar"
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorContains(t, err, errorMessage)
description = "bar"
// not ok -- query does not match
query = "select * from not-foo;"
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorContains(t, err, errorMessage)
query = "select * from foo;"
// not ok -- label type does not match
labelType = fleet.LabelTypeRegular
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorContains(t, err, errorMessage)
labelType = fleet.LabelTypeBuiltIn
// not ok -- label membership type does not match
labelMembershipType = fleet.LabelMembershipTypeManual
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorContains(t, err, errorMessage)
labelMembershipType = fleet.LabelMembershipTypeDynamic
// not ok -- DB error
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return nil, assert.AnError
}
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{spec}, nil, nil)
assert.ErrorIs(t, err, assert.AnError)
}
func TestApplyLabelSpecsCustomHostVitalCriteria(t *testing.T) {
t.Parallel()
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{ID: 1, GlobalRole: new(fleet.RoleAdmin)}})
specWithCriteria := func(criteria fleet.HostVitalCriteria) *fleet.LabelSpec {
raw, err := json.Marshal(&criteria)
require.NoError(t, err)
return &fleet.LabelSpec{
Name: "custom-vital-spec",
LabelType: fleet.LabelTypeRegular,
LabelMembershipType: fleet.LabelMembershipTypeHostVitals,
HostVitalsCriteria: new(json.RawMessage(raw)),
}
}
// A custom_host_vital criterion without an id fails structural validation
// before any datastore call.
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{specWithCriteria(fleet.HostVitalCriteria{
Vital: new("custom_host_vital"),
Value: new("Engineering"),
})}, nil, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "custom_host_vital_id")
// A criterion referencing a non-existent custom vital is rejected.
ds.GetCustomHostVitalsFunc = func(ctx context.Context, ids []uint) ([]fleet.CustomHostVital, error) {
return nil, nil
}
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{specWithCriteria(fleet.HostVitalCriteria{
Vital: new("custom_host_vital"),
Value: new("Engineering"),
CustomHostVitalID: new(uint(999)),
})}, nil, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "does not exist")
require.True(t, ds.GetCustomHostVitalsFuncInvoked)
}
func TestLabelsWithReplica(t *testing.T) {
opts := &testing_utils.DatastoreTestOptions{DummyReplica: true}
ds := mysqltest.CreateMySQLDSWithOptions(t, opts)
defer ds.Close()
svc, ctx := newTestService(t, ds, nil, nil)
user, err := ds.NewUser(ctx, &fleet.User{
Name: "Adminboi",
Password: []byte("p4ssw0rd.123"),
Email: "admin@example.com",
GlobalRole: ptr.String(fleet.RoleAdmin),
})
require.NoError(t, err)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
// create a couple hosts
h1, err := ds.NewHost(ctx, &fleet.Host{
Hostname: "host1",
HardwareSerial: uuid.NewString(),
UUID: uuid.NewString(),
Platform: "darwin",
LastEnrolledAt: time.Now(),
DetailUpdatedAt: time.Now(),
})
require.NoError(t, err)
h2, err := ds.NewHost(ctx, &fleet.Host{
Hostname: "host2",
HardwareSerial: uuid.NewString(),
UUID: uuid.NewString(),
Platform: "darwin",
LastEnrolledAt: time.Now(),
DetailUpdatedAt: time.Now(),
})
require.NoError(t, err)
// make the newly-created hosts available to the reader
opts.RunReplication()
lbl, hostIDs, err := svc.NewLabel(ctx, fleet.LabelPayload{Name: "label1", Hosts: []string{"host1", "host2"}})
require.NoError(t, err)
require.ElementsMatch(t, []uint{h1.ID, h2.ID}, hostIDs)
require.Equal(t, 2, lbl.HostCount)
require.Equal(t, user.ID, *lbl.AuthorID)
// make the newly-created label available to the reader
opts.RunReplication("labels", "label_membership")
lblWithName, hostIDs, err := svc.ModifyLabel(ctx, lbl.ID, fleet.ModifyLabelPayload{Hosts: []string{"host1"}})
require.NoError(t, err)
require.ElementsMatch(t, []uint{h1.ID}, hostIDs)
require.Equal(t, 1, lblWithName.HostCount)
require.Equal(t, user.ID, *lblWithName.AuthorID)
// reading this label without replication returns the old data as it only uses the reader
lblWithName, hostIDs, err = svc.GetLabel(ctx, lblWithName.ID)
require.NoError(t, err)
require.ElementsMatch(t, []uint{h1.ID, h2.ID}, hostIDs)
require.Equal(t, 2, lblWithName.HostCount)
require.Equal(t, user.ID, *lblWithName.AuthorID)
// running the replication makes the updated data available
opts.RunReplication("labels", "label_membership")
lblWithName, hostIDs, err = svc.GetLabel(ctx, lblWithName.ID)
require.NoError(t, err)
require.ElementsMatch(t, []uint{h1.ID}, hostIDs)
require.Equal(t, 1, lblWithName.HostCount)
require.Equal(t, user.ID, *lblWithName.AuthorID)
}
func TestLabelCrossTeamHostMembership(t *testing.T) {
ds := mysqltest.CreateMySQLDS(t)
defer ds.Close()
svc, ctx := newTestService(t, ds, nil, nil)
// A global admin used only to inspect the resulting label membership.
adminUser, err := ds.NewUser(ctx, &fleet.User{
Name: "Admin",
Password: []byte("p4ssw0rd.123"),
Email: "admin@example.com",
GlobalRole: new(fleet.RoleAdmin),
})
require.NoError(t, err)
adminFilter := fleet.TeamFilter{User: adminUser}
team1, err := ds.NewTeam(ctx, &fleet.Team{Name: "team1"})
require.NoError(t, err)
team2, err := ds.NewTeam(ctx, &fleet.Team{Name: "team2"})
require.NoError(t, err)
// A user who can only write to team1 (team admins/maintainers are allowed
// to create global labels per the authorization policy).
team1User, err := ds.NewUser(ctx, &fleet.User{
Name: "Team1 Maintainer",
Password: []byte("p4ssw0rd.123"),
Email: "team1@example.com",
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: team1.ID}, Role: fleet.RoleMaintainer},
},
})
require.NoError(t, err)
team1Ctx := viewer.NewContext(ctx, viewer.Viewer{User: team1User})
// A host on team1 (team1User can write to it) and a host on team2 (it can't).
team1Host, err := ds.NewHost(ctx, &fleet.Host{
Hostname: "team1-host",
HardwareSerial: uuid.NewString(),
UUID: uuid.NewString(),
Platform: "darwin",
LastEnrolledAt: time.Now(),
DetailUpdatedAt: time.Now(),
})
require.NoError(t, err)
require.NoError(t, ds.AddHostsToTeam(ctx, fleet.NewAddHostsToTeamParams(&team1.ID, []uint{team1Host.ID})))
team2Host, err := ds.NewHost(ctx, &fleet.Host{
Hostname: "team2-host",
HardwareSerial: uuid.NewString(),
UUID: uuid.NewString(),
Platform: "darwin",
LastEnrolledAt: time.Now(),
DetailUpdatedAt: time.Now(),
})
require.NoError(t, err)
require.NoError(t, ds.AddHostsToTeam(ctx, fleet.NewAddHostsToTeamParams(&team2.ID, []uint{team2Host.ID})))
t.Run("NewLabel rejects cross-team host_ids", func(t *testing.T) {
_, _, err := svc.NewLabel(team1Ctx, fleet.LabelPayload{
Name: "cross-team-create",
HostIDs: []uint{team2Host.ID},
})
// team1User has no write access to the team2 host, so this must fail
// authorization rather than silently attaching the host.
checkAuthErr(t, true, err)
})
t.Run("ModifyLabel rejects cross-team host_ids", func(t *testing.T) {
// Create an empty manual global label as the team1 user.
lbl, _, err := svc.NewLabel(team1Ctx, fleet.LabelPayload{Name: "cross-team-modify"})
require.NoError(t, err)
_, _, err = svc.ModifyLabel(team1Ctx, lbl.ID, fleet.ModifyLabelPayload{
HostIDs: []uint{team2Host.ID},
})
checkAuthErr(t, true, err)
// The membership must be unchanged (empty).
hosts, err := ds.ListHostsInLabel(ctx, adminFilter, lbl.ID, fleet.HostListOptions{})
require.NoError(t, err)
require.Empty(t, hosts, "team1 user must not attach a team2 host via raw host_ids")
})
t.Run("read-only access to the target team is rejected", func(t *testing.T) {
// A user who can write to team1 but only has read-only (observer_plus)
// access to team2 must not be able to attach team2 hosts: membership is
// a write operation and requires write authorization on the host.
readOnlyUser, err := ds.NewUser(ctx, &fleet.User{
Name: "Team1 Maintainer, Team2 Observer+",
Password: []byte("p4ssw0rd.123"),
Email: "team1team2@example.com",
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: team1.ID}, Role: fleet.RoleMaintainer},
{Team: fleet.Team{ID: team2.ID}, Role: fleet.RoleObserverPlus},
},
})
require.NoError(t, err)
readOnlyCtx := viewer.NewContext(ctx, viewer.Viewer{User: readOnlyUser})
_, _, err = svc.NewLabel(readOnlyCtx, fleet.LabelPayload{
Name: "read-only-target-team",
HostIDs: []uint{team2Host.ID},
})
checkAuthErr(t, true, err)
})
t.Run("read-only access to the target team is rejected by host name", func(t *testing.T) {
// The by-name path resolves identifiers the caller can see, so an
// observer_plus on team2 resolves the team2 host and must then be
// rejected by the write-authorization check (unlike a user with no
// access to team2, for whom the host name resolves to nothing).
readOnlyUser, err := ds.NewUser(ctx, &fleet.User{
Name: "Team1 Maintainer, Team2 Observer+ (by name)",
Password: []byte("p4ssw0rd.123"),
Email: "team1team2-byname@example.com",
Teams: []fleet.UserTeam{
{Team: fleet.Team{ID: team1.ID}, Role: fleet.RoleMaintainer},
{Team: fleet.Team{ID: team2.ID}, Role: fleet.RoleObserverPlus},
},
})
require.NoError(t, err)
readOnlyCtx := viewer.NewContext(ctx, viewer.Viewer{User: readOnlyUser})
_, _, err = svc.NewLabel(readOnlyCtx, fleet.LabelPayload{
Name: "read-only-target-team-by-name",
Hosts: []string{"team2-host"},
})
checkAuthErr(t, true, err)
})
t.Run("a mix of in-scope and out-of-scope hosts is rejected atomically", func(t *testing.T) {
// Create a manual label with an in-scope team1 host, then attempt to
// add a second team1 host together with the out-of-scope team2 host.
// The request must be rejected and leave membership unchanged, so the
// in-scope host is not partially applied.
team1Host2, err := ds.NewHost(ctx, &fleet.Host{
Hostname: "team1-host-2",
HardwareSerial: uuid.NewString(),
UUID: uuid.NewString(),
Platform: "darwin",
LastEnrolledAt: time.Now(),
DetailUpdatedAt: time.Now(),
})
require.NoError(t, err)
require.NoError(t, ds.AddHostsToTeam(ctx, fleet.NewAddHostsToTeamParams(&team1.ID, []uint{team1Host2.ID})))
lbl, _, err := svc.NewLabel(team1Ctx, fleet.LabelPayload{
Name: "atomic-mix",
HostIDs: []uint{team1Host.ID},
})
require.NoError(t, err)
_, _, err = svc.ModifyLabel(team1Ctx, lbl.ID, fleet.ModifyLabelPayload{
HostIDs: []uint{team1Host2.ID, team2Host.ID},
})
checkAuthErr(t, true, err)
// Membership must be unchanged: still only the original team1 host.
hosts, err := ds.ListHostsInLabel(ctx, adminFilter, lbl.ID, fleet.HostListOptions{})
require.NoError(t, err)
require.Len(t, hosts, 1)
require.Equal(t, team1Host.ID, hosts[0].ID)
})
t.Run("non-existent host_ids are rejected", func(t *testing.T) {
// A host ID that does not exist must not silently bypass the
// authorization check; the request is rejected as invalid.
_, _, err := svc.NewLabel(team1Ctx, fleet.LabelPayload{
Name: "missing-host",
HostIDs: []uint{999999},
})
require.Error(t, err)
require.ErrorContains(t, err, "does not exist")
})
t.Run("hosts the caller can write to are still allowed", func(t *testing.T) {
// Sanity check that the write-authorization check doesn't over-restrict:
// team1User can attach a team1 host to a global label they create, both
// by ID and by name, and can remove all hosts.
lbl, hostIDs, err := svc.NewLabel(team1Ctx, fleet.LabelPayload{
Name: "in-scope-create",
HostIDs: []uint{team1Host.ID},
})
require.NoError(t, err)
require.ElementsMatch(t, []uint{team1Host.ID}, hostIDs)
hosts, err := ds.ListHostsInLabel(ctx, adminFilter, lbl.ID, fleet.HostListOptions{})
require.NoError(t, err)
require.Len(t, hosts, 1)
require.Equal(t, team1Host.ID, hosts[0].ID)
// Modifying by name with an in-scope host is allowed.
_, hostIDs, err = svc.ModifyLabel(team1Ctx, lbl.ID, fleet.ModifyLabelPayload{
Hosts: []string{"team1-host"},
})
require.NoError(t, err)
require.ElementsMatch(t, []uint{team1Host.ID}, hostIDs)
// Removing all hosts (empty list) is allowed and needs no host authz.
_, hostIDs, err = svc.ModifyLabel(team1Ctx, lbl.ID, fleet.ModifyLabelPayload{
Hosts: []string{},
})
require.NoError(t, err)
require.Empty(t, hostIDs)
})
}
func TestBatchValidateLabels(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
t.Run("no auth context", func(t *testing.T) {
_, err := svc.BatchValidateLabels(context.Background(), nil, nil)
require.ErrorContains(t, err, "Authentication required")
})
authCtx := authz_ctx.AuthorizationContext{}
ctx = authz_ctx.NewContext(ctx, &authCtx)
t.Run("no auth checked", func(t *testing.T) {
_, err := svc.BatchValidateLabels(ctx, nil, nil)
require.ErrorContains(t, err, "Authentication required")
})
// validator requires that an authz check has been performed upstream so we'll set it now for
// the rest of the tests
authCtx.SetChecked()
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}})
mockLabels := map[string]uint{
"foo": 1,
"bar": 2,
"baz": 3,
}
mockLabelIdent := func(name string, id uint) fleet.LabelIdent {
return fleet.LabelIdent{LabelID: id, LabelName: name}
}
ds.LabelIDsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]uint, error) {
res := make(map[string]uint)
if names == nil {
return res, nil
}
for _, name := range names {
if id, ok := mockLabels[name]; ok {
res[name] = id
}
}
return res, nil
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
res := make(map[string]*fleet.Label)
if names == nil {
return res, nil
}
for _, name := range names {
if id, ok := mockLabels[name]; ok {
res[name] = &fleet.Label{
ID: id,
Name: name,
}
}
}
return res, nil
}
testCases := []struct {
name string
labelNames []string
expectLabels map[string]fleet.LabelIdent
expectError string
}{
{
"no labels",
nil,
nil,
"",
},
{
"include labels",
[]string{"foo", "bar"},
map[string]fleet.LabelIdent{
"foo": mockLabelIdent("foo", 1),
"bar": mockLabelIdent("bar", 2),
},
"",
},
{
"non-existent label",
[]string{"foo", "qux"},
nil,
"some or all the labels provided don't exist",
},
{
"duplicate label",
[]string{"foo", "foo"},
map[string]fleet.LabelIdent{
"foo": mockLabelIdent("foo", 1),
},
"",
},
{
"empty slice",
[]string{},
nil,
"",
},
{
"empty string",
[]string{""},
nil,
"some or all the labels provided don't exist",
},
}
for _, tt := range testCases {
t.Run(tt.name, func(t *testing.T) {
got, err := svc.BatchValidateLabels(ctx, nil, tt.labelNames)
if tt.expectError != "" {
require.Contains(t, err.Error(), tt.expectError)
} else {
require.NoError(t, err)
require.Equal(t, tt.expectLabels, got)
}
})
}
}
func TestApplyLabelSpecsManualLabelNilHosts(t *testing.T) {
t.Parallel()
ds := new(mock.Store)
user := &fleet.User{
ID: 3,
Email: "foo@bar.com",
GlobalRole: ptr.String(fleet.RoleAdmin),
}
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{}, nil
}
ds.SetAsideLabelsFunc = func(ctx context.Context, teamID *uint, namesToMove []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorID *uint) error {
return nil
}
// Manual label with nil hosts (omitted) should be accepted
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "manual_no_hosts",
LabelMembershipType: fleet.LabelMembershipTypeManual,
Hosts: nil,
},
}, nil, nil)
require.NoError(t, err)
// Manual label with empty hosts should also be accepted
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "manual_empty_hosts",
LabelMembershipType: fleet.LabelMembershipTypeManual,
Hosts: []string{},
},
}, nil, nil)
require.NoError(t, err)
// Dynamic label with hosts should still be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "dynamic_with_hosts",
Query: "SELECT 1",
LabelMembershipType: fleet.LabelMembershipTypeDynamic,
Hosts: []string{"host1"},
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as dynamic but contains hosts")
// Dynamic label without query should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "dynamic_no_query",
LabelMembershipType: fleet.LabelMembershipTypeDynamic,
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as dynamic but is missing a query")
// Dynamic label with criteria should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "dynamic_with_criteria",
Query: "SELECT 1",
LabelMembershipType: fleet.LabelMembershipTypeDynamic,
HostVitalsCriteria: new(json.RawMessage(`{"vital":"end_user_idp_group","operator":"=","value":"Engineering"}`)),
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as dynamic but contains criteria")
// Manual label with query should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "manual_with_query",
LabelMembershipType: fleet.LabelMembershipTypeManual,
Query: "SELECT 1",
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as manual but contains a query")
// Manual label with criteria should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "manual_with_criteria",
LabelMembershipType: fleet.LabelMembershipTypeManual,
HostVitalsCriteria: new(json.RawMessage(`{"vital":"end_user_idp_group","operator":"=","value":"Engineering"}`)),
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as manual but contains criteria")
// Manual label with platform should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "manual_with_platform",
LabelMembershipType: fleet.LabelMembershipTypeManual,
Platform: "darwin",
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as manual but contains a platform")
// Host_vitals label without criteria should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "host_vitals_no_criteria",
LabelMembershipType: fleet.LabelMembershipTypeHostVitals,
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as host_vitals but is missing criteria")
// Host_vitals label with query should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "host_vitals_with_query",
LabelMembershipType: fleet.LabelMembershipTypeHostVitals,
HostVitalsCriteria: new(json.RawMessage(`{"vital":"end_user_idp_group","operator":"=","value":"Engineering"}`)),
Query: "SELECT 1",
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as host_vitals but contains a query")
// Host_vitals label with platform should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "host_vitals_with_platform",
LabelMembershipType: fleet.LabelMembershipTypeHostVitals,
HostVitalsCriteria: new(json.RawMessage(`{"vital":"end_user_idp_group","operator":"=","value":"Engineering"}`)),
Platform: "darwin",
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as host_vitals but contains a platform")
// Host_vitals label with hosts should be rejected
err = svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{
Name: "host_vitals_with_hosts",
LabelMembershipType: fleet.LabelMembershipTypeHostVitals,
HostVitalsCriteria: new(json.RawMessage(`{"vital":"end_user_idp_group","operator":"=","value":"Engineering"}`)),
Hosts: []string{"host1"},
},
}, nil, nil)
require.Error(t, err)
require.ErrorContains(t, err, "declared as host_vitals but contains hosts")
}
// mockListHostsLiteByIDs sets up ListHostsLiteByIDs to return a lite host for
// each requested ID, so that label membership authorization can run in tests
// that use a mock datastore.
func mockListHostsLiteByIDs(ds *mock.Store) {
ds.ListHostsLiteByIDsFunc = func(ctx context.Context, ids []uint) ([]*fleet.Host, error) {
hosts := make([]*fleet.Host, 0, len(ids))
for _, id := range ids {
hosts = append(hosts, &fleet.Host{ID: id})
}
return hosts, nil
}
}
func TestNewManualLabel(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}})
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
lbl.ID = 1
lbl.LabelMembershipType = fleet.LabelMembershipTypeManual
return lbl, nil
}
ds.HostIDsByIdentifierFunc = func(ctx context.Context, filter fleet.TeamFilter, hostnames []string) ([]uint, error) {
return []uint{99, 100}, nil
}
mockListHostsLiteByIDs(ds)
t.Run("using hostnames", func(t *testing.T) {
ds.UpdateLabelMembershipByHostIDsFunc = func(ctx context.Context, label fleet.Label, hostIds []uint, teamFilter fleet.TeamFilter) (*fleet.Label, []uint, error) {
require.Equal(t, uint(1), label.ID)
require.Equal(t, []uint{99, 100}, hostIds)
return nil, nil, nil
}
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "foo",
Hosts: []string{"host1", "host2"},
})
require.NoError(t, err)
})
t.Run("using IDs", func(t *testing.T) {
ds.UpdateLabelMembershipByHostIDsFunc = func(ctx context.Context, label fleet.Label, hostIds []uint, teamFilter fleet.TeamFilter) (*fleet.Label, []uint, error) {
require.Equal(t, uint(1), label.ID)
require.Equal(t, []uint{1, 2}, hostIds)
return nil, nil, nil
}
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "foo",
HostIDs: []uint{1, 2},
})
require.NoError(t, err)
})
}
func TestModifyManualLabel(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}})
ds.LabelFunc = func(ctx context.Context, lid uint, teamFilter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{
Label: fleet.Label{
ID: lid,
LabelMembershipType: fleet.LabelMembershipTypeManual,
},
}, nil, nil
}
ds.HostIDsByIdentifierFunc = func(ctx context.Context, filter fleet.TeamFilter, hostnames []string) ([]uint, error) {
return []uint{99, 100}, nil
}
mockListHostsLiteByIDs(ds)
t.Run("using hostnames", func(t *testing.T) {
ds.SaveLabelFunc = func(ctx context.Context, lbl *fleet.Label, hostIDs []uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
require.Equal(t, uint(1), lbl.ID)
require.Equal(t, []uint{99, 100}, hostIDs)
return &fleet.LabelWithTeamName{Label: *lbl}, hostIDs, nil
}
_, _, err := svc.ModifyLabel(ctx, 1, fleet.ModifyLabelPayload{
Hosts: []string{"host1", "host2"},
})
require.NoError(t, err)
require.True(t, ds.SaveLabelFuncInvoked)
})
t.Run("using IDs", func(t *testing.T) {
ds.SaveLabelFunc = func(ctx context.Context, lbl *fleet.Label, hostIDs []uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
require.Equal(t, uint(1), lbl.ID)
require.Equal(t, []uint{1, 2}, hostIDs)
return &fleet.LabelWithTeamName{Label: *lbl}, hostIDs, nil
}
_, _, err := svc.ModifyLabel(ctx, 1, fleet.ModifyLabelPayload{
HostIDs: []uint{1, 2},
})
require.NoError(t, err)
require.True(t, ds.SaveLabelFuncInvoked)
})
}
func TestNewHostVitalsLabel(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}})
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
return lbl, nil
}
t.Run("create host vitals label", func(t *testing.T) {
lbl, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "foo",
Criteria: &fleet.HostVitalCriteria{
Vital: ptr.String("end_user_idp_group"),
Value: ptr.String("admin"),
},
})
require.NoError(t, err)
assert.Equal(t, fleet.LabelTypeRegular, lbl.LabelType)
assert.Equal(t, fleet.LabelMembershipTypeHostVitals, lbl.LabelMembershipType)
// Test parsing the criteria
query, queryValues, err := lbl.CalculateHostVitalsQuery()
require.NoError(t, err)
queryValuesJson, err := json.Marshal(queryValues)
require.NoError(t, err)
// Compare whitespace-normalized SQL: the IdP join fragment is a multi-line
// raw string whose indentation is irrelevant to the query's meaning.
assert.Equal(t,
"SELECT %s FROM %s JOIN host_scim_user ON (hosts.id = host_scim_user.host_id) JOIN scim_users ON (host_scim_user.scim_user_id = scim_users.id) LEFT JOIN ( WITH RECURSIVE scim_user_group_expanded AS ( SELECT scim_user_id, group_id FROM scim_user_group WHERE scim_user_id IN (SELECT scim_user_id FROM host_scim_user) UNION SELECT e.scim_user_id, gg.parent_group_id AS group_id FROM scim_user_group_expanded e JOIN scim_group_group gg ON gg.child_group_id = e.group_id ) SELECT scim_user_id, group_id FROM scim_user_group_expanded ) scim_user_group ON (host_scim_user.scim_user_id = scim_user_group.scim_user_id) LEFT JOIN scim_groups ON (scim_user_group.group_id = scim_groups.id) WHERE scim_groups.display_name = ? GROUP BY hosts.id",
strings.Join(strings.Fields(query), " "))
assert.Equal(t, `["admin"]`, string(queryValuesJson))
})
t.Run("create custom host vital label", func(t *testing.T) {
ds.GetCustomHostVitalsFunc = func(ctx context.Context, ids []uint) ([]fleet.CustomHostVital, error) {
return []fleet.CustomHostVital{{ID: 7, Name: "Department"}}, nil
}
ds.GetCustomHostVitalsFuncInvoked = false
lbl, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "custom-vital-label",
Criteria: &fleet.HostVitalCriteria{
Vital: new("custom_host_vital"),
Value: new("Engineering"),
CustomHostVitalID: new(uint(7)),
},
})
require.NoError(t, err)
assert.True(t, ds.GetCustomHostVitalsFuncInvoked)
assert.Equal(t, fleet.LabelMembershipTypeHostVitals, lbl.LabelMembershipType)
query, queryValues, err := lbl.CalculateHostVitalsQuery()
require.NoError(t, err)
queryValuesJson, err := json.Marshal(queryValues)
require.NoError(t, err)
assert.Equal(t, "SELECT %s FROM %s JOIN host_custom_host_vitals ON (hosts.id = host_custom_host_vitals.host_id AND host_custom_host_vitals.custom_host_vital_id = ?) WHERE host_custom_host_vitals.value = ? GROUP BY hosts.id", query)
assert.JSONEq(t, `[7,"Engineering"]`, string(queryValuesJson))
})
t.Run("custom host vital label missing id is rejected", func(t *testing.T) {
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "custom-vital-no-id",
Criteria: &fleet.HostVitalCriteria{
Vital: new("custom_host_vital"),
Value: new("Engineering"),
},
})
require.Error(t, err)
require.Contains(t, err.Error(), "custom_host_vital_id")
})
t.Run("custom host vital label with unknown id is rejected", func(t *testing.T) {
ds.GetCustomHostVitalsFunc = func(ctx context.Context, ids []uint) ([]fleet.CustomHostVital, error) {
return nil, nil
}
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "custom-vital-bad-id",
Criteria: &fleet.HostVitalCriteria{
Vital: new("custom_host_vital"),
Value: new("Engineering"),
CustomHostVitalID: new(uint(999)),
},
})
require.Error(t, err)
require.Contains(t, err.Error(), "does not exist")
})
}
func TestNewLabelFieldValidation(t *testing.T) {
ds := new(mock.Store)
svc, ctx := newTestService(t, ds, nil, nil)
ctx = viewer.NewContext(ctx, viewer.Viewer{User: &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)}})
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
lbl.ID = 1
return lbl, nil
}
// Manual label (no query) with platform should be rejected
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{
Name: "manual_with_platform",
Platform: "darwin",
})
require.Error(t, err)
require.ErrorContains(t, err, "declared as manual but contains a platform")
// Host_vitals label with platform should be rejected
_, _, err = svc.NewLabel(ctx, fleet.LabelPayload{
Name: "vitals_with_platform",
Platform: "darwin",
Criteria: &fleet.HostVitalCriteria{
Vital: ptr.String("end_user_idp_group"),
Value: ptr.String("admin"),
},
})
require.Error(t, err)
require.ErrorContains(t, err, "declared as host_vitals but contains a platform")
// Dynamic label with invalid platform should be rejected
_, _, err = svc.NewLabel(ctx, fleet.LabelPayload{
Name: "dynamic_bad_platform",
Query: "SELECT 1",
Platform: "invalidplatform",
})
require.Error(t, err)
require.ErrorContains(t, err, "invalid platform")
// Dynamic label with valid platform should succeed
_, _, err = svc.NewLabel(ctx, fleet.LabelPayload{
Name: "dynamic_good_platform",
Query: "SELECT 1",
Platform: "darwin",
})
require.NoError(t, err)
}
func TestLabelActivities(t *testing.T) {
ds := new(mock.Store)
opts := &TestServerOpts{}
svc, ctx := newTestService(t, ds, nil, nil, opts)
user := &fleet.User{ID: 7, GlobalRole: ptr.String(fleet.RoleAdmin)}
ctx = viewer.NewContext(ctx, viewer.Viewer{User: user})
var activities []activity_api.ActivityDetails
opts.ActivityMock.NewActivityFunc = func(_ context.Context, _ *activity_api.User, a activity_api.ActivityDetails) error {
activities = append(activities, a)
return nil
}
const teamID = uint(42)
teamName := "Workstations"
ds.TeamLiteFunc = func(ctx context.Context, tid uint) (*fleet.TeamLite, error) {
require.Equal(t, teamID, tid)
return &fleet.TeamLite{ID: tid, Name: teamName}, nil
}
t.Run("create global label via UI emits created_label", func(t *testing.T) {
activities = activities[:0]
ds.NewLabelFunc = func(ctx context.Context, lbl *fleet.Label, opts ...fleet.OptionalArg) (*fleet.Label, error) {
lbl.ID = 100
return lbl, nil
}
_, _, err := svc.NewLabel(ctx, fleet.LabelPayload{Name: "global1", Query: "SELECT 1"})
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeCreatedLabel)
require.True(t, ok, "expected ActivityTypeCreatedLabel, got %T", activities[0])
require.Equal(t, uint(100), got.ID)
require.Equal(t, "global1", got.Name)
require.Nil(t, got.FleetID)
require.Nil(t, got.FleetName)
})
t.Run("modify label via UI emits edited_label with team info", func(t *testing.T) {
activities = activities[:0]
labelID := uint(101)
ds.LabelFunc = func(ctx context.Context, lid uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{
Label: fleet.Label{
ID: lid,
Name: "edited",
LabelMembershipType: fleet.LabelMembershipTypeDynamic,
},
}, nil, nil
}
ds.SaveLabelFunc = func(ctx context.Context, lbl *fleet.Label, hostIDs []uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{
Label: fleet.Label{ID: lbl.ID, Name: lbl.Name, TeamID: ptr.Uint(teamID)},
TeamName: &teamName,
}, nil, nil
}
_, _, err := svc.ModifyLabel(ctx, labelID, fleet.ModifyLabelPayload{Description: ptr.String("new")})
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeEditedLabel)
require.True(t, ok, "expected ActivityTypeEditedLabel, got %T", activities[0])
require.Equal(t, labelID, got.ID)
require.Equal(t, "edited", got.Name)
require.NotNil(t, got.FleetID)
require.Equal(t, teamID, *got.FleetID)
require.NotNil(t, got.FleetName)
require.Equal(t, teamName, *got.FleetName)
})
t.Run("delete label by name via UI emits deleted_label", func(t *testing.T) {
activities = activities[:0]
ds.LabelByNameFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) (*fleet.Label, error) {
return &fleet.Label{ID: 200, Name: name}, nil
}
ds.DeleteLabelFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) error {
return nil
}
err := svc.DeleteLabel(ctx, "to-remove")
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeDeletedLabel)
require.True(t, ok, "expected ActivityTypeDeletedLabel, got %T", activities[0])
require.Equal(t, uint(200), got.ID)
require.Equal(t, "to-remove", got.Name)
require.Nil(t, got.FleetID)
})
t.Run("delete team label by name resolves team name", func(t *testing.T) {
activities = activities[:0]
ds.LabelByNameFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) (*fleet.Label, error) {
return &fleet.Label{ID: 201, Name: name, TeamID: ptr.Uint(teamID)}, nil
}
ds.DeleteLabelFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) error {
return nil
}
err := svc.DeleteLabel(ctx, "team-label")
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeDeletedLabel)
require.True(t, ok)
require.NotNil(t, got.FleetID)
require.Equal(t, teamID, *got.FleetID)
require.NotNil(t, got.FleetName)
require.Equal(t, teamName, *got.FleetName)
})
t.Run("delete team label aborts before delete when team lookup fails", func(t *testing.T) {
activities = activities[:0]
ds.LabelByNameFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) (*fleet.Label, error) {
return &fleet.Label{ID: 250, Name: name, TeamID: ptr.Uint(teamID)}, nil
}
var deleteCalled bool
ds.DeleteLabelFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) error {
deleteCalled = true
return nil
}
// Override TeamLite for this subtest only.
prevTeamLite := ds.TeamLiteFunc
ds.TeamLiteFunc = func(ctx context.Context, tid uint) (*fleet.TeamLite, error) {
return nil, assert.AnError
}
t.Cleanup(func() { ds.TeamLiteFunc = prevTeamLite })
err := svc.DeleteLabel(ctx, "team-label-fail")
require.Error(t, err)
require.False(t, deleteCalled, "label must not be deleted when team lookup fails")
require.Empty(t, activities, "no activity should be emitted when delete is skipped")
})
t.Run("delete label by ID via UI emits deleted_label", func(t *testing.T) {
activities = activities[:0]
ds.LabelFunc = func(ctx context.Context, lid uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{
Label: fleet.Label{ID: lid, Name: "delete-by-id", TeamID: ptr.Uint(teamID)},
TeamName: &teamName,
}, nil, nil
}
ds.DeleteLabelFunc = func(ctx context.Context, name string, filter fleet.TeamFilter) error {
return nil
}
err := svc.DeleteLabelByID(ctx, 300)
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeDeletedLabel)
require.True(t, ok)
require.Equal(t, uint(300), got.ID)
require.Equal(t, "delete-by-id", got.Name)
require.NotNil(t, got.FleetID)
require.Equal(t, teamID, *got.FleetID)
require.NotNil(t, got.FleetName)
require.Equal(t, teamName, *got.FleetName)
})
t.Run("apply specs emits per-label created/edited/no-op", func(t *testing.T) {
activities = activities[:0]
// Pre-existing label "edited-spec" has the OLD description; "noop-spec"
// matches the spec exactly so it should produce no activity. After
// apply, "new-spec" exists with its newly assigned ID.
var lookupCalls int
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
lookupCalls++
result := map[string]*fleet.Label{
"edited-spec": {ID: 401, Name: "edited-spec", Description: "old", Query: "SELECT 1", LabelMembershipType: fleet.LabelMembershipTypeDynamic},
"noop-spec": {ID: 402, Name: "noop-spec", Description: "same", Query: "SELECT 2", LabelMembershipType: fleet.LabelMembershipTypeDynamic},
}
if lookupCalls > 1 { // post-apply: new-spec now exists; edited-spec has new desc
result["new-spec"] = &fleet.Label{ID: 403, Name: "new-spec", Description: "fresh", Query: "SELECT 3", LabelMembershipType: fleet.LabelMembershipTypeDynamic}
result["edited-spec"] = &fleet.Label{ID: 401, Name: "edited-spec", Description: "new", Query: "SELECT 1", LabelMembershipType: fleet.LabelMembershipTypeDynamic}
}
return result, nil
}
ds.SetAsideLabelsFunc = func(ctx context.Context, notOnTeamID *uint, names []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorID *uint) error {
return nil
}
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{Name: "new-spec", Description: "fresh", Query: "SELECT 3", LabelMembershipType: fleet.LabelMembershipTypeDynamic},
{Name: "edited-spec", Description: "new", Query: "SELECT 1", LabelMembershipType: fleet.LabelMembershipTypeDynamic},
{Name: "noop-spec", Description: "same", Query: "SELECT 2", LabelMembershipType: fleet.LabelMembershipTypeDynamic},
}, nil, nil)
require.NoError(t, err)
// Two activities: one created, one edited; the no-op spec emits nothing.
require.Len(t, activities, 2)
var sawCreate, sawEdit bool
for _, a := range activities {
switch v := a.(type) {
case fleet.ActivityTypeCreatedLabel:
require.Equal(t, "new-spec", v.Name)
sawCreate = true
case fleet.ActivityTypeEditedLabel:
require.Equal(t, "edited-spec", v.Name)
require.Equal(t, uint(401), v.ID)
sawEdit = true
default:
t.Fatalf("unexpected activity type %T", a)
}
}
require.True(t, sawCreate, "expected created_label for new-spec")
require.True(t, sawEdit, "expected edited_label for edited-spec")
})
t.Run("apply specs detects platform-only change", func(t *testing.T) {
activities = activities[:0]
// Existing label "platform-spec" has Platform="darwin"; spec sets it to
// "linux" with all other fields unchanged.
var lookupCalls int
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
lookupCalls++
return map[string]*fleet.Label{
"platform-spec": {ID: 410, Name: "platform-spec", Platform: "darwin", LabelMembershipType: fleet.LabelMembershipTypeDynamic, Query: "SELECT 1"},
}, nil
}
ds.SetAsideLabelsFunc = func(ctx context.Context, notOnTeamID *uint, names []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorID *uint) error {
return nil
}
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{Name: "platform-spec", Platform: "windows", LabelMembershipType: fleet.LabelMembershipTypeDynamic, Query: "SELECT 1"},
}, nil, nil)
require.NoError(t, err)
require.Len(t, activities, 1, "platform change should emit edited_label")
got, ok := activities[0].(fleet.ActivityTypeEditedLabel)
require.True(t, ok, "expected edited_label, got %T", activities[0])
require.Equal(t, "platform-spec", got.Name)
})
t.Run("apply specs detects manual-label host membership change", func(t *testing.T) {
activities = activities[:0]
// Existing manual label "manual-spec" has identical fields to the spec
// (so field comparison says no-op), but its host membership will change
// from {1,2} to {1,3} after apply.
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{
"manual-spec": {ID: 501, Name: "manual-spec", LabelMembershipType: fleet.LabelMembershipTypeManual},
}, nil
}
var membershipCalls int
ds.LabelMembershipHostIDsFunc = func(ctx context.Context, labelID uint) ([]uint, error) {
membershipCalls++
if membershipCalls == 1 { // before apply
return []uint{1, 2}, nil
}
return []uint{1, 3}, nil // after apply
}
ds.SetAsideLabelsFunc = func(ctx context.Context, notOnTeamID *uint, names []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorID *uint) error {
return nil
}
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{Name: "manual-spec", LabelMembershipType: fleet.LabelMembershipTypeManual, Hosts: []string{"host1", "host3"}},
}, nil, nil)
require.NoError(t, err)
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeEditedLabel)
require.True(t, ok, "expected ActivityTypeEditedLabel for host membership change, got %T", activities[0])
require.Equal(t, "manual-spec", got.Name)
})
t.Run("apply specs treats manual-label host no-op as no-op", func(t *testing.T) {
activities = activities[:0]
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{
"manual-spec": {ID: 502, Name: "manual-spec", LabelMembershipType: fleet.LabelMembershipTypeManual},
}, nil
}
ds.LabelMembershipHostIDsFunc = func(ctx context.Context, labelID uint) ([]uint, error) {
return []uint{1, 2}, nil
}
ds.SetAsideLabelsFunc = func(ctx context.Context, notOnTeamID *uint, names []string, user fleet.User) error {
return nil
}
ds.ApplyLabelSpecsWithAuthorFunc = func(ctx context.Context, specs []*fleet.LabelSpec, authorID *uint) error {
return nil
}
err := svc.ApplyLabelSpecs(ctx, []*fleet.LabelSpec{
{Name: "manual-spec", LabelMembershipType: fleet.LabelMembershipTypeManual, Hosts: []string{"host1", "host2"}},
}, nil, nil)
require.NoError(t, err)
require.Empty(t, activities, "expected no activity for manual-label no-op")
})
t.Run("AddLabelsToHost emits edited_label per requested label", func(t *testing.T) {
activities = activities[:0]
const hostID = uint(7000)
const targetTeamID = uint(42)
host := &fleet.Host{ID: hostID, TeamID: ptr.Uint(targetTeamID), Platform: "darwin"}
ds.HostLiteFunc = func(ctx context.Context, id uint) (*fleet.Host, error) {
require.Equal(t, hostID, id)
return host, nil
}
ds.LabelIDsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]uint, error) {
return map[string]uint{"global-manual": 600, "team-manual": 601}, nil
}
ds.LabelFunc = func(ctx context.Context, lid uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
lbl := fleet.Label{ID: lid, LabelMembershipType: fleet.LabelMembershipTypeManual}
if lid == 601 {
lbl.TeamID = ptr.Uint(targetTeamID)
}
return &fleet.LabelWithTeamName{Label: lbl}, nil, nil
}
ds.AddLabelsToHostFunc = func(ctx context.Context, h uint, ids []uint) error {
require.Equal(t, hostID, h)
require.ElementsMatch(t, []uint{600, 601}, ids)
return nil
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
require.NotNil(t, filter.TeamID)
require.Equal(t, targetTeamID, *filter.TeamID)
return map[string]*fleet.Label{
"global-manual": {ID: 600, Name: "global-manual"},
"team-manual": {ID: 601, Name: "team-manual", TeamID: ptr.Uint(targetTeamID)},
}, nil
}
require.NoError(t, svc.AddLabelsToHost(ctx, hostID, []string{"global-manual", "team-manual"}))
require.Len(t, activities, 2)
byName := map[string]fleet.ActivityTypeEditedLabel{}
for _, a := range activities {
e, ok := a.(fleet.ActivityTypeEditedLabel)
require.True(t, ok, "expected edited_label, got %T", a)
byName[e.Name] = e
}
require.Nil(t, byName["global-manual"].FleetID)
require.NotNil(t, byName["team-manual"].FleetID)
require.Equal(t, targetTeamID, *byName["team-manual"].FleetID)
require.NotNil(t, byName["team-manual"].FleetName)
require.Equal(t, teamName, *byName["team-manual"].FleetName)
})
t.Run("AddLabelsToHost dedupes label names in activities", func(t *testing.T) {
activities = activities[:0]
const hostID = uint(7100)
host := &fleet.Host{ID: hostID, Platform: "darwin"}
ds.HostLiteFunc = func(ctx context.Context, id uint) (*fleet.Host, error) {
return host, nil
}
ds.LabelIDsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]uint, error) {
require.Len(t, names, 1, "duplicates should be removed before validation")
require.Equal(t, "dup-label", names[0])
return map[string]uint{"dup-label": 800}, nil
}
ds.LabelFunc = func(ctx context.Context, lid uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{Label: fleet.Label{ID: lid, LabelMembershipType: fleet.LabelMembershipTypeManual}}, nil, nil
}
ds.AddLabelsToHostFunc = func(ctx context.Context, h uint, ids []uint) error {
require.Equal(t, []uint{800}, ids)
return nil
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
require.Equal(t, []string{"dup-label"}, names, "duplicates should be removed before activity emission")
return map[string]*fleet.Label{"dup-label": {ID: 800, Name: "dup-label"}}, nil
}
require.NoError(t, svc.AddLabelsToHost(ctx, hostID, []string{"dup-label", "dup-label", "dup-label"}))
require.Len(t, activities, 1, "duplicate label names must produce a single activity")
got, ok := activities[0].(fleet.ActivityTypeEditedLabel)
require.True(t, ok)
require.Equal(t, "dup-label", got.Name)
})
t.Run("RemoveLabelsFromHost emits edited_label", func(t *testing.T) {
activities = activities[:0]
const hostID = uint(7001)
host := &fleet.Host{ID: hostID, Platform: "darwin"} // no team
ds.HostLiteFunc = func(ctx context.Context, id uint) (*fleet.Host, error) {
return host, nil
}
ds.LabelIDsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]uint, error) {
return map[string]uint{"global-manual": 700}, nil
}
ds.LabelFunc = func(ctx context.Context, lid uint, filter fleet.TeamFilter) (*fleet.LabelWithTeamName, []uint, error) {
return &fleet.LabelWithTeamName{Label: fleet.Label{ID: lid, LabelMembershipType: fleet.LabelMembershipTypeManual}}, nil, nil
}
ds.RemoveLabelsFromHostFunc = func(ctx context.Context, h uint, ids []uint) error {
require.Equal(t, hostID, h)
require.Equal(t, []uint{700}, ids)
return nil
}
ds.LabelsByNameFunc = func(ctx context.Context, names []string, filter fleet.TeamFilter) (map[string]*fleet.Label, error) {
return map[string]*fleet.Label{
"global-manual": {ID: 700, Name: "global-manual"},
}, nil
}
require.NoError(t, svc.RemoveLabelsFromHost(ctx, hostID, []string{"global-manual"}))
require.Len(t, activities, 1)
got, ok := activities[0].(fleet.ActivityTypeEditedLabel)
require.True(t, ok)
require.Equal(t, "global-manual", got.Name)
require.Nil(t, got.FleetID)
})
}