server.go 20.8 KB
Newer Older
1
package keyshareserver
2
3

import (
4
	"bytes"
5
	"context"
6
7
8
9
10
11
12
13
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"
14
	"time"
15

16
	"github.com/jasonlvhit/gocron"
17
18
19
20
21
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
	irma "github.com/privacybydesign/irmago"
	"github.com/sirupsen/logrus"

22
	"github.com/privacybydesign/irmago/internal/common"
23
	"github.com/privacybydesign/irmago/internal/keysharecore"
24
25
26
27
28
29
30
	"github.com/privacybydesign/irmago/server"
	"github.com/privacybydesign/irmago/server/irmaserver"

	"github.com/go-chi/chi"
)

type SessionData struct {
31
	LastKeyID    irma.PublicKeyIdentifier // last used key, used in signing the issuance message
32
	LastCommitID uint64
33
	expiry       time.Time
34
35
}

36
37
38
39
40
41
// Used to provide context in protocol sessions
type requestAuthorization struct {
	user                  KeyshareUser
	hasValidAuthorization bool
}

42
type Server struct {
43
	// configuration
44
45
	conf *Configuration

46
	// external components
47
	core          *keysharecore.Core
48
49
	sessionserver *irmaserver.Server
	db            KeyshareDB
50
51

	// Scheduler used to clean sessions
52
53
	scheduler     *gocron.Scheduler
	stopScheduler chan<- bool
54

55
	// Session data, keeping track of current keyshare protocol session state for each user
56
57
58
59
60
61
62
	sessions    map[string]*SessionData
	sessionLock sync.Mutex
}

func New(conf *Configuration) (*Server, error) {
	var err error
	s := &Server{
63
64
65
		conf:      conf,
		sessions:  map[string]*SessionData{},
		scheduler: gocron.NewScheduler(),
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
	}

	// Do initial processing of configuration and create keyshare core
	s.core, err = processConfiguration(conf)
	if err != nil {
		return nil, err
	}

	// Load neccessary idemix keys into core, and ensure that future updates
	// to them are processed
	s.LoadIdemixKeys(conf.ServerConfiguration.IrmaConfiguration)
	conf.ServerConfiguration.IrmaConfiguration.UpdateListeners = append(
		conf.ServerConfiguration.IrmaConfiguration.UpdateListeners,
		s.LoadIdemixKeys)

81
	// Setup IRMA session server
82
83
84
85
86
	s.sessionserver, err = irmaserver.New(conf.ServerConfiguration)
	if err != nil {
		return nil, err
	}

87
88
	// Setup DB
	s.db = conf.DB
89

90
91
92
93
	// Setup session cache clearing
	s.scheduler.Every(10).Seconds().Do(s.clearSessions)
	s.stopScheduler = s.scheduler.Start()

94
95
96
	return s, nil
}

97
98
99
100
101
func (s *Server) Stop() {
	s.stopScheduler <- true
	s.sessionserver.Stop()
}

102
// clean up any expired sessions
103
104
105
106
107
108
109
110
111
112
113
func (s *Server) clearSessions() {
	now := time.Now()
	s.sessionLock.Lock()
	defer s.sessionLock.Unlock()
	for k, v := range s.sessions {
		if now.After(v.expiry) {
			delete(s.sessions, k)
		}
	}
}

114
115
func (s *Server) Handler() http.Handler {
	router := chi.NewRouter()
116
117
118

	if s.conf.Verbose >= 2 {
		opts := server.LogOptions{Response: true, Headers: true, From: false, EncodeBinary: true}
119
		router.Use(server.LogMiddleware("keyshareserver", opts))
120
121
	}

122
	// Registration
123
	router.Post("/client/register", s.handleRegister)
124

125
	// Pin logic
126
127
	router.Post("/users/verify/pin", s.handleVerifyPin)
	router.Post("/users/change/pin", s.handleChangePin)
128
129

	// Keyshare sessions
130
131
132
133
134
135
136
	router.Group(func(router chi.Router) {
		router.Use(s.userMiddleware)
		router.Use(s.authorizationMiddleware)
		router.Post("/users/isAuthorized", s.handleValidate)
		router.Post("/prove/getCommitments", s.handleCommitments)
		router.Post("/prove/getResponse", s.handleResponse)
	})
137

138
	// IRMA server for issuing myirma credential during registration
139
140
141
142
	router.Mount("/irma/", s.sessionserver.HandlerFunc())
	return router
}

