api.go 13.7 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
1
package server
2
3

import (
4
5
	"bytes"
	"encoding/gob"
6
	"encoding/json"
7
	"fmt"
8
	"io/ioutil"
9
	"net"
10
	"net/http"
11
	"reflect"
12
	"runtime"
13
	"runtime/debug"
14
	"time"
15

16
	"github.com/go-errors/errors"
17
	"github.com/privacybydesign/gabi"
18
	"github.com/privacybydesign/irmago"
19
	"github.com/sirupsen/logrus"
20
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
21
22
)

23
24
var Logger *logrus.Logger = logrus.StandardLogger()

Sietse Ringers's avatar
Sietse Ringers committed
25
// Configuration contains configuration for the irmaserver library and irmad.
26
type Configuration struct {
27
	// irma_configuration. If not given, this will be popupated using SchemesPath.
28
	IrmaConfiguration *irma.Configuration `json:"-"`
29
30
31
	// Path to IRMA schemes to parse into IrmaConfiguration (only used if IrmaConfiguration == nil).
	// If left empty, default value is taken using DefaultSchemesPath().
	// If an empty folder is specified, default schemes (irma-demo and pbdf) are downloaded into it.
32
33
34
	SchemesPath string `json:"schemes_path" mapstructure:"schemes_path"`
	// If specified, schemes found here are copied into SchemesPath (only used if IrmaConfiguration == nil)
	SchemesAssetsPath string `json:"schemes_assets_path" mapstructure:"schemes_assets_path"`
35
36
37
38
	// Disable scheme updating
	DisableSchemesUpdate bool `json:"disable_schemes_update" mapstructure:"disable_schemes_update"`
	// Update all schemes every x minutes (default value 0 means 60) (use DisableSchemesUpdate to disable)
	SchemesUpdateInterval int `json:"schemes_update" mapstructure:"schemes_update"`
39
	// Path to issuer private keys to parse
40
	IssuerPrivateKeysPath string `json:"privkeys" mapstructure:"privkeys"`
41
42
	// Issuer private keys
	IssuerPrivateKeys map[irma.IssuerIdentifier]*gabi.PrivateKey `json:"-"`
43
44
	// Path at which to store revocation databases
	RevocationPath string `json:"revocation_path" mapstructure:"revocation_path"`
45
46
	// Credentials types for which revocation database should be hosted
	RevocableCredentials map[irma.CredentialTypeIdentifier]struct{} `json:"-"`
47
48
	// URL at which the IRMA app can reach this server during sessions
	URL string `json:"url" mapstructure:"url"`
49
50
51
	// Required to be set to true if URL does not begin with https:// in production mode.
	// In this case, the server would communicate with IRMA apps over plain HTTP. You must otherwise
	// ensure (using eg a reverse proxy with TLS enabled) that the attributes are protected in transit.
52
	DisableTLS bool `json:"no_tls" mapstructure:"no_tls"`
Sietse Ringers's avatar
Sietse Ringers committed
53
54
55
	// (Optional) email address of server admin, for incidental notifications such as breaking API changes
	// See https://github.com/privacybydesign/irmago/tree/master/server#specifying-an-email-address
	// for more information
56
	Email string `json:"email" mapstructure:"email"`
57
	// Enable server sent events for status updates (experimental; tends to hang when a reverse proxy is used)
58
	EnableSSE bool `json:"enable_sse" mapstructure:"enable_sse"`
59
60
61
62
63
64
65
66
67

	// Logging verbosity level: 0 is normal, 1 includes DEBUG level, 2 includes TRACE level
	Verbose int `json:"verbose" mapstructure:"verbose"`
	// Don't log anything at all
	Quiet bool `json:"quiet" mapstructure:"quiet"`
	// Output structured log in JSON format
	LogJSON bool `json:"log_json" mapstructure:"log_json"`
	// Custom logger instance. If specified, Verbose, Quiet and LogJSON are ignored.
	Logger *logrus.Logger `json:"-"`
68
69
70

	// Production mode: enables safer and stricter defaults and config checking
	Production bool `json:"production" mapstructure:"production"`
71
72
}

