This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
505 lines (448 loc) · 12.6 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
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
//go:build !development
package main
import (
"bytes"
"context"
"crypto/rsa"
"crypto/tls"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"time"
log "github.com/sirupsen/logrus"
"github.com/crewjam/saml"
"github.com/crewjam/saml/samlsp"
"github.com/getsentry/sentry-go"
sentryhttp "github.com/getsentry/sentry-go/http"
"github.com/go-chi/chi/v5"
"github.com/go-co-op/gocron"
"github.com/gorilla/csrf"
_ "github.com/jackc/pgx/v4/stdlib"
)
type StartRequest struct {
Attributes []string `json:"attributes"`
Continuation string `json:"continuation"`
AttributeURL *string `json:"attr_url"`
}
type StartResponse struct {
ClientURL string `json:"client_url"`
}
func (c *Configuration) handleDigidCancelError(w http.ResponseWriter, r *http.Request, err error) {
if _, ok := err.(*saml.InvalidResponseError); ok {
log.Printf("WARNING: received cancel saml response")
returnURL := *c.WidgetURL
returnQuery := returnURL.Query()
returnQuery.Set("notification", "cancel")
returnURL.RawQuery = returnQuery.Encode()
http.Redirect(w, r, returnURL.String(), 302)
} else {
log.Printf("ERROR: %s", err)
returnURL := *c.WidgetURL
returnQuery := returnURL.Query()
returnQuery.Set("notification", "error")
returnURL.RawQuery = returnQuery.Encode()
http.Redirect(w, r, returnURL.String(), 302)
}
}
// Start Verder Helpen authentication session
func (c *Configuration) startSession(w http.ResponseWriter, r *http.Request) {
log.Debug("Starting session")
// Extract request
body, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
var request StartRequest
err = json.Unmarshal(body, &request)
if err != nil {
w.WriteHeader(400)
log.Warn(err)
return
}
if c.BRPServer != "" {
// Validate requested attributes
for _, attribute := range request.Attributes {
_, ok := c.AttributeMapping[attribute]
if !ok {
w.WriteHeader(400)
log.WithFields(log.Fields{
"attribute": attribute,
}).Warn("Requested attribute not in mapping")
return
}
}
}
// Create a new session in the database
encodedAttributes, err := json.Marshal(request.Attributes)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
session, err := c.SessionManager.NewSession(string(encodedAttributes), request.Continuation, request.AttributeURL)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
// And instruct the core appropriately
clientURL := *c.ServerURL
clientURL.Path = path.Join(clientURL.Path, "session", session.id)
response, err := json.Marshal(StartResponse{ClientURL: clientURL.String()})
w.WriteHeader(200)
w.Write(response)
}
type AuthResult struct {
status string
attributes map[string]string
}
// Handle an actual end-user login
func (c *Configuration) doLogin(w http.ResponseWriter, r *http.Request) {
// Fetch corresponding Verder Helpen session
id := chi.URLParam(r, "sessionid")
session, err := c.SessionManager.GetSession(id)
if err != nil {
w.WriteHeader(400)
log.Warn(err)
return
}
var attributes []string
err = json.Unmarshal([]byte(session.attributes), &attributes)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
authnContextClass := samlsp.AttributeFromContext(r.Context(), "AuthnContextClassRef")
if !CompareAuthnContextClass(c.AuthnContextClassRef, authnContextClass) {
w.WriteHeader(500)
log.WithFields(log.Fields{
"class": authnContextClass,
}).Error("AuthnContextClass too low")
return
}
// Extract attributes from BRP:
samlsession := samlsp.SessionFromContext(r.Context()).(*SamlSession)
bsn := samlsession.attributes.Get("NameID")
if bsn[:9] != "s00000000" {
w.WriteHeader(500)
log.Error("Unexpected sectoral code", bsn[:9])
return
}
var attributeResult map[string]string
if c.BRPServer != "" {
// Replace BSN with test BSN in preprod environment
altbsn, ok := c.TestBSNMapping[bsn[10:]]
if ok {
bsn = "s00000000:" + altbsn
}
attributeResult, err = GetBRPAttributes(c.BRPServer, bsn[10:], c.AttributeMapping, c.Client, c.CaCerts)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
} else {
attributeResult = map[string]string{
"bsn": bsn[10:],
}
}
// Encode attributes
attributesJSON, err := json.Marshal(attributeResult)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
// Store the information needed for confirmation
err = c.SamlSessionManager.SetVerderHelpenSession(samlsession, id, string(attributesJSON))
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
confirmURL := *c.ServerURL
confirmURL.Path = path.Join(confirmURL.Path, "confirm", id)
http.Redirect(w, r, confirmURL.String(), 302)
}
func (c *Configuration) getConfirm(w http.ResponseWriter, r *http.Request) {
samlsession := samlsp.SessionFromContext(r.Context()).(*SamlSession)
url_sessionid := chi.URLParam(r, "sessionid")
// Get jwt and session id
sessionid, attributeJSON, err := c.SamlSessionManager.GetVerderHelpenSession(samlsession)
if err == samlsp.ErrNoSession {
w.WriteHeader(400)
log.Warn(err)
return
}
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
if url_sessionid != sessionid {
w.WriteHeader(400)
log.Warn("Confirmation received from user for session that is not its most recent")
return
}
// check Verder Helpen session exists
_, err = c.SessionManager.GetSession(sessionid)
if err != nil {
w.WriteHeader(400)
log.Warn(err)
return
}
var attributes map[string]string
err = json.Unmarshal([]byte(attributeJSON), &attributes)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
lang := c.Bundle.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
// translate the attribute keys to the appropriate language
translatedAttributes := map[string]string{}
for k, v := range attributes {
// if the translation for the attribute key is not available, use the key itself
translation := c.Bundle.Translate(lang, "attributes."+k)
translatedAttributes[translation] = v
}
// And show the user the confirmation screen
c.Template.ExecuteTemplate(w, "confirm", map[string]interface{}{
"attributes": translatedAttributes,
"language": lang,
"logoutPath": path.Join("/logout", sessionid),
csrf.TemplateTag: csrf.TemplateField(r),
})
}
func (c *Configuration) doConfirm(w http.ResponseWriter, r *http.Request) {
samlsession := samlsp.SessionFromContext(r.Context()).(*SamlSession)
url_sessionid := chi.URLParam(r, "sessionid")
// Get jwt and session id
sessionid, attributesJSON, err := c.SamlSessionManager.GetVerderHelpenSession(samlsession)
if err == samlsp.ErrNoSession {
w.WriteHeader(400)
log.Warn(err)
return
}
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
if url_sessionid != sessionid {
w.WriteHeader(400)
log.Warn("Confirmation received from user for session that is not its most recent")
return
}
session, err := c.SessionManager.GetSession(sessionid)
if err != nil {
w.WriteHeader(400)
log.Warn(err)
return
}
// Construct authentication result JWT
var attributes map[string]string
err = json.Unmarshal([]byte(attributesJSON), &attributes)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
logoutUrl := *c.InternalURL
logoutUrl.Path = path.Join(logoutUrl.Path, "logout", sessionid)
authToken, err := buildAttributeJWT(attributes, logoutUrl.String(), c.JwtSigningKey, c.JwtEncryptionKey)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
// Log out session before redirecting
err = c.SamlSessionManager.Logout(samlsession.id)
if err != nil {
log.Error("Logout failed: ", err)
// Note, this error shouldn't be propagated to remote
}
// And deliver it appropriately
if session.attributeURL != nil {
response, err := http.Post(*session.attributeURL, "application/jwt", bytes.NewReader([]byte(authToken)))
if err != nil {
// Just log
log.Error(err)
} else {
defer response.Body.Close()
if response.StatusCode >= 300 {
log.Errorf("attribute url failed (%d)\n", response.StatusCode)
}
}
http.Redirect(w, r, session.continuation, 302)
} else {
redirectURL, err := url.Parse(session.continuation)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
redirectQuery := redirectURL.Query()
redirectQuery.Set("result", string(authToken))
redirectURL.RawQuery = redirectQuery.Encode()
http.Redirect(w, r, redirectURL.String(), 302)
}
}
func (c *Configuration) doLogout(w http.ResponseWriter, r *http.Request) {
samlsession := samlsp.SessionFromContext(r.Context()).(*SamlSession)
url_sessionid := chi.URLParam(r, "sessionid")
// Get jwt and session id
sessionid, _, err := c.SamlSessionManager.GetVerderHelpenSession(samlsession)
if err == samlsp.ErrNoSession {
w.WriteHeader(400)
log.Warn(err)
return
}
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
if url_sessionid != sessionid {
w.WriteHeader(400)
log.Warn("Logout received from user for session that is not its most recent")
return
}
// get Verder Helpen session exists
session, err := c.SessionManager.GetSession(sessionid)
if err != nil {
w.WriteHeader(400)
log.Warn(err)
return
}
// get continuation URL before actually logging out
redirectURL, err := url.Parse(session.continuation)
if err != nil {
w.WriteHeader(500)
log.Error(err)
return
}
// Handle logout request
err = c.SamlSessionManager.Logout(samlsession.id)
if err != nil {
log.Error("Logout failed: ", err)
// Note, this error shouldn't be propagated to remote
}
// redirect to redirect URL without result
http.Redirect(w, r, redirectURL.String(), 302)
}
func (c *Configuration) BuildHandler() http.Handler {
// Setup SAML plugin
idpMetadata, err := samlsp.FetchMetadata(context.Background(), http.DefaultClient,
*c.IdpMetadataURL)
if err != nil {
log.Fatal("Failed to download IdP metadata: ", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{c.SamlKeyPair},
}
transport := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: transport}
samlSP, err := samlsp.New(samlsp.Options{
EntityID: c.EntityID,
URL: *c.ServerURL,
Key: c.SamlKeyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: c.SamlKeyPair.Leaf,
HTTPClient: client,
IDPMetadata: idpMetadata,
SignRequest: true,
UseArtifactResponse: true,
RequestedAuthnContext: &saml.RequestedAuthnContext{
Comparison: "minimum",
AuthnContextClassRef: c.AuthnContextClassRef,
},
})
samlSP.Session = &samlsp.CookieSessionProvider{
Name: "samlsession",
Domain: c.ServerURL.Host,
HTTPOnly: true,
Secure: c.ServerURL.Scheme == "https",
SameSite: http.SameSiteLaxMode,
MaxAge: 60 * time.Minute,
Codec: c.SamlSessionManager,
}
samlSP.OnError = c.handleDigidCancelError
// Construct router
r := chi.NewRouter()
if c.SentryDSN != "" {
sentryMiddleware := sentryhttp.New(sentryhttp.Options{})
r.Use(sentryMiddleware.Handle)
}
// csrfMiddleware
csrfMiddleware := csrf.Protect(
c.CsrfAuthKey,
csrf.Path("/"),
)
r.Route("/", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(samlSP.RequireAccount)
r.Get("/session/{sessionid}", c.doLogin)
r.With(csrfMiddleware).Get("/confirm/{sessionid}", c.getConfirm)
r.With(csrfMiddleware).Post("/confirm/{sessionid}", c.doConfirm)
r.With(csrfMiddleware).Post("/logout/{sessionid}", c.doLogout)
})
})
r.Mount("/saml/", samlSP)
r.Route("/internal", func(r chi.Router) {
r.Post("/start_authentication", c.startSession)
})
return r
}
var release string
type SentryLogHook struct{}
func (t *SentryLogHook) Levels() []log.Level {
return []log.Level{
log.PanicLevel,
log.FatalLevel,
log.ErrorLevel,
}
}
func (t *SentryLogHook) Fire(event *log.Entry) error {
sentry_event := sentry.Event{
Message: event.Message,
}
if event.Level == log.ErrorLevel {
sentry_event.Level = sentry.LevelError
} else {
sentry_event.Level = sentry.LevelFatal
}
sentry.CaptureEvent(&sentry_event)
return nil
}
func main() {
configuration := ParseConfiguration()
if configuration.SentryDSN != "" {
// Setup sentry
err := sentry.Init(sentry.ClientOptions{
Dsn: configuration.SentryDSN,
Release: release,
ServerName: "auth-digid",
Environment: os.Getenv("ENVIRONMENT"),
})
if err != nil {
log.Fatal("Error starting sentry: ", err)
}
defer sentry.Recover()
// And hook into logging
log.AddHook(&SentryLogHook{})
}
s := gocron.NewScheduler(time.UTC)
s.Every("1m").Do(func() {
configuration.SamlSessionManager.Cleanup()
configuration.SessionManager.Cleanup()
})
s.StartAsync()
http.Handle("/", configuration.BuildHandler())
http.ListenAndServe(":8000", nil)
}