143
// On configuration changes, inform the keyshare core of any
144
// new IRMA issuer public keys.
145
146
func (s *Server) LoadIdemixKeys(conf *irma.Configuration) {
	for _, issuer := range conf.Issuers {
147
		keyIDs, err := conf.PublicKeyIndices(issuer.Identifier())
148
		if err != nil {
149
			s.conf.Logger.WithFields(logrus.Fields{"issuer": issuer, "error": err}).Warn("Could not find keyIDs for issuer")
150
151
			continue
		}
152
		for _, id := range keyIDs {
153
154
			key, err := conf.PublicKey(issuer.Identifier(), id)
			if err != nil {
155
				s.conf.Logger.WithFields(logrus.Fields{"keyID": id, "error": err}).Warn("Could not fetch public key for issuer")
156
157
158
159
160
161
162
				continue
			}
			s.core.DangerousAddTrustedPublicKey(irma.PublicKeyIdentifier{Issuer: issuer.Identifier(), Counter: uint(id)}, key)
		}
	}
}

163
// /prove/getCommitments
164
func (s *Server) handleCommitments(w http.ResponseWriter, r *http.Request) {
165
166
167
168
	// Fetch from context
	user := r.Context().Value("user").(KeyshareUser)
	authorization := r.Context().Value("authorization").(string)

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
	// Read keys
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	var keys []irma.PublicKeyIdentifier
	err = json.Unmarshal(body, &keys)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		s.conf.Logger.WithField("body", body).Debug("Malformed request data")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	if len(keys) == 0 {
		s.conf.Logger.Info("Malformed request: no keys over which to commit specified")
		server.WriteError(w, server.ErrorInvalidRequest, "No key specified")
		return
	}

190
191
192
193
	commitments, err := s.generateCommitments(user, authorization, keys)
	if err == keysharecore.ErrInvalidChallenge || err == keysharecore.ErrInvalidJWT {
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
194
	}
195
	if err != nil {
196
197
		// already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
198
199
200
		return
	}

201
202
203
	server.WriteJson(w, commitments)
}

204
func (s *Server) generateCommitments(user KeyshareUser, authorization string, keys []irma.PublicKeyIdentifier) (*irma.ProofPCommitmentMap, error) {
205
	// Generate commitments
206
	commitments, commitID, err := s.core.GenerateCommitments(user.Data().Coredata, authorization, keys)
207
208
	if err != nil {
		s.conf.Logger.WithField("error", err).Warn("Could not generate commitments for request")
209
		return nil, err
210
211
212
	}

	// Prepare output message format
213
	mappedCommitments := map[irma.PublicKeyIdentifier]*gabi.ProofPCommitment{}
214
	for i, keyID := range keys {
215
		if err != nil {
216
			s.conf.Logger.WithFields(logrus.Fields{"keyid": keyID, "error": err}).Error("Could not convert key identifier to string")
217
			return nil, err
218
		}
219
		mappedCommitments[keyID] = commitments[i]
220
221
222
	}

	// Store needed data for later requests.
223
	username := user.Data().Username
224
225
226
227
	s.sessionLock.Lock()
	if _, ok := s.sessions[username]; !ok {
		s.sessions[username] = &SessionData{}
	}
228
229
	s.sessions[username].LastCommitID = commitID
	s.sessions[username].LastKeyID = keys[0]
230
	s.sessions[username].expiry = time.Now().Add(10 * time.Second)
231
232
233
	s.sessionLock.Unlock()

	// And send response
234
	return &irma.ProofPCommitmentMap{Commitments: mappedCommitments}, nil
235
236
}

