From 71c9547de5a914061ea863da874cce3f8fb1640e Mon Sep 17 00:00:00 2001 From: Ivan Fraixedes Date: Tue, 3 Oct 2023 14:34:03 +0200 Subject: [PATCH] private/apigen: Don't allow certain types for Request/Response We cannot map certain types to TypeScript, hence we verify them in the Endpoint.Validate method. Even some types could be somehow mapped, we don't want to add more complexity or allow types that don't make sense to be for a request or response. Change-Id: I51ecee286e637b1160e967d77f9ce6c7403ddfdc --- private/apigen/endpoint.go | 30 ++++++++++++++++++++++++++++++ private/apigen/endpoint_test.go | 23 +++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/private/apigen/endpoint.go b/private/apigen/endpoint.go index c4b58387be63..3798a4e57808 100644 --- a/private/apigen/endpoint.go +++ b/private/apigen/endpoint.go @@ -81,6 +81,36 @@ func (e *Endpoint) Validate() error { return errsEndpoint.New("TypeScriptName doesn't match the regular expression %q", typeScriptNameRegExp) } + if e.Request != nil { + switch k := reflect.TypeOf(e.Request).Kind(); k { + case reflect.Invalid, + reflect.Complex64, + reflect.Complex128, + reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Pointer, + reflect.UnsafePointer: + return errsEndpoint.New("Request cannot be of a type %q", k) + } + } + + if e.Response != nil { + switch k := reflect.TypeOf(e.Response).Kind(); k { + case reflect.Invalid, + reflect.Complex64, + reflect.Complex128, + reflect.Chan, + reflect.Func, + reflect.Interface, + reflect.Map, + reflect.Pointer, + reflect.UnsafePointer: + return errsEndpoint.New("Response cannot be of a type %q", k) + } + } + return nil } diff --git a/private/apigen/endpoint_test.go b/private/apigen/endpoint_test.go index 5f51c2865e1b..88a95aeba5ae 100644 --- a/private/apigen/endpoint_test.go +++ b/private/apigen/endpoint_test.go @@ -4,8 +4,10 @@ package apigen import ( + "fmt" "math/rand" "net/http" + "reflect" "strconv" "testing" @@ -104,6 +106,27 @@ func TestEndpoint_Validate(t *testing.T) { }, errMsg: "TypeScriptName doesn't match the regular expression", }, + { + testName: "invalid Request type", + endpointFn: func() *Endpoint { + request := &struct { + Name string `json:"name"` + }{} + e := validEndpoint + e.Request = request + return &e + }, + errMsg: fmt.Sprintf("Request cannot be of a type %q", reflect.Pointer), + }, + { + testName: "invalid Response type", + endpointFn: func() *Endpoint { + e := validEndpoint + e.Response = map[string]string{} + return &e + }, + errMsg: fmt.Sprintf("Response cannot be of a type %q", reflect.Map), + }, } for _, tc := range tcases {