73
74
75
76
77
type SessionPackage struct {
	SessionPtr *irma.Qr `json:"sessionPtr"`
	Token      string   `json:"token"`
}

78
79
// SessionResult contains session information such as the session status, type, possible errors,
// and disclosed attributes or attribute-based signature if appropriate to the session type.
80
type SessionResult struct {
81
82
83
84
85
86
87
	Token       string                       `json:"token"`
	Status      Status                       `json:"status"`
	Type        irma.Action                  `json:"type"'`
	ProofStatus irma.ProofStatus             `json:"proofStatus,omitempty"`
	Disclosed   [][]*irma.DisclosedAttribute `json:"disclosed,omitempty"`
	Signature   *irma.SignedMessage          `json:"signature,omitempty"`
	Err         *irma.RemoteError            `json:"error,omitempty"`
88

89
	LegacySession bool `json:"-"` // true if request was started with legacy (i.e. pre-condiscon) session request
90
91
}

Sietse Ringers's avatar
Sietse Ringers committed
92
// Status is the status of an IRMA session.
93
94
95
type Status string

const (
Sietse Ringers's avatar
Sietse Ringers committed
96
97
98
99
100
	StatusInitialized Status = "INITIALIZED" // The session has been started and is waiting for the client
	StatusConnected   Status = "CONNECTED"   // The client has retrieved the session request, we wait for its response
	StatusCancelled   Status = "CANCELLED"   // The session is cancelled, possibly due to an error
	StatusDone        Status = "DONE"        // The session has completed successfully
	StatusTimeout     Status = "TIMEOUT"     // Session timed out
101
)
102

103
// Remove this when dropping support for legacy pre-condiscon session requests
104
105
106
107
108
109
110
111
112
type LegacySessionResult struct {
	Token       string                     `json:"token"`
	Status      Status                     `json:"status"`
	Type        irma.Action                `json:"type"`
	ProofStatus irma.ProofStatus           `json:"proofStatus,omitempty"`
	Disclosed   []*irma.DisclosedAttribute `json:"disclosed,omitempty"`
	Signature   *irma.SignedMessage        `json:"signature,omitempty"`
	Err         *irma.RemoteError          `json:"error,omitempty"`
}
113

