-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.go
343 lines (297 loc) · 9.66 KB
/
handler.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
// Copyright (c) ClaceIO, LLC
// SPDX-License-Identifier: Apache-2.0
package server
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/claceio/clace/internal/utils"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
const (
VARY_HEADER = "Vary"
)
var (
COMPRESSION_ENABLED_MIME_TYPES = []string{
"text/html",
"text/css",
"text/plain",
"text/xml",
"text/x-component",
"text/javascript",
"application/x-javascript",
"application/javascript",
"application/json",
"application/manifest+json",
"application/vnd.api+json",
"application/xml",
"application/xhtml+xml",
"application/rss+xml",
"application/atom+xml",
"application/vnd.ms-fontobject",
"application/x-font-ttf",
"application/x-font-opentype",
"application/x-font-truetype",
"image/svg+xml",
"image/x-icon",
"image/vnd.microsoft.icon",
"font/ttf",
"font/eot",
"font/otf",
"font/opentype",
}
)
const (
REALM = "clace"
)
type Handler struct {
*utils.Logger
config *utils.ServerConfig
server *Server
router *chi.Mux
}
func panicRecovery(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil && rvr != http.ErrAbortHandler {
msg := fmt.Sprint(rvr)
//logger.Error().Str("recover", msg).Str("trace", string(debug.Stack())).Msg("Error during request processing")
// TODO log
http.Error(w, msg, http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// NewUDSHandler creates a new handler for admin APIs over the unix domain socket
func NewUDSHandler(logger *utils.Logger, config *utils.ServerConfig, server *Server) *Handler {
router := chi.NewRouter()
router.Use(panicRecovery)
handler := &Handler{
Logger: logger,
config: config,
server: server,
router: router,
}
router.Use(middleware.CleanPath)
router.Mount(utils.INTERNAL_URL_PREFIX, handler.serveInternal(false))
// App APIs are not mounted over UDS
// No authentication middleware is added for UDS, the unix file permissions are used
return handler
}
// NewTCPHandler creates a new handler for HTTP/HTTPS requests. App API's are mounted amd
// authentication is enabled. It also mounts the internal APIs if admin over TCP is enabled
func NewTCPHandler(logger *utils.Logger, config *utils.ServerConfig, server *Server) *Handler {
router := chi.NewRouter()
router.Use(panicRecovery)
handler := &Handler{
Logger: logger,
config: config,
server: server,
router: router,
}
router.Use(AddVaryHeader)
router.Use(middleware.CleanPath)
router.Use(middleware.Compress(5, COMPRESSION_ENABLED_MIME_TYPES...))
if config.Security.AdminOverTCP {
// Mount the internal API's only if admin over TCP is enabled
logger.Warn().Msg("Admin API access over TCP is enabled, enable 2FA for admin user account")
router.Mount(utils.INTERNAL_URL_PREFIX, handler.serveInternal(true))
} else {
router.Mount(utils.INTERNAL_URL_PREFIX, http.NotFoundHandler()) // reserve the path
}
router.HandleFunc("/*", handler.callApp)
return handler
}
func (h *Handler) callApp(w http.ResponseWriter, r *http.Request) {
h.Debug().Str("method", r.Method).Str("url", r.URL.String()).Msg("App Received request")
domain := r.Host
if strings.Contains(domain, ":") {
domain = strings.Split(domain, ":")[0]
}
matchedApp, err := h.server.MatchApp(domain, r.URL.Path)
if err != nil {
h.Error().Err(err).Str("path", r.URL.Path).Msg("No app matched request")
http.Error(w, "No matching app found", http.StatusNotFound)
return
}
h.server.serveApp(w, r, matchedApp)
}
func (h *Handler) serveInternal(enableBasicAuth bool) http.Handler {
// These API's are mounted at /_clace
r := chi.NewRouter()
// Get app
r.Get("/app", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.getApp)
}))
r.Get("/app/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.getApp)
}))
// Create app
r.Post("/app", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.createApp)
}))
r.Post("/app/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.createApp)
}))
// Delete app
r.Delete("/app", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.deleteApp)
}))
r.Delete("/app/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.deleteApp)
}))
// API to audit the plugin usage and permissions for the app
r.Post("/audit", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.auditApp)
}))
r.Post("/audit/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.apiHandler(w, r, enableBasicAuth, h.auditApp)
}))
return r
}
func normalizePath(path string) string {
if len(path) == 0 || path[0] != '/' {
path = "/" + path
}
if len(path) > 1 {
path = strings.TrimRight(path, "/")
}
return path
}
func (h *Handler) apiHandler(w http.ResponseWriter, r *http.Request, enableBasicAuth bool, apiFunc func(r *http.Request) (any, error)) {
if enableBasicAuth {
authStatus := h.server.authHandler.authenticate(r.Header.Get("Authorization"))
if !authStatus {
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, REALM))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
resp, err := apiFunc(r)
h.Trace().Str("method", r.Method).Str("url", r.URL.String()).Interface("resp", resp).Err(err).Msg("API Received request")
if err != nil {
if reqError, ok := err.(utils.RequestError); ok {
w.Header().Add("Content-Type", "application/json")
errStr, _ := json.Marshal(reqError)
http.Error(w, string(errStr), reqError.Code)
return
}
h.Error().Err(err).Msg("error in api func call")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if resp == nil {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Add("Content-Type", "application/json")
h.Info().Msgf("response: %+v", resp)
err = json.NewEncoder(w).Encode(resp)
if err != nil {
h.Error().Err(err).Msg("error encoding response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *Handler) getApp(r *http.Request) (any, error) {
appPath := chi.URLParam(r, "*")
domain := r.URL.Query().Get("domain")
appPath = normalizePath(appPath)
app, err := h.server.GetApp(utils.CreateAppPathDomain(appPath, domain), false)
if err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusNotFound)
}
return app.AppEntry, nil
}
func (h *Handler) createApp(r *http.Request) (any, error) {
appPath := chi.URLParam(r, "*")
domain := r.URL.Query().Get("domain")
approveStr := r.URL.Query().Get("approve")
approve := false
if approveStr != "" {
var err error
if approve, err = strconv.ParseBool(approveStr); err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusBadRequest)
}
}
appPath = normalizePath(appPath)
matchedApp, err := h.server.MatchAppForDomain(domain, appPath)
if err != nil {
return nil, utils.CreateRequestError(
fmt.Sprintf("error matching app: %s", err), http.StatusInternalServerError)
}
if matchedApp != "" {
return nil, utils.CreateRequestError(
fmt.Sprintf("App already exists at %s", matchedApp), http.StatusBadRequest)
}
var appRequest utils.CreateAppRequest
err = json.NewDecoder(r.Body).Decode(&appRequest)
if err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusBadRequest)
}
var appEntry utils.AppEntry
appEntry.Path = appPath
appEntry.Domain = domain
appEntry.SourceUrl = appRequest.SourceUrl
appEntry.IsDev = appRequest.IsDev
appEntry.AutoSync = appRequest.AutoSync
appEntry.AutoReload = appRequest.AutoReload
if appRequest.AppAuthn != "" {
authType := utils.AppAuthnType(strings.ToLower(string(appRequest.AppAuthn)))
if authType != utils.AppAuthnDefault && authType != utils.AppAuthnNone {
return nil, utils.CreateRequestError("Invalid auth type: "+string(authType), http.StatusBadRequest)
}
appEntry.Rules.AuthnType = utils.AppAuthnType(strings.ToLower(string(appRequest.AppAuthn)))
} else {
appEntry.Rules.AuthnType = utils.AppAuthnDefault
}
auditResult, err := h.server.AddApp(&appEntry, approve)
if err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusBadRequest)
}
return auditResult, nil
}
func (h *Handler) deleteApp(r *http.Request) (any, error) {
appPath := chi.URLParam(r, "*")
domain := r.URL.Query().Get("domain")
appPath = normalizePath(appPath)
err := h.server.DeleteApp(utils.CreateAppPathDomain(appPath, domain))
if err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusBadRequest)
}
h.Trace().Str("appPath", appPath).Msg("Deleted app successfully")
return nil, nil
}
func (h *Handler) auditApp(r *http.Request) (any, error) {
appPath := chi.URLParam(r, "*")
domain := r.URL.Query().Get("domain")
approveStr := r.URL.Query().Get("approve")
approve := false
if approveStr != "" {
var err error
if approve, err = strconv.ParseBool(approveStr); err != nil {
return nil, utils.CreateRequestError(err.Error(), http.StatusBadRequest)
}
}
appPath = normalizePath(appPath)
auditResult, err := h.server.AuditApp(utils.CreateAppPathDomain(appPath, domain), approve)
return auditResult, err
}
func AddVaryHeader(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
value := w.Header().Get(VARY_HEADER)
if value != "" {
value += ", HX-Request"
} else {
value = "HX-Request"
}
w.Header().Add(VARY_HEADER, value)
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}