Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions gateway/route_doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package gateway

import (
"context"
"fmt"
"github.com/viant/datly/repository/contract"
"net/http"
)

// swaggerUITemplate renders a minimal Swagger UI page loaded from a public CDN.
// %s is replaced with the URL of the aggregate OpenAPI spec (JSON).
const swaggerUITemplate = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Datly API</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css">
<style>body { margin: 0; background: #fafafa; }</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js" crossorigin></script>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = function () {
window.ui = SwaggerUIBundle({
url: %q,
dom_id: "#swagger-ui",
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
layout: "StandaloneLayout"
});
};
</script>
</body>
</html>`

// NewOpenAPIDocRoute serves an interactive Swagger UI page that renders the
// aggregate OpenAPI spec located at specURL.
func (r *Router) NewOpenAPIDocRoute(URL string, specURL string) *Route {
page := []byte(fmt.Sprintf(swaggerUITemplate, specURL))
return &Route{
Path: contract.NewPath(http.MethodGet, URL),
Handler: func(ctx context.Context, response http.ResponseWriter, req *http.Request) {
setContentType(response, http.StatusOK, "text/html")
write(response, http.StatusOK, page)
},
Kind: RouteOpenAPIKind,
Config: r.config.Logging,
Version: r.config.Version,
}
}
66 changes: 66 additions & 0 deletions gateway/route_openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package gateway

import (
"context"
"encoding/json"
"github.com/viant/datly/gateway/router/openapi"
"github.com/viant/datly/repository"
"github.com/viant/datly/repository/contract"
"gopkg.in/yaml.v3"
"net/http"
"strings"
)

func (r *Router) NewOpenAPIRoute(URL string, components *repository.Service, providers ...*repository.Provider) *Route {
Expand Down Expand Up @@ -44,3 +46,67 @@ func (r *Router) generateOpenAPI(ctx context.Context, components *repository.Ser

return http.StatusOK, specMarshal
}

// NewOpenAPIAggregateRoute builds a route that serves a single OpenAPI 3.0.1 spec
// covering all supplied (public) providers. It defaults to JSON and can return YAML
// when the request asks for it via ?format=yaml or an Accept header containing yaml.
func (r *Router) NewOpenAPIAggregateRoute(URL string, components *repository.Service, providers ...*repository.Provider) *Route {
return &Route{
Path: contract.NewPath(http.MethodGet, URL),
Providers: providers,
Handler: func(ctx context.Context, response http.ResponseWriter, req *http.Request) {
r.handleOpenAPIAggregate(ctx, components, response, req, providers)
},
Kind: RouteOpenAPIKind,
Config: r.config.Logging,
Version: r.config.Version,
NewMultiRoute: func(routes []*contract.Path) *Route {
return r.NewOpenAPIAggregateRoute("", components, providers...)
},
}
}

func (r *Router) handleOpenAPIAggregate(ctx context.Context, components *repository.Service, res http.ResponseWriter, request *http.Request, providers []*repository.Provider) {
asYAML := wantsYAML(request)
statusCode, content, contentType := r.generateOpenAPIWithFormat(ctx, components, providers, asYAML)
setContentType(res, statusCode, contentType)
write(res, statusCode, content)
}

func (r *Router) generateOpenAPIWithFormat(ctx context.Context, components *repository.Service, providers []*repository.Provider, asYAML bool) (int, []byte, string) {
spec, err := openapi.GenerateOpenAPI3Spec(ctx, components, r.OpenAPIInfo, providers...)
if err != nil {
return http.StatusInternalServerError, []byte(err.Error()), "text/plain"
}

if asYAML {
specMarshal, err := yaml.Marshal(spec)
if err != nil {
return http.StatusInternalServerError, []byte(err.Error()), "text/plain"
}
return http.StatusOK, specMarshal, "text/yaml"
}

specMarshal, err := json.MarshalIndent(spec, "", " ")
if err != nil {
return http.StatusInternalServerError, []byte(err.Error()), "text/plain"
}
return http.StatusOK, specMarshal, "application/json"
}

func wantsYAML(request *http.Request) bool {
if request == nil {
return false
}
switch strings.ToLower(strings.TrimSpace(request.URL.Query().Get("format"))) {
case "yaml", "yml":
return true
case "json":
return false
}
accept := strings.ToLower(request.Header.Get("Accept"))
if strings.Contains(accept, "yaml") {
return true
}
return false
}
71 changes: 71 additions & 0 deletions gateway/route_openapi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package gateway

import (
"net/http"
"net/http/httptest"
"net/url"
"testing"

"github.com/stretchr/testify/require"
)

func TestRouterNewOpenAPIAggregateRoute(t *testing.T) {
router := &Router{config: &Config{}}

route := router.NewOpenAPIAggregateRoute("/v1/api/meta/openapi", nil)

require.NotNil(t, route)
require.Equal(t, "/v1/api/meta/openapi", route.Path.URI)
require.Equal(t, http.MethodGet, route.Path.Method)
require.Equal(t, RouteOpenAPIKind, route.Kind)
require.NotNil(t, route.Handler)
}

func TestRouterNewOpenAPIDocRoute(t *testing.T) {
router := &Router{config: &Config{}}

route := router.NewOpenAPIDocRoute("/v1/api/meta/doc", "/v1/api/meta/openapi")

require.NotNil(t, route)
require.Equal(t, "/v1/api/meta/doc", route.Path.URI)
require.Equal(t, http.MethodGet, route.Path.Method)
require.NotNil(t, route.Handler)

recorder := httptest.NewRecorder()
route.Handler(nil, recorder, nil)

require.Equal(t, http.StatusOK, recorder.Code)
require.Contains(t, recorder.Header().Get("Content-Type"), "text/html")
body := recorder.Body.String()
require.Contains(t, body, "swagger-ui")
require.Contains(t, body, `"/v1/api/meta/openapi"`)
}

func TestWantsYAML(t *testing.T) {
testCases := []struct {
description string
rawQuery string
accept string
expect bool
}{
{description: "default is json", expect: false},
{description: "format=yaml", rawQuery: "format=yaml", expect: true},
{description: "format=yml", rawQuery: "format=yml", expect: true},
{description: "format=json overrides accept", rawQuery: "format=json", accept: "application/yaml", expect: false},
{description: "accept yaml", accept: "application/yaml", expect: true},
{description: "accept json", accept: "application/json", expect: false},
}

for _, testCase := range testCases {
request := &http.Request{
URL: &url.URL{RawQuery: testCase.rawQuery},
Header: http.Header{},
}
if testCase.accept != "" {
request.Header.Set("Accept", testCase.accept)
}
require.Equalf(t, testCase.expect, wantsYAML(request), testCase.description)
}

require.False(t, wantsYAML(nil))
}
13 changes: 13 additions & 0 deletions gateway/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ func NewRouter(ctx context.Context, components *repository.Service, config *Conf
apiKeyMatcher: newApiKeyMatcher(config.APIKeys),
mcpRegistry: mcpRegistry,
logger: logging.New(logging.INFO, nil),
OpenAPIInfo: openapi3.Info{
Title: "Datly API",
Version: config.Version,
},
}
return r, r.init(ctx)
}
Expand Down Expand Up @@ -333,6 +337,7 @@ func (r *Router) newMatcher(ctx context.Context) (*matcher.Matcher, []*contract.

unique := map[string]bool{}
var openAPIs = map[string][]*repository.Provider{}
var allProviders []*repository.Provider
var optionsPaths = map[string][]*path.Path{}
for _, anItem := range container.Items {
for _, aPath := range anItem.Paths {
Expand Down Expand Up @@ -400,6 +405,7 @@ func (r *Router) newMatcher(ctx context.Context) (*matcher.Matcher, []*contract.
routes = append(routes, r.NewViewMetaHandler(r.routeURL(r.config.Meta.ViewURI, aPath.URI), provider))
key := r.routeURL(r.config.Meta.OpenApiURI, aPath.URI)
openAPIs[key] = append(openAPIs[key], provider)
allProviders = append(allProviders, provider)

if !unique[aPath.URI] {
unique[aPath.URI] = true
Expand All @@ -426,6 +432,13 @@ func (r *Router) newMatcher(ctx context.Context) (*matcher.Matcher, []*contract.
routes = append(routes, r.NewOpenAPIRoute(key, r.repository, providers...))
}

if strings.TrimSpace(r.config.Meta.OpenApiURI) != "" {
routes = append(routes, r.NewOpenAPIAggregateRoute(r.config.Meta.OpenApiURI, r.repository, allProviders...))
if strings.TrimSpace(r.config.Meta.DocURI) != "" {
routes = append(routes, r.NewOpenAPIDocRoute(r.config.Meta.DocURI, r.config.Meta.OpenApiURI))
}
}

for uri, paths := range optionsPaths {
routes = append(routes, r.NewOptionsRoute(uri, paths))

Expand Down
11 changes: 9 additions & 2 deletions gateway/router/openapi/generator_operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
)

func (g *generator) generateOperation(ctx context.Context, component *ComponentSchema) (*openapi.Operation, error) {
g.authSchemeName = ""

body, err := g.requestBody(ctx, component)
if err != nil {
return nil, err
Expand All @@ -25,11 +27,16 @@ func (g *generator) generateOperation(ctx context.Context, component *ComponentS
return nil, err
}

return &openapi.Operation{
operation := &openapi.Operation{
Parameters: dedupe(parameters),
RequestBody: body,
Responses: responses,
}, nil
}
if g.authSchemeName != "" {
security := openapi.SecurityRequirements{openapi.SecurityRequirement{g.authSchemeName: []string{}}}
operation.Security = &security
}
return operation, nil
}

func (g *generator) operationParameters(ctx context.Context, component *ComponentSchema) ([]*openapi.Parameter, error) {
Expand Down
54 changes: 53 additions & 1 deletion gateway/router/openapi/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,58 @@ func TestGeneratorHelpersMore_Table(t *testing.T) {
}
})

t.Run("path parameter is emitted and required", func(t *testing.T) {
g := &generator{
_parametersIndex: map[string]*openapi3.Parameter{},
commonParameters: map[string]*openapi3.Parameter{},
}
comp := newTestComponent(t)
comp.View = &view.View{Template: &view.Template{}, Selector: &view.Config{}}
cSchema := &ComponentSchema{component: comp, schemas: NewContainer()}
param := &state.Parameter{Name: "ID", In: &state.Location{Kind: state.KindPath, Name: "id"}, Schema: state.NewSchema(reflect.TypeOf(1))}

converted, ok, err := g.convertParam(context.Background(), cSchema, param, "")
if err != nil || !ok || len(converted) != 1 {
t.Fatalf("unexpected convert result: ok=%v err=%v n=%d", ok, err, len(converted))
}
if converted[0].In != "path" {
t.Fatalf("expected in=path, got %q", converted[0].In)
}
if converted[0].Name != "id" {
t.Fatalf("expected name=id, got %q", converted[0].Name)
}
if !converted[0].Required {
t.Fatalf("expected path parameter to be required")
}
})

t.Run("authorization header becomes security scheme", func(t *testing.T) {
g := &generator{
_parametersIndex: map[string]*openapi3.Parameter{},
commonParameters: map[string]*openapi3.Parameter{},
securitySchemes: map[string]*openapi3.SecurityScheme{},
}
comp := newTestComponent(t)
comp.View = &view.View{Template: &view.Template{}, Selector: &view.Config{}}
cSchema := &ComponentSchema{component: comp, schemas: NewContainer()}
param := &state.Parameter{Name: "Jwt", In: &state.Location{Kind: state.KindHeader, Name: "Authorization"}, Schema: state.NewSchema(reflect.TypeOf(""))}

converted, ok, err := g.convertParam(context.Background(), cSchema, param, "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if ok || len(converted) != 0 {
t.Fatalf("expected Authorization header to be skipped as a parameter, got ok=%v n=%d", ok, len(converted))
}
if g.authSchemeName != bearerAuthSchemeName {
t.Fatalf("expected auth scheme %q, got %q", bearerAuthSchemeName, g.authSchemeName)
}
scheme := g.securitySchemes[bearerAuthSchemeName]
if scheme == nil || scheme.Type != "http" || scheme.Scheme != "bearer" || scheme.BearerFormat != "JWT" {
t.Fatalf("unexpected security scheme: %+v", scheme)
}
})

t.Run("convert param kind whitelist", func(t *testing.T) {
testCases := []struct {
name string
Expand All @@ -271,8 +323,8 @@ func TestGeneratorHelpersMore_Table(t *testing.T) {
{name: "header", kind: state.KindHeader, expectKeep: true},
{name: "query", kind: state.KindQuery, expectKeep: true},
{name: "form", kind: state.KindForm, expectKeep: true},
{name: "path", kind: state.KindPath, expectKeep: true},
{name: "body skipped in parameter list", kind: state.KindRequestBody, expectKeep: false},
{name: "path skipped", kind: state.KindPath, expectKeep: false},
{name: "cookie skipped", kind: state.KindCookie, expectKeep: false},
{name: "state skipped", kind: state.KindState, expectKeep: false},
}
Expand Down
Loading
Loading