forked from getarcaneapp/arcane
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter_bootstrap.go
More file actions
207 lines (182 loc) · 6.78 KB
/
router_bootstrap.go
File metadata and controls
207 lines (182 loc) · 6.78 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
package bootstrap
import (
"context"
"log/slog"
"path"
"strings"
"github.com/gin-gonic/gin"
sloggin "github.com/samber/slog-gin"
"github.com/getarcaneapp/arcane/backend/frontend"
"github.com/getarcaneapp/arcane/backend/internal/api"
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/huma"
"github.com/getarcaneapp/arcane/backend/internal/huma/handlers"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
"github.com/getarcaneapp/arcane/types"
)
var (
registerPlaywrightRoutes []func(apiGroup *gin.RouterGroup, services *Services)
registerBuildableRoutes []func(apiGroup *gin.RouterGroup, services *Services)
)
var loggerSkipPatterns = []string{
"POST /api/tunnel/poll",
"GET /api/environments/*/ws/containers/*/logs",
"GET /api/environments/*/ws/containers/*/stats",
"GET /api/environments/*/ws/containers/*/terminal",
"GET /api/environments/*/ws/projects/*/logs",
"GET /api/environments/*/ws/system/stats",
"GET /_app/*",
"GET /img",
"GET /api/fonts/sans",
"GET /api/fonts/mono",
"GET /api/fonts/serif",
"GET /api/health",
"HEAD /api/health",
}
func shouldLogRequest(c *gin.Context) bool {
mp := c.Request.Method + " " + c.Request.URL.Path
for _, pat := range loggerSkipPatterns {
if pat == mp {
return false
}
if before, ok := strings.CutSuffix(pat, "/*"); ok {
if strings.HasPrefix(mp, before) {
return false
}
}
if ok, _ := path.Match(pat, mp); ok {
return false
}
if strings.HasSuffix(pat, "/") && strings.HasPrefix(mp, pat) {
return false
}
}
return true
}
func createAuthValidator(appServices *Services) middleware.AuthValidator {
return func(ctx context.Context, c *gin.Context) bool {
// Check for API key authentication
if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {
// User-owned API key
if user, err := appServices.ApiKey.ValidateApiKey(ctx, apiKey); err == nil && user != nil {
return true
}
// Environment bootstrap key (user_id = NULL): used by the proxy when forwarding
// requests to a remote env whose apiUrl resolves back to this manager.
if _, err := appServices.ApiKey.GetEnvironmentByApiKey(ctx, apiKey); err == nil {
return true
}
return false
}
// Check for Bearer token authentication
token := ""
if auth := c.GetHeader("Authorization"); strings.HasPrefix(auth, "Bearer ") {
token = strings.TrimPrefix(auth, "Bearer ")
} else if cookieToken, err := cookie.GetTokenCookie(c); err == nil && cookieToken != "" {
token = cookieToken
}
if token == "" {
return false
}
user, err := appServices.Auth.VerifyToken(ctx, token)
return err == nil && user != nil
}
}
func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services) (*gin.Engine, *edge.TunnelServer) {
if cfg.Environment == "production" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
router := gin.New()
router.Use(gin.Recovery())
router.Use(sloggin.NewWithConfig(slog.Default(), sloggin.Config{
Filters: []sloggin.Filter{shouldLogRequest},
}))
authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).
WithApiKeyValidator(appServices.ApiKey).
WithEnvironmentAccessTokenResolver(appServices.Environment)
corsMiddleware := middleware.NewCORSMiddleware(cfg).Add()
router.Use(corsMiddleware)
apiGroup := router.Group("/api")
tunnelRegistry := edge.NewTunnelRegistry()
edge.SetDefaultRegistry(tunnelRegistry)
envResolver := func(ctx context.Context, id string) (string, *string, bool, error) {
env, err := appServices.Environment.GetEnvironmentByID(ctx, id)
if err != nil || env == nil {
return "", nil, false, err
}
return env.ApiUrl, env.AccessToken, env.Enabled, nil
}
// Register public webhook trigger endpoint before auth middleware (token in URL is the sole auth)
handlers.RegisterWebhookTrigger(apiGroup, appServices.Webhook) //nolint:contextcheck
apiGroup.Use(middleware.NewEnvProxyMiddlewareWithParam(
types.LOCAL_DOCKER_ENVIRONMENT_ID,
"id",
envResolver,
createAuthValidator(appServices),
))
humaServices := &huma.Services{
User: appServices.User,
Auth: appServices.Auth,
Oidc: appServices.Oidc,
ApiKey: appServices.ApiKey,
AppImages: appServices.AppImages,
Font: appServices.Font,
Project: appServices.Project,
Event: appServices.Event,
Version: appServices.Version,
Environment: appServices.Environment,
Settings: appServices.Settings,
JobSchedule: appServices.JobSchedule,
SettingsSearch: appServices.SettingsSearch,
ContainerRegistry: appServices.ContainerRegistry,
Template: appServices.Template,
Docker: appServices.Docker,
Image: appServices.Image,
ImageUpdate: appServices.ImageUpdate,
Build: appServices.Build,
BuildWorkspace: appServices.BuildWorkspace,
Volume: appServices.Volume,
Container: appServices.Container,
Network: appServices.Network,
Port: appServices.Port,
Swarm: appServices.Swarm,
Notification: appServices.Notification,
Apprise: appServices.Apprise,
Updater: appServices.Updater,
CustomizeSearch: appServices.CustomizeSearch,
System: appServices.System,
SystemUpgrade: appServices.SystemUpgrade,
GitRepository: appServices.GitRepository,
GitOpsSync: appServices.GitOpsSync,
Webhook: appServices.Webhook,
Vulnerability: appServices.Vulnerability,
Dashboard: appServices.Dashboard,
Config: cfg,
}
_ = huma.SetupAPI(router, apiGroup, cfg, humaServices)
for _, register := range registerBuildableRoutes {
register(apiGroup, appServices)
}
api.RegisterDiagnosticsRoutes(apiGroup, authMiddleware, api.DefaultWebSocketMetrics()) //nolint:contextcheck
// Remaining Gin handlers (WebSocket/streaming)
api.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, authMiddleware, cfg) //nolint:contextcheck
// Register edge tunnel endpoint for manager to accept agent connections
// This is only registered when NOT in agent mode (i.e., running as manager)
var tunnelServer *edge.TunnelServer
if !cfg.AgentMode {
tunnelServer = registerEdgeTunnelRoutes(ctx, cfg, apiGroup, appServices)
}
if cfg.Environment != "production" {
for _, registerFunc := range registerPlaywrightRoutes {
registerFunc(apiGroup, appServices)
}
}
if err := frontend.RegisterFrontend(router); err != nil {
_, _ = gin.DefaultErrorWriter.Write([]byte("Failed to register frontend: " + err.Error() + "\n"))
}
return router, tunnelServer
}