generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
option.go
424 lines (355 loc) · 13.2 KB
/
option.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package serveropts
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
echoprometheus "github.com/datumforge/echo-prometheus/v5"
echo "github.com/datumforge/echox"
"github.com/datumforge/echox/middleware"
"github.com/datumforge/echozap"
"github.com/datumforge/entx"
"github.com/datumforge/fgax"
sentrygo "github.com/getsentry/sentry-go"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
"github.com/datumforge/datum/internal/ent/generated"
"github.com/datumforge/datum/internal/graphapi"
"github.com/datumforge/datum/internal/httpserve/config"
"github.com/datumforge/datum/internal/httpserve/server"
"github.com/datumforge/datum/pkg/analytics"
"github.com/datumforge/datum/pkg/cache"
authmw "github.com/datumforge/datum/pkg/middleware/auth"
"github.com/datumforge/datum/pkg/middleware/cachecontrol"
"github.com/datumforge/datum/pkg/middleware/cors"
"github.com/datumforge/datum/pkg/middleware/echocontext"
"github.com/datumforge/datum/pkg/middleware/mime"
"github.com/datumforge/datum/pkg/middleware/ratelimit"
"github.com/datumforge/datum/pkg/middleware/redirect"
"github.com/datumforge/datum/pkg/middleware/secure"
"github.com/datumforge/datum/pkg/middleware/sentry"
"github.com/datumforge/datum/pkg/providers/webauthn"
"github.com/datumforge/datum/pkg/sessions"
"github.com/datumforge/datum/pkg/utils/emails"
"github.com/datumforge/datum/pkg/utils/marionette"
"github.com/datumforge/datum/pkg/utils/totp"
"github.com/datumforge/datum/pkg/utils/ulids"
)
type ServerOption interface {
apply(*ServerOptions)
}
type applyFunc struct {
applyInternal func(*ServerOptions)
}
func (fso *applyFunc) apply(s *ServerOptions) {
fso.applyInternal(s)
}
func newApplyFunc(apply func(option *ServerOptions)) *applyFunc {
return &applyFunc{
applyInternal: apply,
}
}
// WithConfigProvider supplies the config for the server
func WithConfigProvider(cfgProvider config.ConfigProvider) ServerOption {
return newApplyFunc(func(s *ServerOptions) {
s.ConfigProvider = cfgProvider
})
}
// WithLogger supplies the logger for the server
func WithLogger(l *zap.SugaredLogger) ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// Add logger to main config
s.Config.Logger = l
// Add logger to the handlers config
s.Config.Handler.Logger = l
})
}
// WithHTTPS sets up TLS config settings for the server
func WithHTTPS() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if !s.Config.Settings.Server.TLS.Enabled {
// this is set to enabled by WithServer
// if TLS is not enabled, move on
return
}
s.Config.WithTLSDefaults()
if !s.Config.Settings.Server.TLS.AutoCert {
s.Config.WithTLSCerts(s.Config.Settings.Server.TLS.CertFile, s.Config.Settings.Server.TLS.CertKey)
}
})
}
// WithGeneratedKeys will generate a public/private key pair
// that can be used for jwt signing.
// This should only be used in a development environment
func WithGeneratedKeys() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
privFileName := "private_key.pem"
// generate a new private key if one doesn't exist
if _, err := os.Stat(privFileName); err != nil {
// Generate a new RSA private key with 2048 bits
privateKey, err := rsa.GenerateKey(rand.Reader, 2048) //nolint:gomnd
if err != nil {
s.Config.Logger.Panicf("Error generating RSA private key:", err)
}
// Encode the private key to the PEM format
privateKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
privateKeyFile, err := os.Create(privFileName)
if err != nil {
s.Config.Logger.Panicf("Error creating private key file:", err)
}
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
s.Config.Logger.Panicw("unable to encode pem on startup", "error", err.Error())
}
privateKeyFile.Close()
}
keys := map[string]string{}
// check if kid was passed in
kidPriv := s.Config.Settings.Auth.Token.KID
// if we didn't get a kid in the settings, assign one
if kidPriv == "" {
kidPriv = ulids.New().String()
}
keys[kidPriv] = fmt.Sprintf("%v", privFileName)
s.Config.Settings.Auth.Token.Keys = keys
})
}
// WithAuth supplies the authn and jwt config for the server
func WithAuth() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// add oauth providers
s.Config.Handler.OauthProvider = s.Config.Settings.Auth.Providers
// add auth middleware
conf := authmw.NewAuthOptions(
authmw.WithAudience(s.Config.Settings.Auth.Token.Audience),
authmw.WithIssuer(s.Config.Settings.Auth.Token.Issuer),
authmw.WithJWKSEndpoint(s.Config.Settings.Auth.Token.JWKSEndpoint),
authmw.WithDBClient(s.Config.Handler.DBClient),
)
s.Config.Handler.WebAuthn = webauthn.NewWithConfig(s.Config.Settings.Auth.Providers.Webauthn)
s.Config.GraphMiddleware = append(s.Config.GraphMiddleware, authmw.Authenticate(conf))
s.Config.Handler.AuthMiddleware = append(s.Config.Handler.AuthMiddleware, authmw.Authenticate(conf))
})
}
// WithReadyChecks adds readiness checks to the server
func WithReadyChecks(c *entx.EntClientConfig, f *fgax.Client, r *redis.Client) ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// Always add a check to the primary db connection
s.Config.Handler.AddReadinessCheck("db_primary", entx.Healthcheck(c.GetPrimaryDB()))
// Check the secondary db, if enabled
if s.Config.Settings.DB.MultiWrite {
s.Config.Handler.AddReadinessCheck("db_secondary", entx.Healthcheck(c.GetSecondaryDB()))
}
// Check the connection to openFGA, if enabled
if s.Config.Settings.Authz.Enabled {
s.Config.Handler.AddReadinessCheck("fga", fgax.Healthcheck(*f))
}
// Check the connection to redis, if enabled
if s.Config.Settings.Redis.Enabled {
s.Config.Handler.AddReadinessCheck("redis", cache.Healthcheck(r))
}
})
}
// WithGraphRoute adds the graph handler to the server
func WithGraphRoute(srv *server.Server, c *generated.Client) ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// Setup Graph API Handlers
r := graphapi.NewResolver(c).
WithLogger(s.Config.Logger.Named("resolvers"))
handler := r.Handler(s.Config.Settings.Server.Dev)
// Add Graph Handler
srv.AddHandler(handler)
})
}
// WithMiddleware adds the middleware to the server
func WithMiddleware() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// Initialize middleware if null
if s.Config.DefaultMiddleware == nil {
s.Config.DefaultMiddleware = []echo.MiddlewareFunc{}
}
// default middleware
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware,
middleware.RequestID(), // add request id
middleware.Recover(), // recover server from any panic/fatal error gracefully
middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "remote_ip=${remote_ip}, method=${method}, uri=${uri}, status=${status}, session=${header:Set-Cookie}, host=${host}, referer=${referer}, user_agent=${user_agent}, route=${route}, path=${path}, auth=${header:Authorization}\n",
}),
echoprometheus.MetricsMiddleware(), // add prometheus metrics
echozap.ZapLogger(s.Config.Logger.Desugar()), // add zap logger, middleware requires the "regular" zap logger
echocontext.EchoContextToContextMiddleware(), // adds echo context to parent
mime.NewWithConfig(mime.Config{DefaultContentType: echo.MIMEApplicationJSONCharsetUTF8}), // add mime middleware
)
})
}
// WithEmailManager sets up the default SendGrid email manager to be used to send emails to users
// on registration, password reset, etc
func WithEmailManager() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
em, err := emails.New(s.Config.Settings.Email)
if err != nil {
panic(err)
}
if err := s.Config.Settings.Email.ConsoleURLConfig.Validate(); err != nil {
panic(err)
}
em.ConsoleURLConfig = s.Config.Settings.Email.ConsoleURLConfig
if err := s.Config.Settings.Email.MarketingURLConfig.Validate(); err != nil {
panic(err)
}
em.MarketingURLConfig = s.Config.Settings.Email.MarketingURLConfig
s.Config.Handler.EmailManager = em
})
}
// WithTaskManager sets up the default Marionette task manager to be used for delegating background tasks
func WithTaskManager() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
// Start task manager
tmConfig := marionette.Config{
Logger: s.Config.Logger,
}
tm := marionette.New(tmConfig)
tm.Start()
s.Config.Handler.TaskMan = tm
})
}
// WithSessionManager sets up the default session manager with a 10 minute ttl
// with persistence to redis
func WithSessionManager(rc *redis.Client) ServerOption {
return newApplyFunc(func(s *ServerOptions) {
cc := sessions.DefaultCookieConfig
// In order for things to work in dev mode with localhost
// we need to se the debug cookie config
if s.Config.Settings.Server.Dev {
cc = &sessions.DebugOnlyCookieConfig
} else {
cc.Name = sessions.DefaultCookieName
}
sm := sessions.NewCookieStore[map[string]any](cc,
[]byte(s.Config.Settings.Sessions.SigningKey),
[]byte(s.Config.Settings.Sessions.EncryptionKey),
)
// add session middleware, this has to be added after the authMiddleware so we have the user id
// when we get to the session. this is also added here so its only added to the graph routes
// REST routes are expected to add the session middleware, as required
sessionConfig := sessions.NewSessionConfig(
sm,
sessions.WithPersistence(rc),
sessions.WithLogger(s.Config.Logger),
sessions.WithSkipperFunc(authmw.SessionSkipperFunc),
)
// set cookie config to be used
sessionConfig.CookieConfig = cc
// Make the cookie session store available
// to graph and REST endpoints
s.Config.Handler.SessionConfig = &sessionConfig
s.Config.SessionConfig = &sessionConfig
s.Config.GraphMiddleware = append(s.Config.GraphMiddleware,
sessions.LoadAndSaveWithConfig(sessionConfig),
)
})
}
// WithSentry sets up the sentry middleware for error tracking
func WithSentry() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Sentry.Enabled {
if err := sentrygo.Init(s.Config.Settings.Sentry.ClientOptions()); err != nil {
s.Config.Logger.Fatalw("failed to initialize sentry", "error", err)
}
// add sentry middleware
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, sentry.New())
}
})
}
// WithAnalytics sets up the PostHog analytics manager
func WithAnalytics() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
ph := s.Config.Settings.PostHog.Init()
if ph == nil {
s.Config.Handler.AnalyticsClient = &analytics.EventManager{
Enabled: false,
Handler: nil,
}
return
}
s.Config.Handler.AnalyticsClient = &analytics.EventManager{
Enabled: true,
Handler: ph,
}
})
}
// WithOTP sets up the OTP provider
func WithOTP() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.TOTP.Enabled {
if s.Config.Settings.TOTP.Secret == "" {
s.Config.Settings.TOTP.Secret = ulids.New().String()
}
opts := []totp.ConfigOption{
totp.WithCodeLength(s.Config.Settings.TOTP.CodeLength),
totp.WithIssuer(s.Config.Settings.TOTP.Issuer),
totp.WithSecret(totp.Secret{
Version: 0,
Key: s.Config.Settings.TOTP.Secret,
}),
}
// append redis client if enabed
if s.Config.Settings.TOTP.WithRedis {
opts = append(opts, totp.WithRedis(s.Config.Handler.RedisClient))
}
// setup new opt manager
otpMan := totp.NewOTP(
opts...,
)
s.Config.Handler.OTPManager = &totp.Manager{
TOTPManager: otpMan,
}
}
})
}
// WithRateLimiter sets up the rate limiter for the server
func WithRateLimiter() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Ratelimit.Enabled {
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, ratelimit.RateLimiterWithConfig(&s.Config.Settings.Ratelimit))
}
})
}
// WithSecureMW sets up the secure middleware for the server
func WithSecureMW() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Server.Secure.Enabled {
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, secure.Secure(&s.Config.Settings.Server.Secure))
}
})
}
// WithRedirects sets up the redirects for the server
func WithRedirects() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Server.Redirects.Enabled {
redirects := s.Config.Settings.Server.Redirects
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, redirect.NewWithConfig(redirects))
}
})
}
// WithCacheHeaders sets up the cache control headers for the server
func WithCacheHeaders() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Server.CacheControl.Enabled {
cacheConfig := s.Config.Settings.Server.CacheControl
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, cachecontrol.NewWithConfig(cacheConfig))
}
})
}
// WithCORS sets up the CORS middleware for the server
func WithCORS() ServerOption {
return newApplyFunc(func(s *ServerOptions) {
if s.Config.Settings.Server.CORS.Enabled {
s.Config.DefaultMiddleware = append(s.Config.DefaultMiddleware, cors.New(s.Config.Settings.Server.CORS.AllowOrigins))
}
})
}