api.go 8.97 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
16

	"github.com/Sirupsen/logrus"
	"github.com/go-errors/errors"
17
18
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
19
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
20
	"github.com/privacybydesign/irmago/server"
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
		if conf.CachePath == "" {
37
			conf.IrmaConfiguration, err = irma.NewConfiguration(conf.IrmaConfigurationPath)
38
		} else {
39
40
41
42
			conf.IrmaConfiguration, err = irma.NewConfigurationFromAssets(
				filepath.Join(conf.CachePath, "irma_configuration"),
				conf.IrmaConfigurationPath,
			)
43
		}
44
		if err != nil {
45
			return server.LogError(err)
46
		}
47
		if err = conf.IrmaConfiguration.ParseFolder(); err != nil {
48
			return server.LogError(err)
49
50
51
52
53
		}
	}

	if len(conf.IrmaConfiguration.SchemeManagers) == 0 {
		if conf.DownloadDefaultSchemes {
54
			if err := conf.IrmaConfiguration.DownloadDefaultSchemes(); err != nil {
55
				return server.LogError(err)
56
			}
57
		} else {
58
			return server.LogError(errors.New("no schemes found in irma_configuration folder " + conf.IrmaConfiguration.Path))
59
		}
60
61
	}

Sietse Ringers's avatar
Sietse Ringers committed
62
63
64
	if conf.SchemeUpdateInterval != 0 {
		conf.IrmaConfiguration.AutoUpdateSchemes(uint(conf.SchemeUpdateInterval))
	} else {
65
		conf.Logger.Info("Scheme updating disabled")
Sietse Ringers's avatar
Sietse Ringers committed
66
67
	}

68
69
	if conf.IssuerPrivateKeys == nil {
		conf.IssuerPrivateKeys = make(map[irma.IssuerIdentifier]*gabi.PrivateKey)
70
	}
71
72
	if conf.IssuerPrivateKeysPath != "" {
		files, err := ioutil.ReadDir(conf.IssuerPrivateKeysPath)
73
		if err != nil {
74
			return server.LogError(err)
75
76
77
78
79
		}
		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 {
80
				return server.LogError(errors.Errorf("Private key %s belongs to an unknown issuer", filename))
81
			}
82
			sk, err := gabi.NewPrivateKeyFromFile(filepath.Join(conf.IssuerPrivateKeysPath, filename))
83
			if err != nil {
84
				return server.LogError(err)
85
			}
86
			conf.IssuerPrivateKeys[issid] = sk
87
88
		}
	}
89
	for issid, sk := range conf.IssuerPrivateKeys {
90
91
		pk, err := conf.IrmaConfiguration.PublicKey(issid, int(sk.Counter))
		if err != nil {
92
			return server.LogError(err)
93
94
		}
		if pk == nil {
95
			return server.LogError(errors.Errorf("Missing public key belonging to private key %s-%d", issid.String(), sk.Counter))
96
97
		}
		if new(big.Int).Mul(sk.P, sk.Q).Cmp(pk.N) != 0 {
98
			return server.LogError(errors.Errorf("Private key %s-%d does not belong to corresponding public key", issid.String(), sk.Counter))
99
100
101
		}
	}

102
103
104
	if conf.URL != "" {
		if !strings.HasSuffix(conf.URL, "/") {
			conf.URL = conf.URL + "/"
105
106
107
108
109
		}
	} 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")
	}

110
111
112
	return nil
}

113
114
115
func StartSession(req interface{}) (*irma.Qr, string, error) {
	rrequest, err := server.ParseSessionRequest(req)
	if err != nil {
116
		return nil, "", server.LogError(err)
117
	}
118
119
120
121

	request := rrequest.SessionRequest()
	action := request.Action()
	if action == irma.ActionIssuing {
122
		if err := validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
123
			return nil, "", server.LogError(err)
124
125
126
		}
	}

127
	session := newSession(action, rrequest)
128
	conf.Logger.Infof("%s session started, token %s", action, session.token)
