api.go 5.2 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
	"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
}

Sietse Ringers's avatar
Sietse Ringers committed
66
67
68
69
70
71
72
73
func GetSessionResult(token string) *irmaserver.SessionResult {
	session := sessions.get(token)
	if session != nil {
		return nil
	}
	return session.result
}

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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)
94
95
		status, output = responseJson(nil, getError(irmaserver.ErrorInvalidRequest, ""))
		return
96
97
	}

Sietse Ringers's avatar
Sietse Ringers committed
98
	// Fetch the session
99
100
101
102
103
	token := matches[1]
	verb := matches[2]
	session := sessions.get(token)
	if session == nil {
		conf.Logger.Warnf("Session not found: %s", token)
104
105
		status, output = responseJson(nil, getError(irmaserver.ErrorSessionUnknown, ""))
		return
106
	}
107
108
	session.Lock()
	defer session.Unlock()
109

110
	// However we return, if the session has been finished or cancelled by any of the handlers
111
112
	// 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
113
	defer func() {
114
115
		if session.finished() && !session.returned {
			session.returned = true
116
117
118
119
			result = session.result
		}
	}()

120
121
122
123
	// Route to handler
	switch len(verb) {
	case 0:
		if method == "DELETE" {
124
125
126
			session.handleDelete()
			status = http.StatusOK
			return
127
128
129
130
131
132
		}
		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 {
133
134
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, err.Error()))
				return
135
136
			}
			if err := json.Unmarshal([]byte(h.Get(irma.MaxVersionHeader)), max); err != nil {
137
138
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, err.Error()))
				return
139
			}
140
			status, output = responseJson(session.handleGetRequest(min, max))
141
			return
142
		}
143
144
		status, output = responseJson(nil, session.fail(irmaserver.ErrorInvalidRequest, ""))
		return
145
	default:
Sietse Ringers's avatar
Sietse Ringers committed
146
147
148
149
150
151
152
153
154
		if method != "POST" {
			status, output = responseJson(nil, session.fail(irmaserver.ErrorInvalidRequest, ""))
			return
		}

		if verb == "commitments" && session.action == irma.ActionIssuing {
			commitments := &gabi.IssueCommitmentMessage{}
			if err := irma.UnmarshalValidate(message, commitments); err != nil {
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
155
				return
156
			}
Sietse Ringers's avatar
Sietse Ringers committed
157
158
159
160
161
162
163
			status, output = responseJson(session.handlePostCommitments(commitments))
			return
		}
		if verb == "proofs" && session.action == irma.ActionDisclosing {
			proofs := gabi.ProofList{}
			if err := irma.UnmarshalValidate(message, &proofs); err != nil {
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
164
				return
165
			}
Sietse Ringers's avatar
Sietse Ringers committed
166
167
168
169
170
171
172
			status, output = responseJson(session.handlePostProofs(proofs))
			return
		}
		if verb == "proofs" && session.action == irma.ActionSigning {
			signature := &irma.SignedMessage{}
			if err := irma.UnmarshalValidate(message, signature); err != nil {
				status, output = responseJson(nil, session.fail(irmaserver.ErrorMalformedInput, ""))
173
				return
174
			}
Sietse Ringers's avatar
Sietse Ringers committed
175
			status, output = responseJson(session.handlePostSignature(signature))
176
			return
177
		}
Sietse Ringers's avatar
Sietse Ringers committed
178

179
180
		status, output = responseJson(nil, session.fail(irmaserver.ErrorInvalidRequest, ""))
		return
181
182
	}
}