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

import (
4
	"encoding/json"
5
	"net"
6
	"net/http"
7
8
9
	"os"
	"path/filepath"
	"runtime"
10
11
	"runtime/debug"

12
	"github.com/Sirupsen/logrus"
13
	"github.com/go-errors/errors"
14
	"github.com/privacybydesign/gabi"
15
	"github.com/privacybydesign/irmago"
16
	"github.com/privacybydesign/irmago/internal/fs"
17
18
)

19
20
var Logger *logrus.Logger = logrus.StandardLogger()

21
// Configuration contains configuration for the irmarequestor library and irmaserver.
22
type Configuration struct {
23
24
25
26
27
28
29
30
31
32
33
34
35
36
	// irma_configuration. If not given, this will be popupated using IrmaConfigurationPath.
	IrmaConfiguration *irma.Configuration `json:"-"`
	// Path to schemes to parse (only used if IrmaConfiguration is not given)
	IrmaConfigurationPath string `json:"irmaconf" mapstructure:"irmaconf"`
	// Path to writable dir to write cache to (only used if IrmaConfiguration is not give)
	CachePath string `json:"cachepath" mapstructure:"cachepath"`
	// Path to issuer private keys to parse
	IssuerPrivateKeysPath string `json:"privatekeys" mapstructure:"privatekeys"`
	// Issuer private keys
	IssuerPrivateKeys map[irma.IssuerIdentifier]*gabi.PrivateKey `json:"-"`
	// URL at which the IRMA app can reach this server during sessions
	URL string `json:"url" mapstructure:"url"`
	// Logging
	Logger *logrus.Logger `json:"-"`
37
38
}

39
40
// 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.
41
type SessionResult struct {
Sietse Ringers's avatar
Sietse Ringers committed
42
43
	Token       string
	Status      Status
44
	Type        irma.Action
Sietse Ringers's avatar
Sietse Ringers committed
45
46
47
48
	ProofStatus irma.ProofStatus
	Disclosed   []*irma.DisclosedAttribute
	Signature   *irma.SignedMessage
	Err         *irma.RemoteError
49
50
}

Sietse Ringers's avatar
Sietse Ringers committed
51
// Status is the status of an IRMA session.
52
53
54
type Status string

const (
Sietse Ringers's avatar
Sietse Ringers committed
55
56
57
58
59
	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
60
)
61

62
// RemoteError converts an error and an explaining message to an *irma.RemoteError.
63
64
65
66
67
68
69
70
71
72
73
74
func RemoteError(err Error, message string) *irma.RemoteError {
	stack := string(debug.Stack())
	Logger.Errorf("Error: %d %s %s\n%s", err.Status, err.Type, message, stack)
	return &irma.RemoteError{
		Status:      err.Status,
		Description: err.Description,
		ErrorName:   string(err.Type),
		Message:     message,
		Stacktrace:  stack,
	}
}

75
76
// JsonResponse JSON-marshals the specified object or error
// and returns it along with a suitable HTTP status code
77
78
79
80
81
82
83
84
85
86
87
88
89
90
func JsonResponse(v interface{}, err *irma.RemoteError) (int, []byte) {
	msg := v
	status := http.StatusOK
	if err != nil {
		msg = err
		status = err.Status
	}
	b, e := json.Marshal(msg)
	if e != nil {
		Logger.Error("Failed to serialize response:", e.Error())
		return http.StatusInternalServerError, nil
	}
	return status, b
}
91

92
// WriteError writes the specified error and explaining message as JSON to the http.ResponseWriter.
93
func WriteError(w http.ResponseWriter, err Error, msg string) {
94
	WriteResponse(w, nil, RemoteError(err, msg))
95
96
}

97
// WriteJson writes the specified object as JSON to the http.ResponseWriter.
98
func WriteJson(w http.ResponseWriter, object interface{}) {
99
100
101
	WriteResponse(w, object, nil)
}

102
// WriteResponse writes the specified object or error as JSON to the http.ResponseWriter.
103
104
func WriteResponse(w http.ResponseWriter, object interface{}, rerr *irma.RemoteError) {
	status, bts := JsonResponse(object, rerr)
105
106
107
108
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	w.Write(bts)
}
109

110
// WriteString writes the specified string to the http.ResponseWriter.
111
112
113
114
115
func WriteString(w http.ResponseWriter, str string) {
	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(str))
}
116

117
118
119
// ParseSessionRequest tries to parse the specified bytes as an
// disclosure request, a signature request, and an issuance request, in that order.
// Returns an error if none of the attempts work.
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
func ParseSessionRequest(bts []byte) (request irma.SessionRequest, err error) {
	request = &irma.DisclosureRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	request = &irma.SignatureRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	request = &irma.IssuanceRequest{}
	if err = irma.UnmarshalValidate(bts, request); err == nil {
		return request, nil
	}
	return nil, errors.New("Invalid or disabled session type")
}
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205

func LocalIP() (string, error) {
	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 CachePath() (string, error) {
	candidates := make([]string, 0, 2)
	if runtime.GOOS != "windows" {
		candidates = append(candidates, filepath.Join("/var/tmp", "irmaserver"))
	}
	candidates = append(candidates, filepath.Join(os.TempDir(), "irmaserver"))
	path := firstWritablePath(candidates)
	if path == "" {
		return "", errors.New("No writable temporary directory found")
	}
	return path, nil
}

func firstWritablePath(paths []string) string {
	for _, path := range paths {
		if err := fs.EnsureDirectoryExists(path); err != nil {
			continue
		}
		return path
	}
	return ""
}

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