114
115
// Remove this when dropping support for legacy pre-condiscon session requests
func (r *SessionResult) Legacy() *LegacySessionResult {
116
117
118
119
	var disclosed []*irma.DisclosedAttribute
	for _, l := range r.Disclosed {
		disclosed = append(disclosed, l[0])
	}
120
	return &LegacySessionResult{r.Token, r.Status, r.Type, r.ProofStatus, disclosed, r.Signature, r.Err}
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
func (conf *Configuration) PrivateKey(id irma.IssuerIdentifier) (sk *gabi.PrivateKey, err error) {
	sk = conf.IssuerPrivateKeys[id]
	if sk == nil {
		if sk, err = conf.IrmaConfiguration.PrivateKey(id); err != nil {
			return nil, err
		}
	}
	return sk, nil
}

func (conf *Configuration) HavePrivateKeys() (bool, error) {
	var err error
	var sk *gabi.PrivateKey
	for id := range conf.IrmaConfiguration.Issuers {
		sk, err = conf.PrivateKey(id)
		if err != nil {
			return false, err
		}
		if sk != nil {
			return true, nil
		}
	}
	return false, nil
}

148
149
150
151
func (status Status) Finished() bool {
	return status == StatusDone || status == StatusCancelled || status == StatusTimeout
}

152
// RemoteError converts an error and an explaining message to an *irma.RemoteError.
153
func RemoteError(err Error, message string) *irma.RemoteError {
154
155
156
157
158
159
160
	var stack string
	Logger.WithFields(logrus.Fields{
		"status":      err.Status,
		"description": err.Description,
		"error":       err.Type,
		"message":     message,
	}).Warnf("Sending session error")
161
	if Logger.IsLevelEnabled(logrus.DebugLevel) {
162
163
164
		stack = string(debug.Stack())
		Logger.Warn(stack)
	}
165
166
167
168
169
170
171
172
173
	return &irma.RemoteError{
		Status:      err.Status,
		Description: err.Description,
		ErrorName:   string(err.Type),
		Message:     message,
		Stacktrace:  stack,
	}
}

174
175
// JsonResponse JSON-marshals the specified object or error
// and returns it along with a suitable HTTP status code
176
func JsonResponse(v interface{}, err *irma.RemoteError) (int, []byte) {
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
	return encodeValOrError(v, err, json.Marshal)
}

func GobResponse(v interface{}, err *irma.RemoteError) (int, []byte) {
	return encodeValOrError(v, err, gobMarshal)
}

func gobMarshal(v interface{}) ([]byte, error) {
	var b bytes.Buffer
	if err := gob.NewEncoder(&b).Encode(v); err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}

func encodeValOrError(v interface{}, err *irma.RemoteError, encoder func(interface{}) ([]byte, error)) (int, []byte) {
193
194
195
196
197
198
	msg := v
	status := http.StatusOK
	if err != nil {
		msg = err
		status = err.Status
	}
199
	b, e := encoder(msg)
200
201
202
203
204
205
	if e != nil {
		Logger.Error("Failed to serialize response:", e.Error())
		return http.StatusInternalServerError, nil
	}
	return status, b
}
206

207
// WriteError writes the specified error and explaining message as JSON to the http.ResponseWriter.
208
func WriteError(w http.ResponseWriter, err Error, msg string) {
209
	WriteResponse(w, nil, RemoteError(err, msg))
210
211
}

212
// WriteJson writes the specified object as JSON to the http.ResponseWriter.
213
func WriteJson(w http.ResponseWriter, object interface{}) {
214
215
216
	WriteResponse(w, object, nil)
}

217
// WriteResponse writes the specified object or error as JSON to the http.ResponseWriter.
218
219
func WriteResponse(w http.ResponseWriter, object interface{}, rerr *irma.RemoteError) {
	status, bts := JsonResponse(object, rerr)
220
221
222
223
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	w.Write(bts)
}
224

225
// WriteString writes the specified string to the http.ResponseWriter.
226
227
228
229
230
func WriteString(w http.ResponseWriter, str string) {
	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(str))
}
231

232
233
234
235
// ParseSessionRequest attempts to parse the input as an irma.RequestorRequest instance, accepting (skipping "irma.")
//  - RequestorRequest instances directly (ServiceProviderRequest, SignatureRequestorRequest, IdentityProviderRequest)
//  - SessionRequest instances (DisclosureRequest, SignatureRequest, IssuanceRequest)
//  - JSON representations ([]byte or string) of any of the above.
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
func ParseSessionRequest(request interface{}) (irma.RequestorRequest, error) {
	switch r := request.(type) {
	case irma.RequestorRequest:
		return r, nil
	case irma.SessionRequest:
		return wrapSessionRequest(r)
	case string:
		return ParseSessionRequest([]byte(r))
	case []byte:
		var attempts = []irma.Validator{&irma.ServiceProviderRequest{}, &irma.SignatureRequestorRequest{}, &irma.IdentityProviderRequest{}}
		t, err := tryUnmarshalJson(r, attempts)
		if err == nil {
			return t.(irma.RequestorRequest), nil
		}
		attempts = []irma.Validator{&irma.DisclosureRequest{}, &irma.SignatureRequest{}, &irma.IssuanceRequest{}}
		t, err = tryUnmarshalJson(r, attempts)
		if err == nil {
			return wrapSessionRequest(t.(irma.SessionRequest))
		}
		return nil, errors.New("Failed to JSON unmarshal request bytes")
	default:
		return nil, errors.New("Invalid request type")
258
	}
259
260
261
262
263
264
265
266
267
268
269
270
}

func wrapSessionRequest(request irma.SessionRequest) (irma.RequestorRequest, error) {
	switch r := request.(type) {
	case *irma.DisclosureRequest:
		return &irma.ServiceProviderRequest{Request: r}, nil
	case *irma.SignatureRequest:
		return &irma.SignatureRequestorRequest{Request: r}, nil
	case *irma.IssuanceRequest:
		return &irma.IdentityProviderRequest{Request: r}, nil
	default:
		return nil, errors.New("Invalid session type")
271
	}
272
273
274
275
276
277
278
}