237
// /prove/getResponse
238
func (s *Server) handleResponse(w http.ResponseWriter, r *http.Request) {
239
240
241
242
243
	// Fetch from context
	user := r.Context().Value("user").(KeyshareUser)
	username := user.Data().Username
	authorization := r.Context().Value("authorization").(string)

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
	// Read challenge
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	challenge := new(big.Int)
	err = json.Unmarshal(body, challenge)
	if err != nil {
		s.conf.Logger.Info("Malformed request: could not parse challenge")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

259
260
261
262
263
	// verify access (avoids leaking whether there is a session ongoing to unauthorized callers)
	if !r.Context().Value("hasValidAuthorization").(bool) {
		s.conf.Logger.Warn("Could not generate keyshare response due to invalid authorization")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid authorization")
		return
264
	}
265

266
267
268
269
270
271
272
	// Get data from session
	s.sessionLock.Lock()
	sessionData, ok := s.sessions[username]
	s.sessionLock.Unlock()
	if !ok {
		s.conf.Logger.Warn("Request for response without previous call to get commitments")
		server.WriteError(w, server.ErrorInvalidRequest, "Missing previous call to getCommitments")
273
274
275
		return
	}

276
277
278
	// And do the actual responding
	proofResponse, err := s.doGenerateResponses(user, authorization, challenge, sessionData.LastCommitID, sessionData.LastKeyID)
	if err == keysharecore.ErrInvalidChallenge || err == keysharecore.ErrInvalidJWT {
279
280
281
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
282
283
284
285
286
287
288
289
	if err != nil {
		// already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}

	server.WriteString(w, proofResponse)
}
290

291
func (s *Server) doGenerateResponses(user KeyshareUser, authorization string, challenge *big.Int, commitID uint64, keyID irma.PublicKeyIdentifier) (string, error) {
David Venhoek's avatar
David Venhoek committed
292
	// Indicate activity on user account
293
	err := s.db.SetSeen(user)
David Venhoek's avatar
David Venhoek committed
294
295
296
297
298
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not mark user as seen recently")
		// Do not send to user
	}

299
300
301
302
	// Make log entry
	err = s.db.AddLog(user, IrmaSession, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
303
		return "", err
304
305
	}

306
	proofResponse, err := s.core.GenerateResponse(user.Data().Coredata, authorization, commitID, challenge, keyID)
307
308
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate response for request")
309
		return "", err
310
311
	}

312
	return proofResponse, nil
313
314
}

315
// /users/isAuthorized
316
func (s *Server) handleValidate(w http.ResponseWriter, r *http.Request) {
317
	if r.Context().Value("hasValidAuthorization").(bool) {
318
		server.WriteJson(w, &irma.KeyshareAuthorization{Status: "authorized", Candidates: []string{"pin"}})
319
	} else {
320
		server.WriteJson(w, &irma.KeyshareAuthorization{Status: "expired", Candidates: []string{"pin"}})
321
322
323
	}
}

324
// /users/verify/pin
325
326
327
328
329
330
331
332
func (s *Server) handleVerifyPin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
333
	var msg irma.KeysharePinMessage
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"error": err}).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

349
350
	// and verify pin
	result, err := s.doVerifyPin(user, msg.Username, msg.Pin)
351
	if err != nil {
352
		// already logged
353
354
355
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
356
357
358
359

	server.WriteJson(w, result)
}

360
func (s *Server) doVerifyPin(user KeyshareUser, username, pin string) (irma.KeysharePinStatus, error) {
361
362
363
364
	// Check whether timing allows this pin to be checked
	ok, tries, wait, err := s.db.ReservePincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
365
		return irma.KeysharePinStatus{}, nil
366
	}
367
	if !ok {
368
369
370
		err = s.db.AddLog(user, PinCheckRefused, nil)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
371
			return irma.KeysharePinStatus{}, err
372
		}
373
		return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
374
375
376
377
378
379
	}
	// At this point, we are allowed to do an actual check (we have successfully reserved a spot for it), so do it.
	jwtt, err := s.core.ValidatePin(user.Data().Coredata, pin, username)
	if err != nil && err != keysharecore.ErrInvalidPin {
		// Errors other than invalid pin are real errors
		s.conf.Logger.WithField("error", err).Error("Could not validate pin")
380
		return irma.KeysharePinStatus{}, err
381
	}
382

383
	if err == keysharecore.ErrInvalidPin {
384
		// Handle invalid pin
385
386
387
		err = s.db.AddLog(user, PinCheckFailed, tries)
		if err != nil {
			s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
388
			return irma.KeysharePinStatus{}, err
389
		}
390
		if tries == 0 {
391
392
393
			err = s.db.AddLog(user, PinCheckBlocked, wait)
			if err != nil {
				s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
394
				return irma.KeysharePinStatus{}, err
395
			}
396
			return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
397
		} else {
398
			return irma.KeysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)}, nil
