BadRequest when no payloads present; BadRequest for invalid payload types (#18169)

## Addresses #17157 
![Screenshot 2024-04-09 at 4 53
22 PM](https://github.com/fleetdm/fleet/assets/61553566/a6a57f55-275f-4a06-89e7-085262d2672c)

- [x] Changes file added for user-visible changes in `changes/`
- [x] Added/updated tests
- [x] Manual QA for all new/changed functionality

---------

Co-authored-by: Jacob Shandling <jacob@fleetdm.com>
This commit is contained in:
Jacob Shandling
2024-04-10 10:55:38 -07:00
committed by GitHub
co-authored by Jacob Shandling
parent 21d1d90e3c
commit dfe51474cd
3 changed files with 24 additions and 1 deletions
+3
View File
@@ -0,0 +1,3 @@
- Fix a bug where the translate API returned "forbidden" instead of "bad request" for an empty JSON body.
- Fixed an uncaught bug where "forbidden" would be returned for invalid payload type, which should
also be a bad request.
+5
View File
@@ -690,6 +690,11 @@ func (s *integrationTestSuite) TestTranslator() {
require.Len(t, payload.List, 1)
assert.Equal(t, s.users[payload.List[0].Payload.Identifier].ID, payload.List[0].Payload.ID)
// empty body
s.DoJSON("POST", "/api/latest/fleet/translate", &translatorRequest{}, http.StatusBadRequest, &payload)
s.DoJSON("POST", "/api/latest/fleet/translate", &translatorRequest{List: []fleet.TranslatePayload{{Type: "notavalidtype", Payload: fleet.StringIdentifierToIDPayload{}}}}, http.StatusBadRequest, &payload)
}
func (s *integrationTestSuite) TestVulnerableSoftware() {
+16 -1
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"fmt"
"github.com/fleetdm/fleet/v4/server/fleet"
)
@@ -61,6 +62,12 @@ func translateHostToID(ctx context.Context, ds fleet.Datastore, identifier strin
}
func (svc *Service) Translate(ctx context.Context, payloads []fleet.TranslatePayload) ([]fleet.TranslatePayload, error) {
if len(payloads) == 0 {
// skip auth since there is no case in which this request will make sense with no payloads
svc.authz.SkipAuthorization(ctx)
return nil, badRequest("payloads must not be empty")
}
var finalPayload []fleet.TranslatePayload
for _, payload := range payloads {
@@ -88,7 +95,15 @@ func (svc *Service) Translate(ctx context.Context, payloads []fleet.TranslatePay
}
translateFunc = translateHostToID
default:
return nil, fleet.NewErrorf(fleet.ErrNoUnknownTranslate, "Type %s is unknown.", payload.Type)
// if no supported payload type, this is bad regardless of authorization
svc.authz.SkipAuthorization(ctx)
return nil, badRequestErr(
fmt.Sprintf("Type %s is unknown. ", payload.Type),
fleet.NewErrorf(
fleet.ErrNoUnknownTranslate,
"Type %s is unknown.",
payload.Type),
)
}
id, err := translateFunc(ctx, svc.ds, payload.Payload.Identifier)