api.go 9.43 KB
Newer Older
1
2
3
4
// Package core is the core of the IRMA server library, allowing IRMA verifiers, issuers
// or attribute-based signature applications to perform IRMA sessions with irmaclient instances
// (i.e. the IRMA app). It exposes a small interface to expose to other programming languages
// through cgo. It is used by the irmarequestor package but otherwise not meant for use in Go.
5
package core
6
7
8

import (
	"encoding/json"
9
	"io/ioutil"
10
	"net/http"
11
	"path/filepath"
12
	"regexp"
13
	"strings"
14
15

	"github.com/go-errors/errors"
16
17
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
18
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
19
	"github.com/privacybydesign/irmago/server"
20
	"github.com/sirupsen/logrus"
21
22
)

Sietse Ringers's avatar
Sietse Ringers committed
23
func Initialize(configuration *server.Configuration) error {
24
25
26
27
28
29
30
	conf = configuration

	if conf.Logger == nil {
		conf.Logger = logrus.New()
		conf.Logger.Level = logrus.DebugLevel
		conf.Logger.Formatter = &logrus.TextFormatter{}
	}
Sietse Ringers's avatar
Sietse Ringers committed
31
	server.Logger = conf.Logger
Sietse Ringers's avatar
Sietse Ringers committed
32
	irma.Logger = conf.Logger
33
34
35

	if conf.IrmaConfiguration == nil {
		var err error
36
37
		if conf.SchemesAssetsPath == "" {
			conf.IrmaConfiguration, err = irma.NewConfiguration(conf.SchemesPath)
38
		} else {
39
			conf.IrmaConfiguration, err = irma.NewConfigurationFromAssets(conf.SchemesPath, conf.SchemesAssetsPath)
40
		}
41
		if err != nil {
42
			return server.LogError(err)
43
		}
44
		if err = conf.IrmaConfiguration.ParseFolder(); err != nil {
45
			return server.LogError(err)
46
47
48
49
50
		}
	}

	if len(conf.IrmaConfiguration.SchemeManagers) == 0 {
		if conf.DownloadDefaultSchemes {
51
			if err := conf.IrmaConfiguration.DownloadDefaultSchemes(); err != nil {
52
				return server.LogError(err)
53
			}
54
		} else {
55
			return server.LogError(errors.New("no schemes found in irma_configuration folder " + conf.IrmaConfiguration.Path))
56
		}
57
	}
Sietse Ringers's avatar
Sietse Ringers committed
58
59
60
61
	if conf.SchemeUpdateInterval != 0 {
		conf.IrmaConfiguration.AutoUpdateSchemes(uint(conf.SchemeUpdateInterval))
	}

62
63
	if conf.IssuerPrivateKeys == nil {
		conf.IssuerPrivateKeys = make(map[irma.IssuerIdentifier]*gabi.PrivateKey)
64
	}
65
66
	if conf.IssuerPrivateKeysPath != "" {
		files, err := ioutil.ReadDir(conf.IssuerPrivateKeysPath)
67
		if err != nil {
68
			return server.LogError(err)
69
70
71
72
73
		}
		for _, file := range files {
			filename := file.Name()
			issid := irma.NewIssuerIdentifier(strings.TrimSuffix(filename, filepath.Ext(filename))) // strip .xml
			if _, ok := conf.IrmaConfiguration.Issuers[issid]; !ok {
74
				return server.LogError(errors.Errorf("Private key %s belongs to an unknown issuer", filename))
75
			}
76
			sk, err := gabi.NewPrivateKeyFromFile(filepath.Join(conf.IssuerPrivateKeysPath, filename))
77
			if err != nil {
78
				return server.LogError(err)
79
			}
80
			conf.IssuerPrivateKeys[issid] = sk
81
82
		}
	}
83
	for issid, sk := range conf.IssuerPrivateKeys {
84
85
		pk, err := conf.IrmaConfiguration.PublicKey(issid, int(sk.Counter))
		if err != nil {
86
			return server.LogError(err)
87
88
		}
		if pk == nil {
89
			return server.LogError(errors.Errorf("Missing public key belonging to private key %s-%d", issid.String(), sk.Counter))
90
91
		}
		if new(big.Int).Mul(sk.P, sk.Q).Cmp(pk.N) != 0 {
92
			return server.LogError(errors.Errorf("Private key %s-%d does not belong to corresponding public key", issid.String(), sk.Counter))
93
94
95
		}
	}

96
97
98
	if conf.URL != "" {
		if !strings.HasSuffix(conf.URL, "/") {
			conf.URL = conf.URL + "/"
99
100
101
102
103
		}
	} else {
		conf.Logger.Warn("No url parameter specified in configuration; unless an url is elsewhere prepended in the QR, the IRMA client will not be able to connect")
	}

104
105
106
	return nil
}

107
108
109
func StartSession(req interface{}) (*irma.Qr, string, error) {
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
110
		return nil, "", server.LogError(err)
111
	}
112
113
114
115

	request := rrequest.SessionRequest()
	action := request.Action()
	if action == irma.ActionIssuing {
116
		if err := validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
117
			return nil, "", server.LogError(err)
118
119
120
		}
	}