399
		}
400
	}
401

402
403
404
405
406
407
408
409
410
411
412
413
414
415
	// Handle success
	err = s.db.ClearPincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
		// Do not send to user
	}
	err = s.db.SetSeen(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not indicate user activity")
		// Do not send to user
	}
	err = s.db.AddLog(user, PinCheckSuccess, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not add log entry for user")
416
		return irma.KeysharePinStatus{}, err
417
	}
418

419
	return irma.KeysharePinStatus{Status: "success", Message: jwtt}, err
420
421
}

422
// /users/change/pin
423
424
425
426
427
428
429
430
func (s *Server) handleChangePin(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
431
	var msg irma.KeyshareChangePin
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

	// Fetch user
	user, err := s.db.User(msg.Username)
	if err != nil {
		s.conf.Logger.WithFields(logrus.Fields{"username": msg.Username, "error": err}).Warn("Could not find user in db")
		server.WriteError(w, server.ErrorUserNotRegistered, "")
		return
	}

447
	result, err := s.doUpdatePin(user, msg.OldPin, msg.NewPin)
448
	if err != nil {
449
		// already logged
450
		server.WriteError(w, server.ErrorInternal, err.Error())
451
452
		return
	}
453
454
455
	server.WriteJson(w, result)
}

456
func (s *Server) doUpdatePin(user KeyshareUser, oldPin, newPin string) (irma.KeysharePinStatus, error) {
457
458
459
460
	// Check whether pin check is currently allowed
	ok, tries, wait, err := s.db.ReservePincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reserve pin check slot")
461
		return irma.KeysharePinStatus{}, err
462
	}
463
	if !ok {
464
		return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
465
	}
466
467
468

	// Try to do the update
	user.Data().Coredata, err = s.core.ChangePin(user.Data().Coredata, oldPin, newPin)
469
	if err == keysharecore.ErrInvalidPin {
470
		if tries == 0 {
471
			return irma.KeysharePinStatus{Status: "error", Message: fmt.Sprintf("%v", wait)}, nil
472
		} else {
473
			return irma.KeysharePinStatus{Status: "failure", Message: fmt.Sprintf("%v", tries)}, nil
474
475
476
		}
	} else if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not change pin")
477
		return irma.KeysharePinStatus{}, nil
478
	}
479
480

	// Mark pincheck as success, resetting users wait and count
481
482
483
484
485
	err = s.db.ClearPincheck(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not reset users pin check logic")
		// Do not send to user
	}
486
487
488
489
490

	// Write user back
	err = s.db.UpdateUser(user)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not write updated user to database")
491
		return irma.KeysharePinStatus{}, err
492
493
	}

494
	return irma.KeysharePinStatus{Status: "success"}, nil
495
496
}

497
// /client/register
498
499
500
501
502
503
504
505
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
	// Extract request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not read request body")
		server.WriteError(w, server.ErrorInvalidRequest, "could not read request body")
		return
	}
506
	var msg irma.KeyshareEnrollment
507
508
509
510
511
512
513
	err = json.Unmarshal(body, &msg)
	if err != nil {
		s.conf.Logger.WithField("error", err).Info("Malformed request: could not parse request body")
		server.WriteError(w, server.ErrorInvalidRequest, "Invalid request")
		return
	}

514
515
516
517
518
519
520
521
522
523
524
525
526
527
	sessionptr, err := s.doRegistration(msg)
	if err == keysharecore.ErrPinTooLong {
		// Too long pin is not an internal error
		server.WriteError(w, server.ErrorInvalidRequest, err.Error())
		return
	}
	if err != nil {
		// Already logged
		server.WriteError(w, server.ErrorInternal, err.Error())
		return
	}
	server.WriteJson(w, sessionptr)
}

528
func (s *Server) doRegistration(msg irma.KeyshareEnrollment) (*irma.Qr, error) {
529
530
531
532
533
	// Generate keyshare server account
	username := generateUsername()
	coredata, err := s.core.GenerateKeyshareSecret(msg.Pin)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not register user")
534
		return nil, err
535
	}
