api.go 7.8 KB
Newer Older
1
2
3
4
package backend

import (
	"encoding/json"
5
	"io/ioutil"
6
	"net/http"
7
	"path/filepath"
8
	"regexp"
9
	"strings"
10
11
12

	"github.com/Sirupsen/logrus"
	"github.com/go-errors/errors"
13
14
	"github.com/privacybydesign/gabi"
	"github.com/privacybydesign/gabi/big"
15
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
16
	"github.com/privacybydesign/irmago/server"
17
18
)

Sietse Ringers's avatar
Sietse Ringers committed
19
func Initialize(configuration *server.Configuration) error {
20
21
22
23
24
25
26
	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
27
	server.Logger = conf.Logger
Sietse Ringers's avatar
Sietse Ringers committed
28
	irma.Logger = conf.Logger
29
30
31

	if conf.IrmaConfiguration == nil {
		var err error
32
33
34
35
36
37
		if conf.CachePath == "" {
			conf.CachePath, err = CachePath()
			if err != nil {
				return err
			}
			conf.CachePath = filepath.Join(conf.CachePath, "irmalibrary")
38
		}
39
40
41
42
43
		conf.IrmaConfiguration, err = irma.NewConfiguration(
			filepath.Join(conf.CachePath, "irma_configuration"),
			conf.IrmaConfigurationPath,
		)
		if err != nil {
44
45
			return err
		}
46
47

		if conf.IrmaConfigurationPath == "" {
48
49
50
			if err := conf.IrmaConfiguration.DownloadDefaultSchemes(); err != nil {
				return err
			}
51
52
53
54
		} else {
			if err = conf.IrmaConfiguration.ParseFolder(); err != nil {
				return err
			}
55
		}
56
57
	}

58
59
60
61
	if len(conf.IrmaConfiguration.SchemeManagers) == 0 {
		return errors.New("no schemes found in irma_configuration folder " + conf.IrmaConfiguration.Path)
	}

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

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
	return nil
}

func StartSession(request irma.SessionRequest) (*irma.Qr, string, error) {
	if err := request.Validate(); err != nil {
		return nil, "", err
	}
	action := irma.ActionUnknown
	switch request.(type) {
	case *irma.DisclosureRequest:
		action = irma.ActionDisclosing
	case *irma.SignatureRequest:
		action = irma.ActionSigning
	case *irma.IssuanceRequest:
		action = irma.ActionIssuing
		if err := validateIssuanceRequest(request.(*irma.IssuanceRequest)); err != nil {
			return nil, "", err
		}
	default:
		conf.Logger.Warnf("Attempt to start session of invalid type")
		return nil, "", errors.New("Invalid session type")
	}

	session := newSession(action, request)
	conf.Logger.Infof("%s session started, token %s", action, session.token)
	return &irma.Qr{
		Type: action,
131
		URL:  conf.URL + session.token,
132
133
134
	}, session.token, nil
}

Sietse Ringers's avatar
Sietse Ringers committed
135
func GetSessionResult(token string) *server.SessionResult {
Sietse Ringers's avatar
Sietse Ringers committed
136
	session := sessions.get(token)
137
	if session == nil {
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 CancelSession(token string) error {
	session := sessions.get(token)
	if session == nil {
		return errors.New("Unknown session, can't cancel")
	}
	session.handleDelete()
	return nil
}

152
153
154
155
156
func HandleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
157
) (status int, output []byte, result *server.SessionResult) {
158
159
160
161
162
163
164
165
166
167
168
169
170
171
	// 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]
		}
	}
	conf.Logger.Debugf("Routing protocol message: %s %s", method, path)
	pattern := regexp.MustCompile("(\\w+)/?(\\w*)")
	matches := pattern.FindStringSubmatch(path)
	if len(matches) != 3 {
		conf.Logger.Warnf("Invalid URL: %s", path)
Sietse Ringers's avatar
Sietse Ringers committed
172
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, ""))
173
		return
174
175
	}

Sietse Ringers's avatar
Sietse Ringers committed
176
	// Fetch the session
177
	token := matches[1]
178
	noun := matches[2]
179
180
181
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
182
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
183
		return
184
	}
185
186
	session.Lock()
	defer session.Unlock()
187

188
	// However we return, if the session has been finished or cancelled by any of the handlers
189
190
	// 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
191
	defer func() {
192
193
		if session.finished() && !session.returned {
			session.returned = true
194
195
			result = session.result
		}
196
		sessions.update(token, session)
197
198
	}()

199
	// Route to handler
200
	switch len(noun) {
201
	case 0:
202
		if method == http.MethodDelete {
203
204
205
			session.handleDelete()
			status = http.StatusOK
			return
206
		}
207
		if method == http.MethodGet {
208
209
210
211
			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
212
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
213
				return
214
215
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
216
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
217
				return
218
			}
Sietse Ringers's avatar
Sietse Ringers committed
219
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
220
			return
221
		}
Sietse Ringers's avatar
Sietse Ringers committed
222
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
223
		return
224
	default:
225
226
		if method == http.MethodGet && noun == "status" {
			status, output = server.JsonResponse(session.handleGetStatus())
Sietse Ringers's avatar
Sietse Ringers committed
227
			return
228
229
230
		}

		// Below are only POST enpoints
231
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
232
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
233
234
235
			return
		}

236
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
237
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
238
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
239
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
240
				return
241
			}
Sietse Ringers's avatar
Sietse Ringers committed
242
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
243
244
			return
		}
245
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
246
247
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
248
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
249
				return
250
			}
Sietse Ringers's avatar
Sietse Ringers committed
251
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
252
253
			return
		}
254
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
255
256
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
257
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
258
				return
259
			}
Sietse Ringers's avatar
Sietse Ringers committed
260
			status, output = server.JsonResponse(session.handlePostSignature(signature))
261
			return
262
		}
Sietse Ringers's avatar
Sietse Ringers committed
263

Sietse Ringers's avatar
Sietse Ringers committed
264
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
265
		return
266
267
	}
}