-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrest.go
251 lines (212 loc) · 7.46 KB
/
rest.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package rest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
argoclient "github.com/argoproj/argo-workflows/v3/pkg/client/clientset/versioned"
"github.com/equinor/flowify-workflows-server/auth"
"github.com/equinor/flowify-workflows-server/models"
"github.com/equinor/flowify-workflows-server/pkg/secret"
"github.com/equinor/flowify-workflows-server/pkg/workspace"
"github.com/equinor/flowify-workflows-server/storage"
"github.com/equinor/flowify-workflows-server/user"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"k8s.io/client-go/kubernetes"
)
type APIError struct {
Code int `json:"code"`
Summary string `json:"summary"`
Detail string `json:"detail"`
}
const (
// tries to validate all input according to spec
validateInput bool = true
// tries to validate output
validateOutput bool = false
)
// try to read a json-marshalled type from the body of a request
func ReadBody(r *http.Request, item any) error {
buf := new(bytes.Buffer)
if err := func() error { // scope for defer and err
_, err := buf.ReadFrom(r.Body)
defer r.Body.Close()
return err
}(); err != nil {
return err
}
if validateInput {
itemType := reflect.ValueOf(item).Type()
if err := models.ValidateDocument(buf.Bytes(), itemType); err != nil {
switch err {
case models.ErrNoSchemaFound:
// not an error here, just continue
default:
return errors.Wrapf(err, "cannot unmarshal item %s", itemType)
}
}
}
if err := json.Unmarshal(buf.Bytes(), item); err != nil {
return err
}
return nil
}
func WriteResponse(w http.ResponseWriter, status int, headers map[string]string, body any, tag string) {
bodyBytes, err := json.Marshal(body)
if err != nil {
WriteErrorResponse(w, APIError{http.StatusInternalServerError, fmt.Sprintf("cannot marshal response object %s", tag), err.Error()}, tag)
return
}
if validateOutput && body != nil {
// ALSO VALIDATE OUTPUT ACCORDING TO SPEC IF CONST IS SET IN PACKAGE
itemType := reflect.ValueOf(body).Type()
if err := models.ValidateDocument(bodyBytes, itemType); err != nil {
switch err {
case models.ErrNoSchemaFound:
// not an error here, just continue
default:
WriteErrorResponse(w, APIError{http.StatusInternalServerError, fmt.Sprintf("%s does not validate", tag), err.Error()}, tag)
return
}
}
}
// add headers
for k, v := range headers {
w.Header().Add(k, v)
}
w.WriteHeader(status)
w.Write(bodyBytes)
}
// unwrap the return code from the error and write a normal response
func WriteErrorResponse(w http.ResponseWriter, apierr APIError, tag string) {
WriteResponse(w, apierr.Code, nil, apierr, tag)
}
func RegisterRoutes(r *mux.Route,
componentClient storage.ComponentClient,
volumeClient storage.VolumeClient,
secretClient secret.SecretClient,
argoclient argoclient.Interface,
k8sclient kubernetes.Interface,
sec auth.AuthenticationClient,
authz auth.AuthorizationClient,
wsclient workspace.WorkspaceClient) {
subrouter := r.Subrouter()
// require authenticated context
subrouter.Use(NewAuthenticationMiddleware(sec))
subrouter.Use(NewAuthorizationContext(wsclient))
RegisterOpenApiRoutes(subrouter.PathPrefix("/spec"))
RegisterUserInfoRoutes(subrouter.PathPrefix(""))
RegisterComponentRoutes(subrouter.PathPrefix(""), componentClient)
RegisterWorkspaceRoutes(subrouter.PathPrefix(""))
// the following handlers below will use the authorized context's WorkspaceAccess
RegisterWorkflowRoutes(subrouter.PathPrefix(""), componentClient)
RegisterJobRoutes(subrouter.PathPrefix(""), componentClient, argoclient)
RegisterSecretRoutes(subrouter.PathPrefix(""), secretClient, authz)
RegisterVolumeRoutes(subrouter.PathPrefix(""), volumeClient, authz)
}
func RegisterOpenApiRoutes(r *mux.Route) {
subrouter := r.Subrouter()
sf := http.FileServer(http.FS(models.StaticSpec))
subrouter.PathPrefix("/").Handler(http.StripPrefix("/api/v1/", sf))
}
func SetContentTypeMiddleware(mediatype string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", mediatype)
next.ServeHTTP(w, r)
})
}
}
func CheckContentHeaderMiddleware(contentType string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
next.ServeHTTP(w, r)
return
}
ct := r.Header.Get("Content-Type")
if i := strings.IndexRune(ct, ';'); i != -1 {
ct = ct[0:i]
}
if ct == contentType {
next.ServeHTTP(w, r)
return
}
WriteErrorResponse(w, APIError{http.StatusUnsupportedMediaType, "Unsupported content type", fmt.Sprintf("Unsupported Content-Type header (%q): expecting %q", ct, contentType)}, "middleware")
})
}
}
func CheckAcceptRequestHeaderMiddleware(mediatype string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Header.Get("Accept")
if val != "" && val != "*/*" && val != mediatype {
WriteErrorResponse(w, APIError{http.StatusNotAcceptable, "Accept media type not acceptable", fmt.Sprintf("requested Accept type %s is not available, expecting %s", val, mediatype)}, "middleware")
return
}
next.ServeHTTP(w, r)
})
}
}
func PathAuthorization(subject auth.Subject, action auth.Action, pathVariableName string, authz auth.AuthorizationClient, next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pathVariable, exists := mux.Vars(r)[pathVariableName]
if !exists {
AuthorizationDenied(w, r, fmt.Errorf("bad request"))
return
}
user := user.GetUser(r.Context())
if allow, err := authz.Authorize(subject, action, user, pathVariable); err != nil || !allow {
if err == nil {
err = fmt.Errorf("not authorized")
}
AuthorizationDenied(w, r, err)
return
}
next(w, r)
})
}
// This ensures that the context is authenticated, with the appropriate User-tokens
func NewAuthenticationMiddleware(sec auth.AuthenticationClient) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
usr, err := sec.Authenticate(r)
if err != nil {
WriteErrorResponse(w, APIError{http.StatusBadRequest, "could not authenticate", err.Error()}, "authmiddleware")
return
}
// continue with authenticated context
next.ServeHTTP(w, r.WithContext(user.UserContext(usr, r.Context())))
})
}
}
// This injects the workspace into the context and can be used to authorize users further down the stack
func NewAuthorizationContext(wsclient workspace.WorkspaceClient) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wss := wsclient.ListWorkspaces()
usr := user.GetUser(r.Context())
aws := []workspace.Workspace{}
for _, ws := range wss {
aw := ws
hasAccess := aw.UserHasAccess(usr)
if hasAccess || !aw.HideForUnauthorized {
aws = append(aws, aw)
}
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), workspace.WorkspaceKey, aws)))
})
}
}
func GetWorkspaceAccess(ctx context.Context) []workspace.Workspace {
val := ctx.Value(workspace.WorkspaceKey)
if val == nil {
return []workspace.Workspace{}
} else {
return val.([]workspace.Workspace)
}
}