536
	user, err := s.db.NewUser(KeyshareUserData{Username: username, Language: msg.Language, Coredata: coredata})
537
538
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not store new user in database")
539
		return nil, err
540
541
	}

542
	// Send email if user specified email address
543
	if msg.Email != nil && *msg.Email != "" && s.conf.EmailServer != "" {
544
		err = s.sendRegistrationEmail(user, msg.Language, *msg.Email)
545
		if err != nil {
546
547
			// already logged in sendRegistrationEmail
			return nil, err
548
		}
549
550
	}

551
552
553
554
555
556
557
558
559
560
561
	// Setup and return issuance session for keyshare credential.
	request := irma.NewIssuanceRequest([]*irma.CredentialRequest{
		{
			CredentialTypeID: irma.NewCredentialTypeIdentifier(s.conf.KeyshareCredential),
			Attributes: map[string]string{
				s.conf.KeyshareAttribute: username,
			},
		}})
	sessionptr, _, err := s.sessionserver.StartSession(request, nil)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not start keyshare credential issuance sessions")
562
		return nil, err
563
	}
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
	return sessionptr, nil
}

func (s *Server) sendRegistrationEmail(user KeyshareUser, language, email string) error {
	// Fetch template and configuration data for users language, falling back if needed
	template, ok := s.conf.RegistrationEmailTemplates[language]
	if !ok {
		template = s.conf.RegistrationEmailTemplates[s.conf.DefaultLanguage]
	}
	verificationBaseURL, ok := s.conf.VerificationURL[language]
	if !ok {
		verificationBaseURL = s.conf.VerificationURL[s.conf.DefaultLanguage]
	}
	subject, ok := s.conf.RegistrationEmailSubject[language]
	if !ok {
		subject = s.conf.RegistrationEmailSubject[s.conf.DefaultLanguage]
	}

	// Generate token
	token := common.NewSessionToken()

	// Add it to the database
	err := s.db.AddEmailVerification(user, email, token)
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate email verifiation mail record")
		return err
	}

	// Build message
	var msg bytes.Buffer
	err = template.Execute(&msg, map[string]string{"VerificationURL": verificationBaseURL + token})
	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not generate email verifiation mail")
		return err
	}

	// And send it
	err = server.SendHTMLMail(
		s.conf.EmailServer,
		s.conf.EmailAuth,
		s.conf.EmailFrom,
		email,
		subject,
		msg.Bytes())

	if err != nil {
		s.conf.Logger.WithField("error", err).Error("Could not send email verifiation mail")
		return err
	}

	return nil
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
}

// Generate a base62 "username".
//  this is a direct port of what the old java server uses.
func generateUsername() string {
	bts := make([]byte, 8)
	_, err := rand.Read(bts)
	if err != nil {
		panic(err)
	}
	raw := make([]byte, 12)
	base64.StdEncoding.Encode(raw, bts)
	return strings.ReplaceAll(
		strings.ReplaceAll(
			strings.ReplaceAll(
				string(raw),
				"+",
				""),
			"/",
			""),
		"=",
		"")
}
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676

func (s *Server) userMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Extract username from request
		username := r.Header.Get("X-IRMA-Keyshare-Username")

		// and fetch its information
		user, err := s.db.User(username)
		if err != nil {
			s.conf.Logger.WithFields(logrus.Fields{"username": username, "error": err}).Warn("Could not find user in db")
			server.WriteError(w, server.ErrorUserNotRegistered, err.Error())
			return
		}

		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "user", user)))
	})
}

func (s *Server) authorizationMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Extract authorization from request
		authorization := r.Header.Get("Authorization")
		if strings.HasPrefix(authorization, "Bearer ") {
			authorization = authorization[7:]
		}

		// verify access
		ctx := r.Context()
		err := s.core.ValidateJWT(ctx.Value("user").(KeyshareUser).Data().Coredata, authorization)
		hasValidAuthorization := (err == nil)

		// Construct new context with both authorization and its validity
		nextContext := context.WithValue(
			context.WithValue(ctx, "authorization", authorization),
			"hasValidAuthorization", hasValidAuthorization)

		next.ServeHTTP(w, r.WithContext(nextContext))
	})
}