-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
319 lines (282 loc) · 10.8 KB
/
server.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
package apis
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net/http"
"os"
"time"
"github.com/alwitt/goutils"
"github.com/alwitt/padlock/authenticate"
"github.com/alwitt/padlock/common"
"github.com/alwitt/padlock/match"
"github.com/alwitt/padlock/users"
"github.com/apex/log"
"github.com/gorilla/mux"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
/*
BuildMetricsCollectionServer create server to host metrics collection endpoint
@param httpCfg common.HTTPServerConfig - HTTP server configuration
@param metricsCollector goutils.MetricsCollector - metrics collector
@param collectionEndpoint string - endpoint to expose the metrics on
@param maxRESTRequests int - max number fo parallel requests to support
@returns HTTP server instance
*/
func BuildMetricsCollectionServer(
httpCfg common.HTTPServerConfig,
metricsCollector goutils.MetricsCollector,
collectionEndpoint string,
maxRESTRequests int,
) (*http.Server, error) {
router := mux.NewRouter()
metricsCollector.ExposeCollectionEndpoint(router, collectionEndpoint, maxRESTRequests)
serverListen := fmt.Sprintf(
"%s:%d", httpCfg.ListenOn, httpCfg.Port,
)
httpSrv := &http.Server{
Addr: serverListen,
WriteTimeout: time.Second * time.Duration(httpCfg.Timeouts.WriteTimeout),
ReadTimeout: time.Second * time.Duration(httpCfg.Timeouts.ReadTimeout),
IdleTimeout: time.Second * time.Duration(httpCfg.Timeouts.IdleTimeout),
Handler: h2c.NewHandler(router, &http2.Server{}),
}
return httpSrv, nil
}
// ====================================================================================
// User Management Server
/*
BuildUserManagementServer creates the user management server
@param httpCfg common.HTTPConfig - HTTP server config
@param manager users.Management - core user management logic block
@param validateSupport common.CustomFieldValidator - customer validator support object
@param metrics goutils.HTTPRequestMetricHelper - metric collection agent
@return the http.Server
*/
func BuildUserManagementServer(
httpCfg common.APIServerConfig,
manager users.Management,
validateSupport common.CustomFieldValidator,
metrics goutils.HTTPRequestMetricHelper,
) (*http.Server, error) {
coreHandler, err := defineUserManagementHandler(
httpCfg.APIs.RequestLogging, manager, validateSupport, metrics,
)
if err != nil {
return nil, err
}
livenessHandler := defineUserManagementLivenessHandler(httpCfg.APIs.RequestLogging, manager)
router := mux.NewRouter()
mainRouter := registerPathPrefix(router, httpCfg.APIs.Endpoint.PathPrefix, nil)
livenessRouter := registerPathPrefix(mainRouter, "/liveness", nil)
v1Router := registerPathPrefix(mainRouter, "/v1", nil)
// Role management
roleRouter := registerPathPrefix(v1Router, "/role", map[string]http.HandlerFunc{
"get": coreHandler.ListAllRolesHandler(),
})
_ = registerPathPrefix(roleRouter, "/{roleName}", map[string]http.HandlerFunc{
"get": coreHandler.GetRoleHandler(),
})
// User management
userRouter := registerPathPrefix(v1Router, "/user", map[string]http.HandlerFunc{
"post": coreHandler.DefineUserHandler(),
"get": coreHandler.ListAllUsersHandler(),
})
perUserRouter := registerPathPrefix(userRouter, "/{userID}", map[string]http.HandlerFunc{
"get": coreHandler.GetUserHandler(),
"delete": coreHandler.DeleteUserHandler(),
"put": coreHandler.UpdateUserHandler(),
})
_ = registerPathPrefix(perUserRouter, "/roles", map[string]http.HandlerFunc{
"put": coreHandler.UpdateUserRolesHandler(),
})
// Health check
_ = registerPathPrefix(livenessRouter, "/alive", map[string]http.HandlerFunc{
"get": livenessHandler.AliveHandler(),
})
_ = registerPathPrefix(livenessRouter, "/ready", map[string]http.HandlerFunc{
"get": livenessHandler.ReadyHandler(),
})
// Add logging middleware
v1Router.Use(func(next http.Handler) http.Handler {
return coreHandler.LoggingMiddleware(next.ServeHTTP)
})
livenessRouter.Use(func(next http.Handler) http.Handler {
return livenessHandler.LoggingMiddleware(next.ServeHTTP)
})
serverListen := fmt.Sprintf(
"%s:%d", httpCfg.Server.ListenOn, httpCfg.Server.Port,
)
httpSrv := &http.Server{
Addr: serverListen,
WriteTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.WriteTimeout),
ReadTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.ReadTimeout),
IdleTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.IdleTimeout),
Handler: h2c.NewHandler(router, &http2.Server{}),
}
return httpSrv, nil
}
// ====================================================================================
// Authorization Server
/*
BuildAuthorizationServer creates the authorization server
@param httpCfg common.HTTPConfig - HTTP server config
@param manager users.Management - core user management logic block
@param requestMatcher match.RequestMatch - the request matcher
@param validateSupport common.CustomFieldValidator - customer validator support object
@param checkHeaders common.AuthorizeRequestParamLocConfig - param on which headers to search for
parameters regarding a REST API to authorize.
@param forUnknownUser common.UnknownUserActionConfig - param on how to handle new unknown user
@param metrics goutils.HTTPRequestMetricHelper - metric collection agent
@return the http.Server
*/
func BuildAuthorizationServer(
httpCfg common.APIServerConfig,
manager users.Management,
requestMatcher match.RequestMatch,
validateSupport common.CustomFieldValidator,
checkHeaders common.AuthorizeRequestParamLocConfig,
forUnknownUser common.UnknownUserActionConfig,
metrics goutils.HTTPRequestMetricHelper,
) (*http.Server, error) {
coreHandler, err := defineAuthorizationHandler(
httpCfg.APIs.RequestLogging,
manager,
requestMatcher,
validateSupport,
checkHeaders,
forUnknownUser,
metrics,
)
if err != nil {
return nil, err
}
livenessHandler := defineAuthorizationLivenessHandler(httpCfg.APIs.RequestLogging, manager)
router := mux.NewRouter()
mainRouter := registerPathPrefix(router, httpCfg.APIs.Endpoint.PathPrefix, nil)
livenessRouter := registerPathPrefix(mainRouter, "/liveness", nil)
v1Router := registerPathPrefix(mainRouter, "/v1", nil)
// Authorize
_ = registerPathPrefix(v1Router, "/allow", map[string]http.HandlerFunc{
"get": coreHandler.AllowHandler(),
})
// Health check
_ = registerPathPrefix(livenessRouter, "/alive", map[string]http.HandlerFunc{
"get": livenessHandler.AliveHandler(),
})
_ = registerPathPrefix(livenessRouter, "/ready", map[string]http.HandlerFunc{
"get": livenessHandler.ReadyHandler(),
})
// Add logging middleware
v1Router.Use(func(next http.Handler) http.Handler {
return coreHandler.LoggingMiddleware(next.ServeHTTP)
})
livenessRouter.Use(func(next http.Handler) http.Handler {
return livenessHandler.LoggingMiddleware(next.ServeHTTP)
})
// Add request parameter extract middleware
v1Router.Use(func(next http.Handler) http.Handler {
return coreHandler.ParamReadMiddleware(next.ServeHTTP)
})
serverListen := fmt.Sprintf(
"%s:%d", httpCfg.Server.ListenOn, httpCfg.Server.Port,
)
httpSrv := &http.Server{
Addr: serverListen,
WriteTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.WriteTimeout),
ReadTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.ReadTimeout),
IdleTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.IdleTimeout),
Handler: h2c.NewHandler(router, &http2.Server{}),
}
return httpSrv, nil
}
// ====================================================================================
// Authentication Server
/*
BuildAuthenticationServer creates the authentication server
@param httpCfg common.HTTPConfig - HTTP server config
@param openIDCfg common.OpenIDIssuerConfig - OpenID issuer configuration
@parem performIntrospection bool - whether to perform introspection
@param tokenCache authenticate.TokenCache - cache to reduce number of introspections
@param authnConfig common.AuthenticationConfig - authentication submodule configuration
@param respHeaderParam common.AuthorizeRequestParamLocConfig - config which indicates what
response headers to output the user parameters on.
@param metrics goutils.HTTPRequestMetricHelper - metric collection agent
@return the http.Server
*/
func BuildAuthenticationServer(
httpCfg common.APIServerConfig,
openIDCfg common.OpenIDIssuerConfig,
performIntrospection bool,
tokenCache authenticate.TokenCache,
authnConfig common.AuthenticationConfig,
respHeaderParam common.AuthorizeRequestParamLocConfig,
metrics goutils.HTTPRequestMetricHelper,
) (*http.Server, error) {
// Define custom HTTP client for connecting with OpenID issuer
oidHTTPClient := http.Client{}
// Define the TLS settings if custom CA was provided
if openIDCfg.CustomCA != nil {
caCert, err := os.ReadFile(*openIDCfg.CustomCA)
if err != nil {
log.WithError(err).Errorf("Unable to read %s", *openIDCfg.CustomCA)
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{RootCAs: caCertPool}
oidHTTPClient.Transport = &http.Transport{TLSClientConfig: tlsConfig}
}
oidClient, err := authenticate.DefineOpenIDClient(openIDCfg, &oidHTTPClient)
if err != nil {
return nil, err
}
introspector := authenticate.DefineIntrospector(tokenCache, oidClient.IntrospectToken)
coreHandler, err := defineAuthenticationHandler(
httpCfg.APIs.RequestLogging,
oidClient,
performIntrospection,
introspector,
authnConfig,
respHeaderParam,
metrics,
)
if err != nil {
return nil, err
}
livenessHandler := defineAuthenticationLivenessHandler(httpCfg.APIs.RequestLogging)
router := mux.NewRouter()
mainRouter := registerPathPrefix(router, httpCfg.APIs.Endpoint.PathPrefix, nil)
livenessRouter := registerPathPrefix(mainRouter, "/liveness", nil)
v1Router := registerPathPrefix(mainRouter, "/v1", nil)
// Authentication
_ = registerPathPrefix(v1Router, "/authenticate", map[string]http.HandlerFunc{
"get": coreHandler.AuthenticateHandler(),
})
// Health check
_ = registerPathPrefix(livenessRouter, "/alive", map[string]http.HandlerFunc{
"get": livenessHandler.AliveHandler(),
})
_ = registerPathPrefix(livenessRouter, "/ready", map[string]http.HandlerFunc{
"get": livenessHandler.ReadyHandler(),
})
// Add logging middleware
v1Router.Use(func(next http.Handler) http.Handler {
return coreHandler.LoggingMiddleware(next.ServeHTTP)
})
livenessRouter.Use(func(next http.Handler) http.Handler {
return livenessHandler.LoggingMiddleware(next.ServeHTTP)
})
serverListen := fmt.Sprintf(
"%s:%d", httpCfg.Server.ListenOn, httpCfg.Server.Port,
)
httpSrv := &http.Server{
Addr: serverListen,
WriteTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.WriteTimeout),
ReadTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.ReadTimeout),
IdleTimeout: time.Second * time.Duration(httpCfg.Server.Timeouts.IdleTimeout),
Handler: h2c.NewHandler(router, &http2.Server{}),
}
return httpSrv, nil
}