api.go 6.78 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
	"github.com/mhe/gabi"
14
	"github.com/mhe/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
28
29
30
31
32
33
34
35
36
37
38
39

	if conf.IrmaConfiguration == nil {
		var err error
		conf.IrmaConfiguration, err = irma.NewConfiguration(conf.IrmaConfigurationPath, "")
		if err != nil {
			return err
		}
		if err = conf.IrmaConfiguration.ParseFolder(); err != nil {
			return err
		}
	}

40
41
	if conf.IssuerPrivateKeys == nil {
		conf.IssuerPrivateKeys = make(map[irma.IssuerIdentifier]*gabi.PrivateKey)
42
	}
43
44
	if conf.IssuerPrivateKeysPath != "" {
		files, err := ioutil.ReadDir(conf.IssuerPrivateKeysPath)
45
46
47
48
49
50
51
52
53
		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)
			}
54
			sk, err := gabi.NewPrivateKeyFromFile(filepath.Join(conf.IssuerPrivateKeysPath, filename))
55
56
57
			if err != nil {
				return err
			}
58
			conf.IssuerPrivateKeys[issid] = sk
59
60
		}
	}
61
	for issid, sk := range conf.IssuerPrivateKeys {
62
63
64
65
66
67
68
69
70
71
72
73
		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)
		}
	}

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
	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,
		URL:  session.token,
	}, session.token, nil
}

Sietse Ringers's avatar
Sietse Ringers committed
105
func GetSessionResult(token string) *server.SessionResult {
Sietse Ringers's avatar
Sietse Ringers committed
106
	session := sessions.get(token)
107
	if session == nil {
Sietse Ringers's avatar
Sietse Ringers committed
108
109
110
111
112
		return nil
	}
	return session.result
}

113
114
115
116
117
118
119
120
121
func CancelSession(token string) error {
	session := sessions.get(token)
	if session == nil {
		return errors.New("Unknown session, can't cancel")
	}
	session.handleDelete()
	return nil
}

122
123
124
125
126
func HandleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
Sietse Ringers's avatar
Sietse Ringers committed
127
) (status int, output []byte, result *server.SessionResult) {
128
129
130
131
132
133
134
135
136
137
138
139
140
141
	// 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
142
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorInvalidRequest, ""))
143
		return
144
145
	}

Sietse Ringers's avatar
Sietse Ringers committed
146
	// Fetch the session
147
	token := matches[1]
148
	noun := matches[2]
149
150
151
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
Sietse Ringers's avatar
Sietse Ringers committed
152
		status, output = server.JsonResponse(nil, server.RemoteError(server.ErrorSessionUnknown, ""))
153
		return
154
	}
155
156
	session.Lock()
	defer session.Unlock()
157

158
	// However we return, if the session has been finished or cancelled by any of the handlers
159
160
	// 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
161
	defer func() {
162
163
		if session.finished() && !session.returned {
			session.returned = true
164
165
			result = session.result
		}
166
		sessions.update(token, session)
167
168
	}()

169
	// Route to handler
170
	switch len(noun) {
171
	case 0:
172
		if method == http.MethodDelete {
173
174
175
			session.handleDelete()
			status = http.StatusOK
			return
176
		}
177
		if method == http.MethodGet {
178
179
180
181
			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
182
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
183
				return
184
185
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
186
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, err.Error()))
187
				return
188
			}
Sietse Ringers's avatar
Sietse Ringers committed
189
			status, output = server.JsonResponse(session.handleGetRequest(min, max))
190
			return
191
		}
Sietse Ringers's avatar
Sietse Ringers committed
192
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
193
		return
194
	default:
195
		if method != http.MethodPost {
Sietse Ringers's avatar
Sietse Ringers committed
196
			status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
Sietse Ringers's avatar
Sietse Ringers committed
197
198
199
			return
		}

200
		if noun == "commitments" && session.action == irma.ActionIssuing {
Sietse Ringers's avatar
Sietse Ringers committed
201
			commitments := &irma.IssueCommitmentMessage{}
Sietse Ringers's avatar
Sietse Ringers committed
202
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
203
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
204
				return
205
			}
Sietse Ringers's avatar
Sietse Ringers committed
206
			status, output = server.JsonResponse(session.handlePostCommitments(commitments))
Sietse Ringers's avatar
Sietse Ringers committed
207
208
			return
		}
209
		if noun == "proofs" && session.action == irma.ActionDisclosing {
Sietse Ringers's avatar
Sietse Ringers committed
210
211
			disclosure := irma.Disclosure{}
			if err := irma.UnmarshalValidate(message, &disclosure); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
212
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
213
				return
214
			}
Sietse Ringers's avatar
Sietse Ringers committed
215
			status, output = server.JsonResponse(session.handlePostDisclosure(disclosure))
Sietse Ringers's avatar
Sietse Ringers committed
216
217
			return
		}
218
		if noun == "proofs" && session.action == irma.ActionSigning {
Sietse Ringers's avatar
Sietse Ringers committed
219
220
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
Sietse Ringers's avatar
Sietse Ringers committed
221
				status, output = server.JsonResponse(nil, session.fail(server.ErrorMalformedInput, ""))
222
				return
223
			}
Sietse Ringers's avatar
Sietse Ringers committed
224
			status, output = server.JsonResponse(session.handlePostSignature(signature))
225
			return
226
		}
Sietse Ringers's avatar
Sietse Ringers committed
227

Sietse Ringers's avatar
Sietse Ringers committed
228
		status, output = server.JsonResponse(nil, session.fail(server.ErrorInvalidRequest, ""))
229
		return
230
231
	}
}