func tryUnmarshalJson(bts []byte, attempts []irma.Validator) (irma.Validator, error) {
	for _, a := range attempts {
		if err := irma.UnmarshalValidate(bts, a); err == nil {
			return a, nil
		}
279
	}
280
	return nil, errors.New("")
281
}
282

283
// LocalIP returns the IP address of one of the (non-loopback) network interfaces
284
func LocalIP() (string, error) {
285
	// Based on https://play.golang.org/p/BDt3qEQ_2H from https://stackoverflow.com/a/23558495
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
	ifaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	for _, iface := range ifaces {
		if iface.Flags&net.FlagUp == 0 {
			continue // interface down
		}
		if iface.Flags&net.FlagLoopback != 0 {
			continue // loopback interface
		}
		addrs, err := iface.Addrs()
		if err != nil {
			return "", err
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() {
				continue
			}
			ip = ip.To4()
			if ip == nil {
				continue // not an ipv4 address
			}
			return ip.String(), nil
		}
	}
	return "", errors.New("No IP found")
}

func Verbosity(level int) logrus.Level {
	switch {
	case level == 1:
		return logrus.DebugLevel
	case level > 1:
		return logrus.TraceLevel
	default:
		return logrus.InfoLevel
	}
}
332

333
334
335
336
func TypeString(x interface{}) string {
	return reflect.TypeOf(x).String()
}

337
func log(level logrus.Level, err error) error {
338
	writer := Logger.WithFields(logrus.Fields{"err": TypeString(err)}).WriterLevel(level)
339
	if e, ok := err.(*errors.Error); ok && Logger.IsLevelEnabled(logrus.DebugLevel) {
340
		_, _ = writer.Write([]byte(e.ErrorStack()))
341
	} else {
342
		_, _ = writer.Write([]byte(fmt.Sprintf("%s", err.Error())))
343
344
345
346
	}
	return err
}

347
func LogFatal(err error) error {
348
	logger := Logger.WithFields(logrus.Fields{"err": TypeString(err)})
349
	// using log() for this doesn't seem to do anything
350
	if e, ok := err.(*errors.Error); ok && Logger.IsLevelEnabled(logrus.DebugLevel) {
351
		logger.Fatal(e.ErrorStack())
352
	} else {
353
		logger.Fatalf("%s", err.Error())
354
355
	}
	return err
356
357
358
359
360
361
}

func LogError(err error) error {
	return log(logrus.ErrorLevel, err)
}

362
func LogWarning(err error) error {
363
	return log(logrus.WarnLevel, err)
364
365
}

366
func LogRequest(typ, method, url, from string, headers http.Header, message []byte) {
367
	fields := logrus.Fields{
368
369
370
371
372
373
		"type":   typ,
		"method": method,
		"url":    url,
	}
	if len(headers) > 0 {
		fields["headers"] = headers
374
	}
375
376
377
378
379
	if len(message) > 0 {
		fields["message"] = string(message)
	}
	if from != "" {
		fields["from"] = from
380
381
382
383
384
	}
	Logger.WithFields(fields).Tracef("=> request")
}

func LogResponse(status int, duration time.Duration, response []byte) {
385
	fields := logrus.Fields{
386
387
		"status":   status,
		"duration": duration.String(),
388
389
390
391
392
393
394
395
396
397
	}
	if len(response) > 0 {
		fields["response"] = string(response)
	}
	l := Logger.WithFields(fields)
	if status < 400 {
		l.Trace("<= response")
	} else {
		l.Warn("<= response")
	}
398
399
}

400
401
402
403
func ToJson(o interface{}) string {
	bts, _ := json.Marshal(o)
	return string(bts)
}
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

func NewLogger(verbosity int, quiet bool, json bool) *logrus.Logger {
	logger := logrus.New()

	if quiet {
		logger.Out = ioutil.Discard
		return logger
	}

	logger.Level = Verbosity(verbosity)
	if json {
		logger.SetFormatter(&logrus.JSONFormatter{})
	} else {
		logger.SetFormatter(&prefixed.TextFormatter{
			FullTimestamp: true,
			DisableColors: runtime.GOOS == "windows",
		})
	}

	return logger
}