-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
176 lines (148 loc) · 4.94 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
package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"math/bits"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
irma "github.com/privacybydesign/irmago"
"github.com/privacybydesign/irmago/server"
"github.com/privacybydesign/irmago/server/irmaserver"
)
const (
// If d is the amount of possible login codes and n is the amount of generated login codes, then the
// chance p that one or more login codes is generated twice ore more is approximately the
// following, according to the generalized birthday problem
// (https://en.wikipedia.org/wiki/Birthday_problem):
// p = 1 - e^(-n^2/(2d))
// 12 characters using 62 characters gives d = 62^12. For n = 10^6, this results in a chance of
// about 1.55 in 10 billion of duplicates:
// p = 1 - e^(-(10^6)^2/(2*62^12)) = 1.55 * 10^(-10)
loginCodeDefaultLength = 12
loginCodeCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
type Server struct {
conf *Configuration
}
func start(conf *Configuration) error {
s := &Server{
conf: conf,
}
handler := chi.NewMux()
if s.conf.Verbose == 2 {
handler.Use(server.LogMiddleware("uniqueid-issuer", server.LogOptions{Response: true}))
}
handler.Use(cors.New(cors.Options{
AllowedOrigins: s.conf.clientDomains(),
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "Cache-Control"},
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete},
AllowCredentials: true,
}).Handler)
handler.Mount("/irma/", irmaserver.HandlerFunc())
handler.Post("/session", s.handleSession)
fullAddr := fmt.Sprintf("%s:%d", conf.ListenAddress, conf.Port)
if conf.TLSPrivateKeyFile != "" {
return server.FilterStopError(http.ListenAndServeTLS(fullAddr, conf.TLSCertificateFile, conf.TLSPrivateKeyFile, handler))
}
return server.FilterStopError(http.ListenAndServe(fullAddr, handler))
}
func (s *Server) handleSession(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
client, ok := s.conf.Clients[auth]
if !ok {
s.conf.Logger.Warn("received request with unknown authorization")
w.WriteHeader(401)
return
}
s.conf.Logger.WithField("client", client.Name).Info("handling request")
loginCode, err := newLoginCode(s.conf.LoginCodeLength)
if err != nil {
_ = server.LogError(err)
w.WriteHeader(500)
return
}
bts, err := s.startSession(loginCode, client.Name)
if err != nil {
_ = server.LogError(err)
w.WriteHeader(500)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(bts)
if err != nil {
_ = server.LogError(err)
}
}
func (s *Server) startSession(loginCode, client string) ([]byte, error) {
// Set the expiry to 10 years from now; these attributes don't really expire in the usual sense
validity := time.Now().AddDate(10, 0, 0)
credid := s.conf.LoginCodeAttr.CredentialTypeIdentifier()
request := irma.NewIssuanceRequest([]*irma.CredentialRequest{{
CredentialTypeID: credid,
Validity: (*irma.Timestamp)(&validity),
Attributes: map[string]string{
s.conf.LoginCodeAttr.Name(): loginCode,
s.conf.ClientAttr.Name(): client,
},
}})
// Start the session. Discard the frontend token: we don't use it in this server, this server
// does not expose the requestor API taking this token as parameter.
sesPtr, _, frontendRequest, err := irmaserver.StartSession(request, nil)
if err != nil {
return nil, err
}
bts, err := json.Marshal(server.SessionPackage{
SessionPtr: sesPtr,
FrontendRequest: frontendRequest,
})
if err != nil {
return nil, err
}
return bts, nil
}
// randomNumbers returns a slice of random integers of the length specified by the first parameter,
// each of them being smaller than the maximum specified by the second parameter, where each number
// between 0 and max-1 (inclusive) is chosen with equal probability.
func randomNumbers(length uint, max uint8) ([]uint8, error) {
var (
ints = make([]uint8, 0, length)
bts []byte
num uint8
mask uint8 = 1<<bits.Len8(max) - 1 // in binary: "bits.Len8(max)" consecutive 1's
)
for len(ints) < int(length) {
// Generate a bunch of new random bytes if we've run out.
// We take 10 bytes every 10 iterations instead of 1 per iteration for efficiency.
if len(bts) == 0 {
bts = make([]byte, 10)
_, err := rand.Read(bts)
if err != nil {
return nil, err
}
}
num, bts = bts[0], bts[1:] // pop off the first byte, store it into num
num &= mask // throw away unnecessary bits
if num >= max {
continue
}
ints = append(ints, num)
}
return ints, nil
}
// newLoginCode generates a new login code, that is a random string, where each character from the
// character set is chosen with equal probability.
func newLoginCode(length uint) (string, error) {
r, err := randomNumbers(length, byte(len(loginCodeCharset)))
if err != nil {
return "", err
}
b := make([]byte, length)
for i := range b {
b[i] = loginCodeCharset[r[i]]
}
return string(b), nil
}