129
	if conf.Logger.IsLevelEnabled(logrus.DebugLevel) {
130
		conf.Logger.Debug("Session request: ", server.ToJson(rrequest))
131
	} else {
132
		logPurgedRequest(rrequest)
133
	}
134
135
	return &irma.Qr{
		Type: action,
136
		URL:  conf.URL + session.token,
137
138
139
	}, session.token, nil
}

Sietse Ringers's avatar
Sietse Ringers committed
140
func GetSessionResult(token string) *server.SessionResult {
Sietse Ringers's avatar
Sietse Ringers committed
141
	session := sessions.get(token)
142
	if session == nil {
143
		conf.Logger.Warn("Session result requested of unknown session ", token)
Sietse Ringers's avatar
Sietse Ringers committed
144
145
146
147
148
		return nil
	}
	return session.result
}

149
150
151
152
153
154
155
156
157
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
}

158
159
160
func CancelSession(token string) error {
	session := sessions.get(token)
	if session == nil {
161
		return server.LogError(errors.Errorf("can't cancel unknown session %s", token))
162
163
164
165
166
	}
	session.handleDelete()
	return nil
}

167
168
169
170
171
func HandleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
172
) (status int, output []byte, result *server.SessionResult) {
173
174
175
176
177
178
179
180
181
	// 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]
		}
	}
182

183
	conf.Logger.Debugf("Routing protocol message: %s %s", method, path)
184
185
186
187
	if len(message) > 0 {
		conf.Logger.Trace("POST body: ", string(message))
	}
	conf.Logger.Trace("HTTP headers: ", server.ToJson(headers))
188
	pattern := regexp.MustCompile("(\\w+)/?(|commitments|proofs|status)$")
189
190
191
	matches := pattern.FindStringSubmatch(path)
	if len(matches) != 3 {
		conf.Logger.Warnf("Invalid URL: %s", path)
Sietse Ringers's avatar
Sietse Ringers committed
192
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, ""))
193
		return
194
195
	}

Sietse Ringers's avatar
Sietse Ringers committed
196
	// Fetch the session
197
	token := matches[1]
198
	noun := matches[2]
199
200
201
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
202
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
203
		return
204
	}
205
206
	session.Lock()
	defer session.Unlock()
207

208
	// However we return, if the session has been finished or cancelled by any of the handlers
209
210
	// then we should inform the user by returning a SessionResult - but only if we have not
	// already done this in the past, e.g. by a previous HTTP call handled by this function
211
	defer func() {
212
213
		if session.finished() && !session.returned {
			session.returned = true
214
			result = session.result
215
			conf.Logger.Infof("Session %s done, status %s", session.token, session.result.Status)
216
		}
217
		sessions.update(token, session)
218
219
	}()

220
	// Route to handler
221
	switch len(noun) {
222
	case 0:
223
		if method == http.MethodDelete {
224
225
226
			session.handleDelete()
			status = http.StatusOK
			return
227
		}
228
		if method == http.MethodGet {
229
230
231
232
			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
233
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
234
				return
235
236
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
237
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
238
				return
239
			}
Sietse Ringers's avatar
Sietse Ringers committed
240
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
241
			return
242
		}
Sietse Ringers's avatar
Sietse Ringers committed
243
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
244
		return
245
	default:
246
247
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
248
			return
249
250
251
		}

		// Below are only POST enpoints
252
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
253
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
254
255
256
			return
		}

257
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
258
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
259
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
260
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
261
				return
262
			}
Sietse Ringers's avatar
Sietse Ringers committed
263
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
264
265
			return
		}
266
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
267
268
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
269
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
270
				return
271
			}
Sietse Ringers's avatar
Sietse Ringers committed
272
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
273
274
			return
		}
275
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
276
277
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
278
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
279
				return
280
			}
Sietse Ringers's avatar
Sietse Ringers committed
281
			status, output = server.JsonResponse(session.handlePostSignature(signature))
282
			return
283
		}
Sietse Ringers's avatar
Sietse Ringers committed
284

Sietse Ringers's avatar
Sietse Ringers committed
285
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
286
		return
287
288
	}
}