feat(chromium): add validation of 'emulatedMediaType' form field at the handler level

This commit is contained in:
Julien Neuhart
2021-11-24 16:32:17 +01:00
parent 415e2ff265
commit 14f94b1566
2 changed files with 59 additions and 26 deletions

View File

@@ -62,7 +62,21 @@ func FormDataChromiumPDFOptions(ctx *api.Context) (*api.FormData, Options) {
return nil
}).
String("emulatedMediaType", &emulatedMediaType, defaultOptions.EmulatedMediaType).
Custom("emulatedMediaType", func(value string) error {
if value == "" {
emulatedMediaType = defaultOptions.EmulatedMediaType
return nil
}
if value != "screen" && value != "print" {
return fmt.Errorf("wrong value, expected either 'screen', 'print' or empty")
}
emulatedMediaType = value
return nil
}).
Bool("landscape", &landscape, defaultOptions.Landscape).
Bool("printBackground", &printBackground, defaultOptions.PrintBackground).
Float64("scale", &scale, defaultOptions.Scale).
@@ -493,16 +507,6 @@ func convertURL(ctx *api.Context, chromium API, engine gotenberg.PDFEngine, URL,
)
}
if errors.Is(err, ErrInvalidEmulatedMediaType) {
return api.WrapError(
fmt.Errorf("convert to PDF: %w", err),
api.NewSentinelHTTPError(
http.StatusBadRequest,
fmt.Sprintf("The media type '%s' (emulatedMediaType) is invalid: allowed values are 'screen' or 'print'", options.EmulatedMediaType),
),
)
}
if errors.Is(err, ErrInvalidEvaluationExpression) {
if options.WaitForExpression == "" {
// We do not expect the 'waitWindowStatus' form field to return

View File

@@ -54,6 +54,50 @@ func TestFormDataChromiumPDFOptions(t *testing.T) {
"foo": "bar",
}
return options
}(),
},
{
ctx: func() *api.MockContext {
ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetValues(map[string][]string{
"extraHttpHeaders": {
"foo",
},
})
return ctx
}(),
options: DefaultOptions(),
},
{
ctx: func() *api.MockContext {
ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetValues(map[string][]string{
"emulatedMediaType": {
"foo",
},
})
return ctx
}(),
options: DefaultOptions(),
},
{
ctx: func() *api.MockContext {
ctx := &api.MockContext{Context: &api.Context{}}
ctx.SetValues(map[string][]string{
"emulatedMediaType": {
"screen",
},
})
return ctx
}(),
options: func() Options {
options := DefaultOptions()
options.EmulatedMediaType = "screen"
return options
}(),
},
@@ -765,21 +809,6 @@ func TestConvertURL(t *testing.T) {
expectHTTPErr: true,
expectHTTPStatus: http.StatusForbidden,
},
{
ctx: &api.MockContext{Context: &api.Context{}},
api: func() API {
chromiumAPI := struct{ ProtoAPI }{}
chromiumAPI.pdf = func(_ context.Context, _ *zap.Logger, _, _ string, _ Options) error {
return ErrInvalidEmulatedMediaType
}
return chromiumAPI
}(),
options: DefaultOptions(),
expectErr: true,
expectHTTPErr: true,
expectHTTPStatus: http.StatusBadRequest,
},
{
ctx: &api.MockContext{Context: &api.Context{}},
api: func() API {