121
	session := newSession(action, rrequest)
122
	conf.Logger.Infof("%s session started, token %s", action, session.token)
123
	if conf.Logger.IsLevelEnabled(logrus.DebugLevel) {
124
		conf.Logger.Debug("Session request: ", server.ToJson(rrequest))
125
	} else {
126
		logPurgedRequest(rrequest)
127
	}
128
129
	return &irma.Qr{
		Type: action,
130
		URL:  conf.URL + session.token,
131
132
133
	}, session.token, nil
}

Sietse Ringers's avatar
Sietse Ringers committed
134
func GetSessionResult(token string) *server.SessionResult {
Sietse Ringers's avatar
Sietse Ringers committed
135
	session := sessions.get(token)
136
	if session == nil {
137
		conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
138
139
140
141
142
		return nil
	}
	return session.result
}

143
144
145
146
147
148
149
150
151
func GetRequest(token string) irma.RequestorRequest {
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warn("Session request requested of unknown session ", token)
		return nil
	}
	return session.rrequest
}

152
153
154
func CancelSession(token string) error {
	session := sessions.get(token)
	if session == nil {
155
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
156
157
158
159
160
	}
	session.handleDelete()
	return nil
}

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
func ParsePath(path string) (string, string, error) {
	pattern := regexp.MustCompile("(\\w+)/?(|commitments|proofs|status|statusevents)$")
	matches := pattern.FindStringSubmatch(path)
	if len(matches) != 3 {
		return "", "", server.LogWarning(errors.Errorf("Invalid URL: %s", path))
	}
	return matches[1], matches[2], nil
}

func SubscribeServerSentEvents(w http.ResponseWriter, r *http.Request, token string) error {
	session := sessions.get(token)
	if session == nil {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of unknown session %s", token))
	}
	if session.status.Finished() {
		return server.LogError(errors.Errorf("can't subscribe to server sent events of finished session %s", token))
	}

	session.Lock()
	defer session.Unlock()
	session.eventSource().ServeHTTP(w, r)
	return nil
}

185
186
187
188
189
func HandleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
190
) (status int, output []byte, result *server.SessionResult) {
191
192
193
194
195
196
197
198
199
	// Parse path into session and action
	if len(path) > 0 { // Remove any starting and trailing slash
		if path[0] == '/' {
			path = path[1:]
		}
		if path[len(path)-1] == '/' {
			path = path[:len(path)-1]
		}
	}
200

201
	conf.Logger.Debugf("Routing protocol message: %s %s", method, path)
202
203
204
205
	if len(message) > 0 {
		conf.Logger.Trace("POST body: ", string(message))
	}
	conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
206
207
208
	token, noun, err := ParsePath(path)
	if err != nil {
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorUnsupported, ""))
209
		return
210
211
	}

Sietse Ringers's avatar
Sietse Ringers committed
212
	// Fetch the session
213
214
215
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
216
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
217
		return
218
	}
219
220
	session.Lock()
	defer session.Unlock()
221

222
223
	// However we return, if the session status has been updated
	// then we should inform the user by returning a SessionResult
224
	defer func() {
225
226
		if session.status != session.prevStatus {
			session.prevStatus = session.status
227
228
229
230
			result = session.result
		}
	}()

231
	// Route to handler
232
	switch len(noun) {
233
	case 0:
234
		if method == http.MethodDelete {
235
236
237
			session.handleDelete()
			status = http.StatusOK
			return
238
		}
239
		if method == http.MethodGet {
240
241
242
243
			h := http.Header(headers)
			min := &irma.ProtocolVersion{}
			max := &irma.ProtocolVersion{}
			if err := json.Unmarshal([]byte(h.Get(irma.MinVersionHeader)), min); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
244
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
245
				return
246
247
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
248
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
249
				return
250
			}
Sietse Ringers's avatar
Sietse Ringers committed
251
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
252
			return
253
		}
Sietse Ringers's avatar
Sietse Ringers committed
254
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
255
		return
256
	default:
257
258
259
260
261
262
		if noun == "statusevents" {
			err := server.RemoteError(server.ErrorInvalidRequest, "server sent events not supported by this server")
			status, output = server.JsonResponse(nil, err)
			return
		}

263
264
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
265
			return
266
267
268
		}

		// Below are only POST enpoints
269
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
270
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
271
272
273
			return
		}

274
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
275
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
276
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
277
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
278
				return
279
			}
Sietse Ringers's avatar
Sietse Ringers committed
280
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
281
282
			return
		}
283
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
284
285
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
286
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
287
				return
288
			}
Sietse Ringers's avatar
Sietse Ringers committed
289
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
290
291
			return
		}
292
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
293
294
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
295
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
296
				return
297
			}
Sietse Ringers's avatar
Sietse Ringers committed
298
			status, output = server.JsonResponse(session.handlePostSignature(signature))
299
			return
300
		}
Sietse Ringers's avatar
Sietse Ringers committed
301

Sietse Ringers's avatar
Sietse Ringers committed
302
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
303
		return
304
305
	}
}