diff --git a/changes/bug-2790-return-proper-status-code b/changes/bug-2790-return-proper-status-code new file mode 100644 index 0000000000..61c1aaa0be --- /dev/null +++ b/changes/bug-2790-return-proper-status-code @@ -0,0 +1 @@ +- When creating a PolicySpec, return the proper HTTP status code if the Team is not found. \ No newline at end of file diff --git a/server/service/global_policies.go b/server/service/global_policies.go index d2582d1013..967d6e26b6 100644 --- a/server/service/global_policies.go +++ b/server/service/global_policies.go @@ -2,6 +2,7 @@ package service import ( "context" + "database/sql" "errors" "fmt" @@ -439,6 +440,13 @@ func (svc *Service) checkPolicySpecAuthorization(ctx context.Context, policies [ if policy.Team != "" { team, err := svc.ds.TeamByName(ctx, policy.Team) if err != nil { + // This is so that the proper HTTP status code is returned + svc.authz.SkipAuthorization(ctx) + + if errors.Is(err, sql.ErrNoRows) { + return newNotFoundError() + } + return ctxerr.Wrap(ctx, err, "getting team by name") } if err := svc.authz.Authorize(ctx, &fleet.Policy{ diff --git a/server/service/global_policies_test.go b/server/service/global_policies_test.go index 7ef07dab65..4fb9e7778c 100644 --- a/server/service/global_policies_test.go +++ b/server/service/global_policies_test.go @@ -2,6 +2,7 @@ package service import ( "context" + "database/sql" "testing" "github.com/fleetdm/fleet/v4/server/contexts/viewer" @@ -11,6 +12,31 @@ import ( "github.com/stretchr/testify/require" ) +func TestCheckPolicySpecAuthorization(t *testing.T) { + t.Run("when team not found", func(t *testing.T) { + ds := new(mock.Store) + ds.TeamByNameFunc = func(ctx context.Context, name string) (*fleet.Team, error) { + return nil, sql.ErrNoRows + } + + svc, ctx := newTestService(t, ds, nil, nil) + + req := []*fleet.PolicySpec{ + { + Team: "some_team", + }, + } + + user := &fleet.User{GlobalRole: ptr.String(fleet.RoleAdmin)} + ctx = viewer.NewContext(ctx, viewer.Viewer{User: user}) + + actual := svc.ApplyPolicySpecs(ctx, req) + var expected *notFoundError + + require.ErrorAs(t, actual, &expected) + }) +} + func TestGlobalPoliciesAuth(t *testing.T) { ds := new(mock.Store) svc, ctx := newTestService(t, ds, nil, nil)