-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathrouter.go
More file actions
749 lines (640 loc) · 25.5 KB
/
Copy pathrouter.go
File metadata and controls
749 lines (640 loc) · 25.5 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
package route
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/getkin/kin-openapi/openapi3"
echo "github.com/theopenlane/echox"
"github.com/theopenlane/httpsling"
"github.com/theopenlane/core/internal/httpserve/common"
"github.com/theopenlane/core/internal/httpserve/handlers"
"github.com/theopenlane/core/pkg/middleware/impersonation"
"github.com/theopenlane/core/pkg/middleware/mime"
"github.com/theopenlane/core/pkg/middleware/transaction"
)
// convertEchoPathToOpenAPI converts Echo's :param syntax to OpenAPI's {param} syntax
func convertEchoPathToOpenAPI(echoPath string) string {
// Split the path into parts and convert :param to {param}
parts := strings.Split(echoPath, "/")
for i, part := range parts {
if strings.HasPrefix(part, ":") {
// Convert :param to {param}
parts[i] = "{" + part[1:] + "}"
}
}
return strings.Join(parts, "/")
}
// addPathParametersFromPattern extracts path parameters from Echo-style path and adds them to OpenAPI operation
func (r *Router) addPathParametersFromPattern(path string, operation *openapi3.Operation) {
// Extract parameter names from Echo-style path (e.g., :id, :name)
parts := strings.SplitSeq(path, "/")
for part := range parts {
if strings.HasPrefix(part, ":") {
paramName := part[1:] // Remove the : prefix
// Check if parameter already exists (e.g., from struct tags)
exists := false
if operation.Parameters != nil {
for _, p := range operation.Parameters {
if p.Value != nil && p.Value.Name == paramName && p.Value.In == "path" {
exists = true
break
}
}
}
// Only add if it doesn't already exist
if !exists {
// Add path parameter to the operation
param := openapi3.NewPathParameter(paramName).
WithSchema(openapi3.NewStringSchema()).
WithDescription(fmt.Sprintf("Path parameter: %s", paramName))
operation.AddParameter(param)
}
}
}
}
// registerSuccessResponseSchemas registers success response schemas dynamically
// This completely eliminates static mappings by allowing handlers to register their own response types
func (r *Router) registerSuccessResponseSchemas(config Config, openAPIContext *handlers.OpenAPIContext) {
if openAPIContext.Registry == nil {
return
}
// For special non-JSON responses, handle them explicitly
r.handleSpecialResponses(config.OperationID, openAPIContext)
}
// handleSpecialResponses handles non-JSON response cases only
func (r *Router) handleSpecialResponses(operationID string, openAPIContext *handlers.OpenAPIContext) {
switch operationID {
// Non-JSON responses only - these don't use h.Success() so need explicit registration
case "AcmeSolver":
r.addPlainTextResponse(openAPIContext, "ACME challenge response")
case "AppleMerchant", "SecurityTxt", "WebAuthnWellKnown", "Robots", "Favicon", "MSFTIdentityWellKnown":
r.addFileResponse(openAPIContext, "Static file content")
case "JWKS":
r.addJSONResponse(openAPIContext, "JSON Web Key Set", "application/json")
case "APIDocs":
r.addJSONResponse(openAPIContext, "OpenAPI specification", "application/json")
case "CSRF":
r.addJSONResponse(openAPIContext, "CSRF token", "application/json")
case "ExampleCSV":
r.addFileResponse(openAPIContext, "CSV file content")
case "Files":
r.addFileResponse(openAPIContext, "File content")
case "GitHubCallback", "GitHubLogin", "GoogleCallback", "GoogleLogin":
r.addRedirectResponse(openAPIContext, "OAuth redirect")
case "UserInfo":
r.addJSONResponse(openAPIContext, "User information", "application/json")
case "Livez", "Ready":
r.addJSONResponse(openAPIContext, "Health check status", "application/json")
case "StripeWebhook", "ResendWebhook":
r.addPlainTextResponse(openAPIContext, "Webhook acknowledgment")
default:
// All other endpoints register their responses via h.Success() calls during registration
}
}
// addPlainTextResponse adds a plain text success response to the operation
func (r *Router) addPlainTextResponse(openAPIContext *handlers.OpenAPIContext, description string) {
response := openapi3.NewResponse().
WithDescription(description).
WithContent(openapi3.NewContentWithSchema(openapi3.NewStringSchema(), []string{"text/plain"}))
openAPIContext.Operation.AddResponse(http.StatusOK, response)
}
// addJSONResponse adds a JSON success response to the operation
func (r *Router) addJSONResponse(openAPIContext *handlers.OpenAPIContext, description, contentType string) {
response := openapi3.NewResponse().
WithDescription(description).
WithContent(openapi3.NewContentWithSchema(openapi3.NewObjectSchema(), []string{contentType}))
openAPIContext.Operation.AddResponse(http.StatusOK, response)
}
// addFileResponse adds a file content success response to the operation
func (r *Router) addFileResponse(openAPIContext *handlers.OpenAPIContext, description string) {
response := openapi3.NewResponse().
WithDescription(description).
WithContent(openapi3.NewContentWithSchema(openapi3.NewStringSchema(), []string{"application/octet-stream"}))
openAPIContext.Operation.AddResponse(http.StatusOK, response)
}
// addRedirectResponse adds a redirect success response to the operation
func (r *Router) addRedirectResponse(openAPIContext *handlers.OpenAPIContext, description string) {
response := openapi3.NewResponse().WithDescription(description)
openAPIContext.Operation.AddResponse(http.StatusFound, response)
}
var (
// baseMW includes the basic middleware, which includes the transaction middleware and recovery middleware, most endpoints will not use this, but use `mw` instead
baseMW = []echo.MiddlewareFunc{}
// mw is the default middleware that is applied to all routes, it includes the transaction middleware and any additional middleware (including csrf)
// this is used for most routes that are not authenticated or restricted
mw = []echo.MiddlewareFunc{}
// authMW is the middleware that is used on authenticated routes, it includes the transaction middleware, the auth middleware, and any additional middleware after the auth middleware
authMW = []echo.MiddlewareFunc{}
)
// Middleware Semantic Names for better readability
var (
// authenticatedEndpoint for endpoints requiring authentication
authenticatedEndpoint = &authMW
// publicEndpoint for standard public endpoints
publicEndpoint = &mw
// unauthenticatedEndpoint for basic endpoints with minimal middleware
unauthenticatedEndpoint = &baseMW
)
// Router is a struct that holds the echo router, the OpenAPI schema, and the handler - it's a way to group these components together
type Router struct {
// Echo is the underlying Echo router instance.
Echo *echo.Echo
// OAS is the OpenAPI spec being assembled.
OAS *openapi3.T
// Handler provides the HTTP handlers wired into routes.
Handler *handlers.Handler
// StartConfig holds Echo start configuration.
StartConfig *echo.StartConfig
// LocalFilePath points to static file roots for local assets.
LocalFilePath string
// Logger is the Echo logger used by the router.
Logger *echo.Logger
// SchemaRegistry registers and resolves OpenAPI schemas.
SchemaRegistry SchemaRegistry
}
// SchemaRegistry interface for dynamic schema registration
type SchemaRegistry interface {
RegisterType(v any) (*openapi3.SchemaRef, error)
GetOrRegister(v any) (*openapi3.SchemaRef, error)
}
// RouterOption is an option function that can be used to configure the router
type RouterOption func(*Router)
// WithLogger is a RouterOption that allows the logger to be set on the router
func WithLogger(logger *echo.Logger) RouterOption {
return func(r *Router) {
r.Logger = logger
}
}
// WithHandler is a RouterOption that allows the handler to be set on the router
func WithHandler(h *handlers.Handler) RouterOption {
return func(r *Router) {
r.Handler = h
}
}
// WithEcho is a RouterOption that allows the echo router to be set on the router
func WithEcho(e *echo.Echo) RouterOption {
return func(r *Router) {
r.Echo = e
}
}
// WithLocalFiles is a RouterOption that allows the local files to be set on the router
func WithLocalFiles(lf string) RouterOption {
return func(r *Router) {
r.LocalFilePath = lf
}
}
// WithOpenAPI is a RouterOption that allows the OpenAPI schema to be set on the router
func WithOpenAPI(oas *openapi3.T) RouterOption {
return func(r *Router) {
r.OAS = oas
}
}
// WithOptions is a RouterOption that allows multiple options to be set on the router
func WithOptions(opts ...RouterOption) RouterOption {
return func(r *Router) {
for _, opt := range opts {
opt(r)
}
}
}
// WithHideBanner is a RouterOption that allows the banner to be hidden on the echo server
func WithHideBanner() RouterOption {
return func(r *Router) {
r.StartConfig = &echo.StartConfig{
HideBanner: true,
}
}
}
// AddRoute is used to add a route to the echo router and OpenAPI schema at the same time ensuring consistency between the spec and the server
func (r *Router) AddRoute(pattern, method string, op *openapi3.Operation, route echo.Routable) error {
_, err := r.Echo.AddRoute(route)
if err != nil {
return err
}
// Convert Echo path syntax to OpenAPI syntax
openAPIPath := convertEchoPathToOpenAPI(pattern)
r.OAS.AddOperation(openAPIPath, method, op)
return nil
}
// AddV1Route is used to add a route to the echo router and OpenAPI schema at the same time ensuring consistency between the spec and the server for version 1 routes of the api
func (r *Router) AddV1Route(pattern, method string, op *openapi3.Operation, route echo.Routable) error {
grp := r.VersionOne()
_, err := grp.AddRoute(route)
if err != nil {
return err
}
// Convert Echo path syntax to OpenAPI syntax
openAPIPath := convertEchoPathToOpenAPI(pattern)
r.OAS.AddOperation(openAPIPath, method, op)
return nil
}
// AddUnversionedRoute is used to add a versioned route to the echo router and OpenAPI schema at the same time ensuring consistency between the spec and the server
func (r *Router) AddUnversionedRoute(pattern, method string, op *openapi3.Operation, route echo.Routable) error {
grp := r.Base()
_, err := grp.AddRoute(route)
if err != nil {
return err
}
// Convert Echo path syntax to OpenAPI syntax
openAPIPath := convertEchoPathToOpenAPI(pattern)
r.OAS.AddOperation(openAPIPath, method, op)
return nil
}
// AddEchoOnlyRoute is used to add a route to the echo router without adding it to the OpenAPI schema
func (r *Router) AddEchoOnlyRoute(route echo.Routable) error {
grp := r.Base()
_, err := grp.AddRoute(route)
if err != nil {
return err
}
return nil
}
// VersionOne returns a new echo group for version 1 of the API
func (r *Router) VersionOne() *echo.Group {
return r.Echo.Group("v1")
}
// VersionTwo returns a new echo group for version 2 of the API - lets anticipate the future
func (r *Router) VersionTwo() *echo.Group {
return r.Echo.Group("v2")
}
// Base returns the base echo group - no "version" prefix for the router group
func (r *Router) Base() *echo.Group {
return r.Echo.Group("")
}
// Config holds the configuration for a route with automatic OpenAPI registration
type Config struct {
// Path is the route path pattern.
Path string
// Method is the HTTP method for the route.
Method string
// Name is the OpenAPI summary for the route.
Name string
// Description is the OpenAPI description for the route.
Description string
// Tags are the OpenAPI tags for grouping.
Tags []string
// OperationID is the OpenAPI operation ID.
OperationID string
// Security defines OpenAPI security requirements for the route.
Security *openapi3.SecurityRequirements
// Middlewares are applied before the handler.
Middlewares []echo.MiddlewareFunc
// Handler is the OpenAPI-aware handler function.
Handler func(echo.Context, *handlers.OpenAPIContext) error
// SimpleHandler is used for routes without OpenAPI context.
SimpleHandler func(echo.Context) error // For handlers that don't need OpenAPI context
// ExcludeFromOAS skips publishing this route in the OpenAPI specification.
ExcludeFromOAS bool
}
// registrationContext is a special echo.Context implementation used during OpenAPI registration
type registrationContext struct {
// Context embeds an Echo context for registration-mode requests.
echo.Context
ctx context.Context
method string
}
// newRegistrationContext creates a new registration context with the HTTP method
func newRegistrationContext(method string) *registrationContext {
// Create a base context with registration marker
baseCtx := common.WithRegistrationMarker(context.Background())
return ®istrationContext{
Context: echo.New().NewContext(nil, nil),
ctx: baseCtx,
method: method,
}
}
// Request returns a minimal request that won't panic when accessed
func (rc *registrationContext) Request() *http.Request {
req, _ := http.NewRequestWithContext(rc.ctx, rc.method, "/", nil)
return req
}
// AddV1HandlerRoute adds a route with automatic OpenAPI context injection
func (r *Router) AddV1HandlerRoute(config Config) error {
operation := openapi3.NewOperation()
operation.Summary = config.Name
operation.Description = config.Description
operation.Tags = config.Tags
operation.OperationID = config.OperationID
if config.Security != nil {
operation.Security = config.Security
}
// Create OpenAPI context
openAPIContext := &handlers.OpenAPIContext{
Operation: operation,
Registry: r.SchemaRegistry,
}
// Call the handler with a registration context to trigger OpenAPI registration
// This allows handlers to register their request/response schemas at startup
regCtx := newRegistrationContext(config.Method)
// Try to call the handler - if it returns an error or panics, that's OK
// during registration. The important thing is that the handler had a chance
// to register its schemas via BindAndValidateWithAutoRegistry and response methods
func() {
defer func() {
// During registration, handlers might panic when accessing nil request fields
// This is expected and OK - the schemas should still be registered
_ = recover()
}()
if config.Handler != nil {
_ = config.Handler(regCtx, openAPIContext)
} else if config.SimpleHandler != nil {
_ = config.SimpleHandler(regCtx)
}
}()
// Ensure common error responses are registered for all endpoints
if openAPIContext.Operation != nil {
// Add standard error responses that all endpoints should have
handlers.AddStandardResponses(openAPIContext.Operation)
// Register success response schemas based on operation ID patterns
r.registerSuccessResponseSchemas(config, openAPIContext)
// Add path parameters from the path pattern if not already added by BindAndValidateWithAutoRegistry
r.addPathParametersFromPattern(config.Path, operation)
}
// Create echo route with automatic OpenAPI context injection
var routeHandler func(echo.Context) error
if config.Handler != nil {
routeHandler = func(c echo.Context) error {
return config.Handler(c, openAPIContext)
}
} else if config.SimpleHandler != nil {
routeHandler = config.SimpleHandler
}
route := echo.Route{
Name: config.Name,
Method: config.Method,
Path: config.Path,
Middlewares: config.Middlewares,
Handler: routeHandler,
}
// Add route to echo router
grp := r.VersionOne()
_, err := grp.AddRoute(route)
if err != nil {
return err
}
if !config.ExcludeFromOAS {
// Add operation to OpenAPI schema (convert Echo path syntax to OpenAPI syntax)
openAPIPath := convertEchoPathToOpenAPI("/v1" + config.Path)
r.OAS.AddOperation(openAPIPath, config.Method, operation)
}
return nil
}
// AddUnversionedHandlerRoute adds an unversioned route with automatic OpenAPI context injection
func (r *Router) AddUnversionedHandlerRoute(config Config) error {
operation := openapi3.NewOperation()
operation.Summary = config.Name
operation.Description = config.Description
operation.Tags = config.Tags
operation.OperationID = config.OperationID
if config.Security != nil {
operation.Security = config.Security
}
// Create OpenAPI context
openAPIContext := &handlers.OpenAPIContext{
Operation: operation,
Registry: r.SchemaRegistry,
}
// Call the handler with a registration context to trigger OpenAPI registration
regCtx := newRegistrationContext(config.Method)
func() {
defer func() {
// During registration, handlers might panic when accessing nil request fields
_ = recover()
}()
if config.Handler != nil {
_ = config.Handler(regCtx, openAPIContext)
} else if config.SimpleHandler != nil {
_ = config.SimpleHandler(regCtx)
}
}()
// Ensure common error responses are registered for all endpoints
if openAPIContext.Operation != nil {
r.registerSuccessResponseSchemas(config, openAPIContext)
// Add path parameters from the path pattern if not already added by BindAndValidateWithAutoRegistry
r.addPathParametersFromPattern(config.Path, operation)
}
// Create echo route with automatic OpenAPI context injection
var routeHandler func(echo.Context) error
if config.Handler != nil {
routeHandler = func(c echo.Context) error {
return config.Handler(c, openAPIContext)
}
} else if config.SimpleHandler != nil {
routeHandler = config.SimpleHandler
}
route := echo.Route{
Name: config.Name,
Method: config.Method,
Path: config.Path,
Middlewares: config.Middlewares,
Handler: routeHandler,
}
// Add route to echo router
grp := r.Base()
_, err := grp.AddRoute(route)
if err != nil {
return err
}
// Add operation to OpenAPI schema (convert Echo path syntax to OpenAPI syntax)
openAPIPath := convertEchoPathToOpenAPI(config.Path)
r.OAS.AddOperation(openAPIPath, config.Method, operation)
return nil
}
// AddGraphQLToOpenAPI adds the GraphQL endpoint to the OpenAPI specification
func (r *Router) AddGraphQLToOpenAPI() {
// Create GraphQL request schema
queryProp := openapi3.NewStringSchema()
queryProp.Description = "The GraphQL query string"
variablesProp := openapi3.NewObjectSchema()
variablesProp.Description = "A JSON object containing variables for the query"
operationNameProp := openapi3.NewStringSchema()
operationNameProp.Description = "The name of the operation to execute (optional)"
requestSchema := openapi3.NewObjectSchema()
requestSchema.WithProperty("query", queryProp)
requestSchema.WithProperty("variables", variablesProp)
requestSchema.WithProperty("operationName", operationNameProp)
requestSchema.Example = map[string]any{
"query": "query GetBooks {\n books {\n id\n title\n }\n}",
"variables": map[string]any{},
}
// Create GraphQL response schema
dataProp := openapi3.NewObjectSchema()
dataProp.Description = "The data returned by the GraphQL operation"
errorItem := openapi3.NewObjectSchema()
errorItem.Description = "An array of error objects if the operation failed"
errorsProp := openapi3.NewArraySchema()
errorsProp.WithItems(errorItem)
responseSchema := openapi3.NewObjectSchema()
responseSchema.WithProperty("data", dataProp)
responseSchema.WithProperty("errors", errorsProp)
// Create the GraphQL operation
operation := openapi3.NewOperation()
operation.OperationID = "GraphQLQuery"
operation.Summary = "GraphQL Endpoint"
operation.Description = "Handles all GraphQL queries, mutations, and subscriptions"
operation.Tags = []string{"graphql"}
// Create the GraphQLHistory operation
operationHistory := openapi3.NewOperation()
operationHistory.OperationID = "GraphQLQueryHistory"
operationHistory.Summary = "GraphQL History Endpoint"
operationHistory.Description = "Handles all GraphQL queries for historical data"
operationHistory.Tags = []string{"graphql", "history", "audit logs"}
// Add request body
requestBody := openapi3.NewRequestBody()
requestBody.Required = true
requestBody.Description = "GraphQL query request"
requestBody.WithJSONSchema(requestSchema)
operation.RequestBody = &openapi3.RequestBodyRef{Value: requestBody}
operationHistory.RequestBody = &openapi3.RequestBodyRef{Value: requestBody}
// Add response
response := openapi3.NewResponse()
response.WithDescription("Successful GraphQL response")
response.WithJSONSchema(responseSchema)
operation.AddResponse(200, response) //nolint:mnd
operationHistory.AddResponse(200, response) //nolint:mnd
// Add the operation to the OpenAPI spec
r.OAS.AddOperation("/query", "POST", operation)
r.OAS.AddOperation("/history/query", "POST", operationHistory)
}
// RegisterRoutes with the echo routers - Router is defined within openapi.go
func RegisterRoutes(router *Router) error {
// base middleware for all routes that does not included additional middleware
baseMW = baseMiddleware(router)
// Middleware for authenticated endpoints
authMW = authMiddleware(router)
// Default middleware for other routes which includes additional middleware
mw = defaultMiddleware(router)
// routeHandlers that take the router and handler as input
routeHandlers := []any{
registerReadinessHandler,
registerForgotPasswordHandler,
registerVerifyHandler,
registerResetPasswordHandler,
registerResendEmailHandler,
registerRegisterHandler,
registerVerifySubscribeHandler,
registerRefreshHandler,
registerJwksWellKnownHandler,
registerInviteHandler,
registerGithubLoginHandler,
registerGithubCallbackHandler,
registerGoogleLoginHandler,
registerGoogleCallbackHandler,
registerWebauthnRegistrationHandler,
registerWebauthnVerificationsHandler,
registerWebauthnAuthenticationHandler,
registerWebauthnAuthVerificationHandler,
registerUserInfoHandler,
registerOAuthRegisterHandler,
registerIntegrationAuthStartHandler,
registerIntegrationAuthCallbackHandler,
registerStaticWebhookRoutes,
registerIntegrationProvidersHandler,
registerIntegrationConfigHandler,
registerIntegrationDisconnectHandler,
registerIntegrationOperationHandler,
registerSwitchRoute,
registerLivenessHandler,
registerSecurityTxtHandler,
registerRobotsHandler,
registerFaviconHandler,
registerOpenAPIHandler,
registerLoginHandler,
registerAccountAccessHandler,
registerAccountRolesHandler,
registerAccountRolesMeHandler,
registerAccountRolesOrganizationHandler,
registerAccountFeaturesHandler,
register2faHandler,
registerExampleCSVHandler,
registerWebAuthnWellKnownHandler,
registerAcmeSolverHandler,
registerCSRFHandler,
registerWebfingerHandler,
registerSSOLoginHandler,
registerSSOCallbackHandler,
registerSSOTokenAuthorizeHandler,
registerSSOTokenCallbackHandler,
registerTrustCenterAnonymousJWTHandler,
registerQuestionnaireHandler,
registerQuestionnaireSubmitHandler,
registerResendQuestionnaireHandler,
registerStartImpersonationHandler,
registerEndImpersonationHandler,
registerProductCatalogHandler,
registerFileDownloadHandler,
registerIntegrationWebhookHandler,
registerSCIMRoutes,
registerEmailTestSendHandler,
registerScopesHandler,
registerOrganizationRolesHandler,
registerRolesHandler,
registerMSFTIdentityWellKnownHandler,
// JOB Runners
// TODO(adelowo): at some point in the future, maybe we should extract these into
// it's own service/binary
registerJobRunnerRegistrationHandler,
}
if router.Handler.CloudflareConfig.Enabled {
routeHandlers = append(routeHandlers, registerCloudflareSnapshotHandler)
}
// Register the Stripe webhook endpoint only when the entitlements
// client has been configured. This ensures the server can run without
// requiring Stripe credentials or webhook support
if router.Handler != nil && router.Handler.Entitlements != nil {
routeHandlers = append(routeHandlers, registerWebhookHandler)
}
if router.LocalFilePath != "" {
routeHandlers = append(routeHandlers, registerUploadsHandler)
}
for _, route := range routeHandlers {
if err := route.(func(*Router) error)(router); err != nil {
return err
}
}
// Add GraphQL endpoint to OpenAPI specification
router.AddGraphQLToOpenAPI()
return nil
}
// baseMiddleware returns the base middleware for the router, which includes the transaction middleware
// this isn't used directly in the router register, instead its combined with other middleware functions below
// to include the additional middleware
func baseMiddleware(router *Router) []echo.MiddlewareFunc {
mw := []echo.MiddlewareFunc{}
// add transaction middleware
transactionConfig := transaction.Client{
EntDBClient: router.Handler.DBClient,
}
mimeMiddleware := mime.NewWithConfig(mime.Config{DefaultContentType: httpsling.ContentTypeJSONUTF8})
return append(mw, mimeMiddleware, transactionConfig.Middleware)
}
// authMiddleware returns the middleware for the router that is used on authenticated routes
// it includes the transaction middleware, the auth middleware, and any additional middleware
// after the auth middleware
func authMiddleware(router *Router) []echo.MiddlewareFunc {
mw := baseMW
// add the impersonation middleware to identify and validate impersonated requests
mw = append(mw, impersonationMiddleware(router))
// add the auth middleware
mw = append(mw, router.Handler.AuthMiddleware...)
// add system admin user context middleware (after auth, so we know if user is system admin)
mw = append(mw, impersonation.SystemAdminUserContextMiddleware())
// append any additional middleware after the auth middleware (includes csrf)
return append(mw, router.Handler.AdditionalMiddleware...)
}
// impersonationMiddleware returns the middleware for the router that is used on
// authenticated routes. it identifies impersonated requests and the user impersonating
// and checks access
func impersonationMiddleware(router *Router) echo.MiddlewareFunc {
mw := impersonation.New(router.Handler.TokenManager)
return mw.Process
}
// defaultMiddleware returns the default middleware for the router to be used
// on all unauthenticated + unrestricted routes
func defaultMiddleware(router *Router) []echo.MiddlewareFunc {
mw := baseMW
// this is the default middleware that is applied to all routes
// it includes the transaction middleware and any additional middleware (includes csrf)
return append(mw, router.Handler.AdditionalMiddleware...)
}