-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
255 lines (212 loc) · 7.71 KB
/
main.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
/*
* This file is part of Windermere (EGIL SCIM Server).
*
* Copyright (C) 2019-2021 Föreningen Sambruk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"context"
"crypto/tls"
"flag"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/Sambruk/windermere/windermere"
"github.com/joesiltberg/bowness/fedtls"
"github.com/joesiltberg/bowness/server"
"github.com/spf13/viper"
"golang.org/x/time/rate"
)
func must(err error) {
if err != nil {
log.Fatal(err.Error())
}
}
// Verifies that certain parameters are set in the configuration file
func verifyRequired(keys ...string) {
for _, key := range keys {
if !viper.IsSet(key) {
log.Fatalf("Missing required configuration setting: %s", key)
}
}
}
// Convenience method for getting a configuration parameter that
// specifies a duration in seconds.
func configuredSeconds(setting string) time.Duration {
return time.Duration(viper.GetInt(setting)) * time.Second
}
// Blocks until we get a signal to shut down
func waitForShutdownSignal() {
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
<-signals
}
// Configuration parameters
const (
CNFMDURL = "MetadataURL"
CNFMDDefaultCacheTTL = "MetadataDefaultCacheTTL"
CNFMDNetworkRetry = "MetadataNetworkRetry"
CNFMDBadContentRetry = "MetadataBadContentRetry"
CNFMDCachePath = "MetadataCachePath"
CNFReadHeaderTimeout = "ReadHeaderTimeout"
CNFReadTimeout = "ReadTimeout"
CNFWriteTimeout = "WriteTimeout"
CNFIdleTimeout = "IdleTimeout"
CNFBackendTimeout = "BackendTimeout"
CNFEnableLimiting = "EnableLimiting"
CNFLimitRequestsPerSecond = "LimitRequestsPerSecond"
CNFLimitBurst = "LimitBurst"
CNFStorageType = "StorageType"
CNFStorageSource = "StorageSource"
CNFAccessLogPath = "AccessLogPath"
CNFJWKSPath = "JWKSPath"
CNFCert = "Cert"
CNFKey = "Key"
CNFListenAddress = "ListenAddress"
CNFAdminListenAddress = "AdminListenAddress"
CNFMDEntityID = "MetadataEntityID"
CNFMDBaseURI = "MetadataBaseURI"
CNFMDOrganization = "MetadataOrganization"
CNFMDOrganizationID = "MetadataOrganizationID"
)
func main() {
// Configuration defaults
defaults := map[string]interface{}{
CNFMDURL: "https://fed.skolfederation.se/prod/md/kontosynk.jws",
CNFMDDefaultCacheTTL: 3600,
CNFMDNetworkRetry: 60,
CNFMDBadContentRetry: 3600,
CNFReadHeaderTimeout: 5,
CNFReadTimeout: 20,
CNFWriteTimeout: 40,
CNFIdleTimeout: 60,
CNFBackendTimeout: 30,
CNFEnableLimiting: false,
CNFLimitRequestsPerSecond: 10.0,
CNFLimitBurst: 50,
CNFStorageType: "file",
CNFStorageSource: "SS12000.json",
CNFAccessLogPath: "",
CNFAdminListenAddress: "",
}
for key, value := range defaults {
viper.SetDefault(key, value)
}
flag.Parse()
if flag.NArg() < 1 {
log.Fatal("Missing configuration file path")
}
configPath := flag.Arg(0)
viper.SetConfigFile(configPath)
must(viper.ReadInConfig())
verifyRequired(CNFJWKSPath, CNFMDCachePath, CNFCert, CNFKey, CNFListenAddress,
CNFMDEntityID, CNFMDBaseURI, CNFMDOrganization, CNFMDOrganizationID)
// Setup federated TLS metadata store
mdstore := fedtls.NewMetadataStore(
viper.GetString(CNFMDURL),
viper.GetString(CNFJWKSPath),
viper.GetString(CNFMDCachePath),
fedtls.DefaultCacheTTL(configuredSeconds(CNFMDDefaultCacheTTL)),
fedtls.NetworkRetry(configuredSeconds(CNFMDNetworkRetry)),
fedtls.BadContentRetry(configuredSeconds(CNFMDBadContentRetry)))
certFile := viper.GetString(CNFCert)
keyFile := viper.GetString(CNFKey)
// The TLS config manager is used by the tls.Listener below to configure
// TLS according to the TLS federation.
mdTLSConfigManager, err := server.NewMetadataTLSConfigManager(certFile, keyFile, mdstore)
if err != nil {
log.Fatalf("Failed to create TLS configuration: %v", err)
}
// Windermere needs a function to get the currently authenticated
// SCIM tenant from the current Context.
tenantGetter := func(c context.Context) string {
return server.NormalizedEntityIDFromContext(c)
}
// Create the Windermere SCIM handler
wind, err := windermere.New(viper.GetString(CNFStorageType), viper.GetString(CNFStorageSource), tenantGetter)
if err != nil {
log.Fatalf("Failed to initialize Windermere: %v", err)
}
// Setup various middlware handlers between Windermere and the http.Server
var handler http.Handler
handler = wind
enableLimiting := viper.GetBool(CNFEnableLimiting)
if enableLimiting {
handler = server.Limiter(handler,
rate.Limit(viper.GetFloat64(CNFLimitRequestsPerSecond)),
viper.GetInt(CNFLimitBurst))
}
beTimeout := configuredSeconds(CNFBackendTimeout)
if beTimeout >= 1*time.Second {
handler = http.TimeoutHandler(handler, beTimeout, "Backend timeout")
}
accessLogPath := viper.GetString(CNFAccessLogPath)
if accessLogPath != "" {
handler = accessLogHandler(handler, accessLogPath, tenantGetter)
}
// Create the HTTP server
srv := &http.Server{
// Wrap the HTTP handler with authentication middleware.
Handler: server.AuthMiddleware(handler, mdstore),
// In order to use the authentication middleware, the server needs
// to have a ConnContext configured so the middleware can access
// connection specific information.
ConnContext: server.ContextModifier(),
ReadHeaderTimeout: configuredSeconds(CNFReadHeaderTimeout),
ReadTimeout: configuredSeconds(CNFReadTimeout),
WriteTimeout: configuredSeconds(CNFWriteTimeout),
IdleTimeout: configuredSeconds(CNFIdleTimeout),
}
// Set up a TLS listener with certificate authorities loaded from
// federation metadata (and dynamically updated as metadata gets refreshed).
address := viper.GetString(CNFListenAddress)
listener, err := tls.Listen("tcp", address, mdTLSConfigManager.Config())
if err != nil {
log.Fatalf("Failed to listen to %s (%v)", address, err)
}
// Start the main HTTP server
go func() {
err := srv.Serve(listener)
if err != http.ErrServerClosed {
log.Fatalf("Unexpected server exit: %v", err)
}
}()
// Possibly start the admin HTTP server
adminAddress := viper.GetString(CNFAdminListenAddress)
if adminAddress != "" {
http.Handle("/metadata", metadataHandler(certFile,
viper.GetString(CNFMDEntityID), viper.GetString(CNFMDBaseURI),
viper.GetString(CNFMDOrganization), viper.GetString(CNFMDOrganizationID)))
go func() {
log.Println(http.ListenAndServeTLS(adminAddress, certFile, keyFile, nil))
}()
}
waitForShutdownSignal()
log.Printf("Shutting down, waiting for active requests to finish...")
err = srv.Shutdown(context.Background())
if err != nil {
log.Printf("Failed to gracefully shutdown server: %v", err)
}
err = wind.Shutdown()
if err != nil {
log.Printf("Failed to gracefully shutdown Windermere: %v", err)
}
log.Printf("Server closed, waiting for metadata store to close...")
mdstore.Quit()
log.Printf("Done.")
}