-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
339 lines (277 loc) · 7.52 KB
/
serve.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package repository
import (
"context"
"crypto/ecdsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/julienschmidt/httprouter"
"github.com/rakutentech/jwk-go/jwk"
"github.com/ttab/elephant-api/repository"
"github.com/ttab/elephant-repository/internal"
"github.com/ttab/elephantine"
"github.com/twitchtv/twirp"
)
func SetUpRouter(
router *httprouter.Router,
opts ...RouterOption,
) error {
for _, opt := range opts {
err := opt(router)
if err != nil {
return err
}
}
return nil
}
func ListenAndServe(ctx context.Context, addr string, h http.Handler) error {
var handler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
ctx := elephantine.WithLogMetadata(r.Context())
h.ServeHTTP(w, r.WithContext(ctx))
}
server := http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
}
//nolint:wrapcheck
return elephantine.ListenAndServeContext(ctx, &server)
}
type ServerOptions struct {
Hooks *twirp.ServerHooks
AuthMiddleware func(
w http.ResponseWriter, r *http.Request, next http.Handler,
) error
}
func (so *ServerOptions) SetJWTValidation(jwtKey *ecdsa.PrivateKey) {
// TODO: This feels like an initial sketch that should be further
// developed to address the JWT cacheing.
so.AuthMiddleware = func(
w http.ResponseWriter, r *http.Request, next http.Handler,
) error {
auth, err := elephantine.AuthInfoFromHeader(&jwtKey.PublicKey,
r.Header.Get("Authorization"))
if err != nil && !errors.Is(err, elephantine.ErrNoAuthorization) {
// TODO: Move the response part to a hook instead?
return elephantine.HTTPErrorf(http.StatusUnauthorized,
"invalid authorization method: %v", err)
}
if auth != nil {
ctx := elephantine.SetAuthInfo(r.Context(), auth)
elephantine.SetLogMetadata(ctx,
elephantine.LogKeySubject, auth.Claims.Subject,
)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
return nil
}
}
type RouterOption func(router *httprouter.Router) error
func WithDocumentsAPI(
service repository.Documents,
opts ServerOptions,
) RouterOption {
return func(router *httprouter.Router) error {
api := repository.NewDocumentsServer(
service,
twirp.WithServerJSONSkipDefaults(true),
twirp.WithServerHooks(opts.Hooks),
)
registerAPI(router, opts, api)
return nil
}
}
func WithSchemasAPI(
service repository.Schemas,
opts ServerOptions,
) RouterOption {
return func(router *httprouter.Router) error {
api := repository.NewSchemasServer(
service,
twirp.WithServerJSONSkipDefaults(true),
twirp.WithServerHooks(opts.Hooks),
)
registerAPI(router, opts, api)
return nil
}
}
func WithWorkflowsAPI(
service repository.Workflows,
opts ServerOptions,
) RouterOption {
return func(router *httprouter.Router) error {
api := repository.NewWorkflowsServer(
service,
twirp.WithServerJSONSkipDefaults(true),
twirp.WithServerHooks(opts.Hooks),
)
registerAPI(router, opts, api)
return nil
}
}
func WithReportsAPI(
service repository.Reports,
opts ServerOptions,
) RouterOption {
return func(router *httprouter.Router) error {
api := repository.NewReportsServer(
service,
twirp.WithServerJSONSkipDefaults(true),
twirp.WithServerHooks(opts.Hooks),
)
registerAPI(router, opts, api)
return nil
}
}
func WithJWKSEndpoint(jwtKey *ecdsa.PrivateKey) RouterOption {
return func(router *httprouter.Router) error {
key := jwk.NewSpec(jwtKey)
key.Algorithm = jwt.SigningMethodES384.Alg()
key.Use = "sig"
keySet := jwk.KeySpecSet{
Keys: []jwk.KeySpec{*key},
}
payload, err := keySet.MarshalPublicJSON()
if err != nil {
return fmt.Errorf("failed to create JWKs payload: %w", err)
}
router.GET("/.well-known/jwks.json", httprouter.Handle(func(
w http.ResponseWriter, r *http.Request, p httprouter.Params,
) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(payload)
}))
return nil
}
}
func WithMetricsAPI(
service repository.Metrics,
opts ServerOptions,
) RouterOption {
return func(router *httprouter.Router) error {
api := repository.NewMetricsServer(
service,
twirp.WithServerJSONSkipDefaults(true),
twirp.WithServerHooks(opts.Hooks),
)
registerAPI(router, opts, api)
return nil
}
}
func WithTokenEndpoint(
jwtKey *ecdsa.PrivateKey, sharedSecret string,
) RouterOption {
return func(router *httprouter.Router) error {
router.POST("/token", internal.RHandleFunc(func(
w http.ResponseWriter, r *http.Request, _ httprouter.Params,
) error {
err := r.ParseForm()
if err != nil {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"invalid form data: %v", err)
}
form := r.Form
switch form.Get("grant_type") {
case "password":
case "refresh_token":
if form.Get("refresh_token") == "" {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"missing 'refresh_token'")
}
rData, err := base64.RawStdEncoding.DecodeString(
form.Get("refresh_token"))
if err != nil {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"invalid refresh token: %v", err)
}
f, err := url.ParseQuery(string(rData))
if err != nil {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"invalid refresh contents: %v", err)
}
form = f
default:
return elephantine.HTTPErrorf(http.StatusBadRequest,
"we only support the \"password\" and \"refresh_token\" grant_type")
}
username := form.Get("username")
if username == "" {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"missing 'username'")
}
password := form.Get("password")
if password != sharedSecret {
return elephantine.HTTPErrorf(http.StatusUnauthorized,
"invalid password")
}
scope := form.Get("scope")
name, uriPart, ok := strings.Cut(username, " <")
if !ok || !strings.HasSuffix(uriPart, ">") {
return elephantine.HTTPErrorf(http.StatusBadRequest,
"username must be in the format \"Name <some://sub/uri>\"")
}
subURI := strings.TrimSuffix(uriPart, ">")
expiresIn := 10 * time.Minute
sub, units, _ := strings.Cut(subURI, ", ")
claims := elephantine.JWTClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(
time.Now().Add(expiresIn)),
Issuer: "test",
Subject: sub,
},
Name: name,
Scope: scope,
}
if len(units) > 0 {
claims.Units = strings.Split(units, ", ")
}
token := jwt.NewWithClaims(jwt.SigningMethodES384, claims)
ss, err := token.SignedString(jwtKey)
if err != nil {
return elephantine.HTTPErrorf(http.StatusInternalServerError,
"failed to sign JWT token")
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(TokenResponse{
AccessToken: ss,
RefreshToken: base64.RawURLEncoding.EncodeToString(
[]byte(form.Encode()),
),
TokenType: "Bearer",
ExpiresIn: int(expiresIn.Seconds()),
})
if err != nil {
return elephantine.HTTPErrorf(http.StatusInternalServerError,
"failed encode token response")
}
return nil
}))
return nil
}
}
type apiServerForRouter interface {
http.Handler
PathPrefix() string
}
func registerAPI(
router *httprouter.Router, opt ServerOptions,
api apiServerForRouter,
) {
router.POST(api.PathPrefix()+":method", internal.RHandleFunc(func(
w http.ResponseWriter, r *http.Request, _ httprouter.Params,
) error {
if opt.AuthMiddleware != nil {
return opt.AuthMiddleware(w, r, api)
}
api.ServeHTTP(w, r)
return nil
}))
}