Allow team maintainers to bulk delete hosts for teams they belong (#2399)

This commit is contained in:
Tomas Touceda 2021-10-06 12:58:01 -03:00 committed by GitHub
parent ea3f0f127f
commit 1b611012df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 1 deletions

View file

@ -4,6 +4,7 @@ import (
"context"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/pkg/errors"
)
/////////////////////////////////////////////////////////////////////////////////
@ -43,7 +44,7 @@ func deleteHostsEndpoint(ctx context.Context, request interface{}, svc fleet.Ser
}
func (svc Service) DeleteHosts(ctx context.Context, ids []uint, opts fleet.HostListOptions, lid *uint) error {
if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionWrite); err != nil {
if err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {
return err
}
@ -52,6 +53,10 @@ func (svc Service) DeleteHosts(ctx context.Context, ids []uint, opts fleet.HostL
}
if len(ids) > 0 {
err := svc.checkWriteForHostIDs(ctx, ids)
if err != nil {
return err
}
return svc.ds.DeleteHosts(ctx, ids)
}
@ -63,5 +68,25 @@ func (svc Service) DeleteHosts(ctx context.Context, ids []uint, opts fleet.HostL
if len(hostIDs) == 0 {
return nil
}
err = svc.checkWriteForHostIDs(ctx, hostIDs)
if err != nil {
return err
}
return svc.ds.DeleteHosts(ctx, hostIDs)
}
func (svc Service) checkWriteForHostIDs(ctx context.Context, ids []uint) error {
for _, id := range ids {
host, err := svc.ds.Host(ctx, id)
if err != nil {
return errors.Wrap(err, "get host for delete")
}
// Authorize again with team loaded now that we have team_id
if err := svc.authz.Authorize(ctx, host, fleet.ActionWrite); err != nil {
return err
}
}
return nil
}

View file

@ -252,6 +252,9 @@ func TestHostAuth(t *testing.T) {
ds.SaveHostFunc = func(ctx context.Context, host *fleet.Host) error {
return nil
}
ds.DeleteHostsFunc = func(ctx context.Context, ids []uint) error {
return nil
}
var testCases = []struct {
name string
@ -340,6 +343,12 @@ func TestHostAuth(t *testing.T) {
err = svc.DeleteHost(ctx, 2)
checkAuthErr(t, tt.shouldFailGlobalWrite, err)
err = svc.DeleteHosts(ctx, []uint{1}, fleet.HostListOptions{}, nil)
checkAuthErr(t, tt.shouldFailTeamWrite, err)
err = svc.DeleteHosts(ctx, []uint{2}, fleet.HostListOptions{}, nil)
checkAuthErr(t, tt.shouldFailGlobalWrite, err)
err = svc.AddHostsToTeam(ctx, ptr.Uint(1), []uint{1})
checkAuthErr(t, tt.shouldFailTeamWrite, err)