From 8176f8506cb912f75e04f25d58dc367d57b8c7f7 Mon Sep 17 00:00:00 2001 From: Amarjeet Singh Rai Date: Tue, 5 Jul 2022 18:59:22 +0100 Subject: [PATCH 1/3] Match on overridden servers at the path level, fixes #564 --- routers/gorillamux/router.go | 151 +++++++++++++++++------------- routers/gorillamux/router_test.go | 40 ++++++++ 2 files changed, 125 insertions(+), 66 deletions(-) diff --git a/routers/gorillamux/router.go b/routers/gorillamux/router.go index bf551a751..8e34ad39e 100644 --- a/routers/gorillamux/router.go +++ b/routers/gorillamux/router.go @@ -34,6 +34,13 @@ type routeMux struct { varsUpdater varsf } +type srv struct { + schemes []string + host, base string + server *openapi3.Server + varsUpdater varsf +} + var singleVariableMatcher = regexp.MustCompile(`^\{([^{}]+)\}$`) // TODO: Handle/HandlerFunc + ServeHTTP (When there is a match, the route variables can be retrieved calling mux.Vars(request)) @@ -42,78 +49,23 @@ var singleVariableMatcher = regexp.MustCompile(`^\{([^{}]+)\}$`) // Assumes spec is .Validate()d // Note that a variable for the port number MUST have a default value and only this value will match as the port (see issue #367). func NewRouter(doc *openapi3.T) (routers.Router, error) { - type srv struct { - schemes []string - host, base string - server *openapi3.Server - varsUpdater varsf + servers, err := makeServers(doc.Servers) + if err != nil { + return nil, err } - servers := make([]srv, 0, len(doc.Servers)) - for _, server := range doc.Servers { - serverURL := server.URL - if submatch := singleVariableMatcher.FindStringSubmatch(serverURL); submatch != nil { - sVar := submatch[1] - sVal := server.Variables[sVar].Default - serverURL = strings.ReplaceAll(serverURL, "{"+sVar+"}", sVal) - var varsUpdater varsf - if lhs := strings.TrimSuffix(serverURL, server.Variables[sVar].Default); lhs != "" { - varsUpdater = func(vars map[string]string) { vars[sVar] = lhs } - } - servers = append(servers, srv{ - base: server.Variables[sVar].Default, - server: server, - varsUpdater: varsUpdater, - }) - continue - } - - var schemes []string - if strings.Contains(serverURL, "://") { - scheme0 := strings.Split(serverURL, "://")[0] - schemes = permutePart(scheme0, server) - serverURL = strings.Replace(serverURL, scheme0+"://", schemes[0]+"://", 1) - } - // If a variable represents the port "http://domain.tld:{port}/bla" - // then url.Parse() cannot parse "http://domain.tld:`bEncode({port})`/bla" - // and mux is not able to set the {port} variable - // So we just use the default value for this variable. - // See https://github.com/getkin/kin-openapi/issues/367 - var varsUpdater varsf - if lhs := strings.Index(serverURL, ":{"); lhs > 0 { - rest := serverURL[lhs+len(":{"):] - rhs := strings.Index(rest, "}") - portVariable := rest[:rhs] - portValue := server.Variables[portVariable].Default - serverURL = strings.ReplaceAll(serverURL, "{"+portVariable+"}", portValue) - varsUpdater = func(vars map[string]string) { - vars[portVariable] = portValue - } - } - - u, err := url.Parse(bEncode(serverURL)) - if err != nil { - return nil, err - } - path := bDecode(u.EscapedPath()) - if len(path) > 0 && path[len(path)-1] == '/' { - path = path[:len(path)-1] - } - servers = append(servers, srv{ - host: bDecode(u.Host), //u.Hostname()? - base: path, - schemes: schemes, // scheme: []string{scheme0}, TODO: https://github.com/gorilla/mux/issues/624 - server: server, - varsUpdater: varsUpdater, - }) - } - if len(servers) == 0 { - servers = append(servers, srv{}) - } muxRouter := mux.NewRouter().UseEncodedPath() r := &Router{} for _, path := range orderedPaths(doc.Paths) { + servers := servers + pathItem := doc.Paths[path] + if len(pathItem.Servers) > 0 { + servers, err = makeServers(pathItem.Servers) + if err != nil { + return nil, err + } + } operations := pathItem.Operations() methods := make([]string, 0, len(operations)) @@ -177,6 +129,73 @@ func (r *Router) FindRoute(req *http.Request) (*routers.Route, map[string]string return nil, nil, routers.ErrPathNotFound } +func makeServers(in openapi3.Servers) ([]srv, error) { + servers := make([]srv, 0, len(in)) + for _, server := range in { + serverURL := server.URL + if submatch := singleVariableMatcher.FindStringSubmatch(serverURL); submatch != nil { + sVar := submatch[1] + sVal := server.Variables[sVar].Default + serverURL = strings.ReplaceAll(serverURL, "{"+sVar+"}", sVal) + var varsUpdater varsf + if lhs := strings.TrimSuffix(serverURL, server.Variables[sVar].Default); lhs != "" { + varsUpdater = func(vars map[string]string) { vars[sVar] = lhs } + } + servers = append(servers, srv{ + base: server.Variables[sVar].Default, + server: server, + varsUpdater: varsUpdater, + }) + continue + } + + var schemes []string + if strings.Contains(serverURL, "://") { + scheme0 := strings.Split(serverURL, "://")[0] + schemes = permutePart(scheme0, server) + serverURL = strings.Replace(serverURL, scheme0+"://", schemes[0]+"://", 1) + } + + // If a variable represents the port "http://domain.tld:{port}/bla" + // then url.Parse() cannot parse "http://domain.tld:`bEncode({port})`/bla" + // and mux is not able to set the {port} variable + // So we just use the default value for this variable. + // See https://github.com/getkin/kin-openapi/issues/367 + var varsUpdater varsf + if lhs := strings.Index(serverURL, ":{"); lhs > 0 { + rest := serverURL[lhs+len(":{"):] + rhs := strings.Index(rest, "}") + portVariable := rest[:rhs] + portValue := server.Variables[portVariable].Default + serverURL = strings.ReplaceAll(serverURL, "{"+portVariable+"}", portValue) + varsUpdater = func(vars map[string]string) { + vars[portVariable] = portValue + } + } + + u, err := url.Parse(bEncode(serverURL)) + if err != nil { + return nil, err + } + path := bDecode(u.EscapedPath()) + if len(path) > 0 && path[len(path)-1] == '/' { + path = path[:len(path)-1] + } + servers = append(servers, srv{ + host: bDecode(u.Host), //u.Hostname()? + base: path, + schemes: schemes, // scheme: []string{scheme0}, TODO: https://github.com/gorilla/mux/issues/624 + server: server, + varsUpdater: varsUpdater, + }) + } + if len(servers) == 0 { + servers = append(servers, srv{}) + } + + return servers, nil +} + func orderedPaths(paths map[string]*openapi3.PathItem) []string { // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md#pathsObject // When matching URLs, concrete (non-templated) paths would be matched diff --git a/routers/gorillamux/router_test.go b/routers/gorillamux/router_test.go index f8800baed..e43255d89 100644 --- a/routers/gorillamux/router_test.go +++ b/routers/gorillamux/router_test.go @@ -254,6 +254,46 @@ func TestServerPath(t *testing.T) { require.NoError(t, err) } +func TestServerOverrideAtPathLevel(t *testing.T) { + helloGET := &openapi3.Operation{Responses: openapi3.NewResponses()} + doc := &openapi3.T{ + OpenAPI: "3.0.0", + Info: &openapi3.Info{ + Title: "rel", + Version: "1", + }, + Servers: openapi3.Servers{ + &openapi3.Server{ + URL: "https://example.com", + }, + }, + Paths: openapi3.Paths{ + "/hello": &openapi3.PathItem{ + Servers: openapi3.Servers{ + &openapi3.Server{ + URL: "https://another.com", + }, + }, + Get: helloGET, + }, + }, + } + err := doc.Validate(context.Background()) + require.NoError(t, err) + router, err := NewRouter(doc) + require.NoError(t, err) + + req, err := http.NewRequest(http.MethodGet, "https://another.com/hello", nil) + require.NoError(t, err) + route, _, err := router.FindRoute(req) + require.Equal(t, "/hello", route.Path) + + req, err = http.NewRequest(http.MethodGet, "https://example.com/hello", nil) + require.NoError(t, err) + route, _, err = router.FindRoute(req) + require.Error(t, err) +} + func TestRelativeURL(t *testing.T) { helloGET := &openapi3.Operation{Responses: openapi3.NewResponses()} doc := &openapi3.T{ From 75696c18c40d7f33c2ca484686a805e44c01a1a7 Mon Sep 17 00:00:00 2001 From: Amarjeet Rai Date: Mon, 1 Aug 2022 16:09:39 +0100 Subject: [PATCH 2/3] Update routers/gorillamux/router.go Co-authored-by: Pierre Fenoll --- routers/gorillamux/router.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/routers/gorillamux/router.go b/routers/gorillamux/router.go index 8e34ad39e..811ba7d16 100644 --- a/routers/gorillamux/router.go +++ b/routers/gorillamux/router.go @@ -61,8 +61,7 @@ func NewRouter(doc *openapi3.T) (routers.Router, error) { pathItem := doc.Paths[path] if len(pathItem.Servers) > 0 { - servers, err = makeServers(pathItem.Servers) - if err != nil { + if servers, err = makeServers(pathItem.Servers); err != nil { return nil, err } } From 4e2561c1577e093e0080b7a94ca99a9d124897ac Mon Sep 17 00:00:00 2001 From: Amarjeet Singh Rai Date: Mon, 1 Aug 2022 16:17:25 +0100 Subject: [PATCH 3/3] check route is nil --- routers/gorillamux/router_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/routers/gorillamux/router_test.go b/routers/gorillamux/router_test.go index e43255d89..104056e18 100644 --- a/routers/gorillamux/router_test.go +++ b/routers/gorillamux/router_test.go @@ -291,6 +291,7 @@ func TestServerOverrideAtPathLevel(t *testing.T) { req, err = http.NewRequest(http.MethodGet, "https://example.com/hello", nil) require.NoError(t, err) route, _, err = router.FindRoute(req) + require.Nil(t, route) require.Error(t, err) }