api.go 5.05 KB
Newer Older
1
2
3
4
5
6
7
8
9
package backend

import (
	"encoding/json"
	"net/http"
	"regexp"

	"github.com/Sirupsen/logrus"
	"github.com/go-errors/errors"
10
	"github.com/mhe/gabi"
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
	"github.com/privacybydesign/irmago"
	"github.com/privacybydesign/irmago/irmaserver"
)

func Initialize(configuration *irmaserver.Configuration) error {
	conf = configuration

	if conf.Logger == nil {
		conf.Logger = logrus.New()
		conf.Logger.Level = logrus.DebugLevel
		conf.Logger.Formatter = &logrus.TextFormatter{}
	}

	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
		}
	}

	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
}

func HandleProtocolMessage(
	path string,
	method string,
	headers map[string][]string,
	message []byte,
) (status int, output []byte, result *irmaserver.SessionResult) {
	// 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)
86
87
		status, output = responseJson(nil, getError(irmaserver.ErrorInvalidRequest, ""))
		return
88
89
	}

Sietse Ringers's avatar
Sietse Ringers committed
90
	// Fetch the session
91
92
93
94
95
	token := matches[1]
	verb := matches[2]
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
96
97
		status, output = responseJson(nil, getError(irmaserver.ErrorSessionUnknown, ""))
		return
98
99
	}

100
	// However we return, if the session has been finished or cancelled by any of the handlers
101
102
	// 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
103
	defer func() {
104
105
		if session.finished() && !session.returned {
			session.returned = true
106
107
108
109
			result = session.result
		}
	}()

110
111
112
113
	// Route to handler
	switch len(verb) {
	case 0:
		if method == "DELETE" {
114
115
116
			session.handleDelete()
			status = http.StatusOK
			return
117
118
119
120
121
122
		}
		if method == "GET" {
			h := http.Header(headers)
			min := &irma.ProtocolVersion{}
			max := &irma.ProtocolVersion{}
			if err := json.Unmarshal([]byte(h.Get(irma.MinVersionHeader)), min); err != nil {
123
124
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, err.Error()))
				return
125
126
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
127
128
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, err.Error()))
				return
129
			}
130
			status, output = responseJson(session.handleGetRequest(min, max))
131
			return
132
		}
133
134
		status, output = responseJson(nil, session.fail(irmaserver.ErrorInvalidRequest, ""))
		return
135
	default:
136
137
138
139
		if method == "POST" {
			if verb == "commitments" && session.action == irma.ActionIssuing {
				commitments := &gabi.IssueCommitmentMessage{}
				if err := irma.UnmarshalValidate(message, commitments); err != nil {
140
141
					status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
					return
142
				}
143
144
				status, output = responseJson(session.handlePostCommitments(commitments))
				return
145
146
147
148
			}
			if verb == "proofs" && session.action == irma.ActionDisclosing {
				proofs := gabi.ProofList{}
				if err := irma.UnmarshalValidate(message, &proofs); err != nil {
149
150
					status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
					return
151
				}
152
153
				status, output = responseJson(session.handlePostProofs(proofs))
				return
154
155
156
157
			}
			if verb == "proofs" && session.action == irma.ActionSigning {
				signature := &irma.SignedMessage{}
				if err := irma.UnmarshalValidate(message, signature); err != nil {
158
159
					status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
					return
160
				}
161
162
				status, output = responseJson(session.handlePostSignature(signature))
				return
163
			}
164
165
		}
		if method == "GET" && verb == "status" {
Sietse Ringers's avatar
Sietse Ringers committed
166
			status, output = responseJson(session.handleGetStatus(), nil)
167
			return
168
		}
169
170
		status, output = responseJson(nil, session.fail(irmaserver.ErrorInvalidRequest, ""))
		return
171
172
	}
}