/
api_service.go
153 lines (131 loc) · 3.84 KB
/
api_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package service
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
oapimiddleware "github.com/deepmap/oapi-codegen/pkg/middleware"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/projectsyn/lieutenant-api/pkg/api"
swaggerui "github.com/projectsyn/lieutenant-api/swagger-ui"
)
// APIImpl implements the API interface
type APIImpl struct {
namespace string
// Metadata on the API itself
metadata api.Metadata
}
// APIConfig holds the config options for the API
type APIConfig struct {
APIVersion string
Namespace string
OidcDiscoveryURL string
OidcCLientID string
}
// APIContext is a custom echo context
type APIContext struct {
echo.Context
client client.Client
}
var (
swaggerJSON []byte
)
// NewAPIServer instantiates a new Echo API server
func NewAPIServer(conf APIConfig, k8sMiddleware ...KubernetesAuth) (*echo.Echo, error) {
swagger, err := api.GetSwagger()
if err != nil {
return nil, fmt.Errorf("error loading swagger spec: %w", err)
}
swaggerJSON, err = swagger.MarshalJSON()
if err != nil {
return nil, fmt.Errorf("error marshalling swagger spec: %w", err)
}
namespace := conf.Namespace
if len(namespace) == 0 {
namespace = "default"
}
apiImpl := &APIImpl{
namespace: namespace,
metadata: api.Metadata{
ApiVersion: conf.APIVersion,
},
}
if conf.OidcCLientID != "" || conf.OidcDiscoveryURL != "" {
apiImpl.metadata.Oidc = &api.OIDCConfig{
ClientId: conf.OidcCLientID,
DiscoveryUrl: conf.OidcDiscoveryURL,
}
}
e := echo.New()
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Skipper: func(c echo.Context) bool { return strings.HasSuffix(c.Path(), "/healthz") },
}))
e.Use(middleware.Recover())
e.Pre(middleware.RemoveTrailingSlash())
e.HTTPErrorHandler = customHTTPErrorHandler
openapi3filter.RegisterBodyDecoder(api.ContentJSONPatch, func(body io.Reader, header http.Header, schema *openapi3.SchemaRef, encFn openapi3filter.EncodingFn) (interface{}, error) {
var value interface{}
if err := json.NewDecoder(body).Decode(&value); err != nil {
return nil, &openapi3filter.ParseError{Kind: openapi3filter.KindInvalidFormat, Cause: err}
}
return value, nil
})
options := &oapimiddleware.Options{
Options: openapi3filter.Options{
AuthenticationFunc: func(c context.Context, input *openapi3filter.AuthenticationInput) error {
return nil
},
},
}
e.Use(oapimiddleware.OapiRequestValidatorWithOptions(swagger, options))
if len(k8sMiddleware) == 0 {
e.Use(DefaultKubernetesAuth.JWTAuth)
} else {
for _, middle := range k8sMiddleware {
e.Use(middle.JWTAuth)
}
}
api.RegisterHandlers(e, apiImpl)
return e, nil
}
func customHTTPErrorHandler(err error, c echo.Context) {
code := http.StatusInternalServerError
message := err.Error()
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
if m, ok := he.Message.(string); ok {
message = m
}
} else if apiErr, ok := err.(errors.APIStatus); ok {
code = int(apiErr.Status().Code)
message = strings.ReplaceAll(apiErr.Status().Message, "\"", "'")
}
reason := api.Reason{
Reason: message,
}
c.JSON(code, reason)
c.Logger().Error(err)
}
// Discovery implements the API dicovery endpoint
func (s *APIImpl) Discovery(ctx echo.Context) error {
return ctx.JSON(http.StatusOK, &s.metadata)
}
// Healthz implements the API health check
func (s *APIImpl) Healthz(ctx echo.Context) error {
return ctx.String(http.StatusOK, "ok")
}
// Docs serves the swagger UI
func (s *APIImpl) Docs(ctx echo.Context) error {
return ctx.HTMLBlob(http.StatusOK, swaggerui.SwaggerHTML)
}
// Openapi serves the JSON spec
func (s *APIImpl) Openapi(ctx echo.Context) error {
return ctx.JSONBlob(http.StatusOK, swaggerJSON)
}