forked from privacybydesign/irmago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
messages.go
364 lines (315 loc) · 9.94 KB
/
messages.go
1
2
3
4
5
6
7
8
9
10
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package irma
import (
"bytes"
"encoding/json"
"net/url"
"strconv"
"strings"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/fxamacker/cbor"
"github.com/go-errors/errors"
"github.com/privacybydesign/gabi"
)
// Status encodes the status of an IRMA session (e.g., connected).
type Status string
// disabled until we offer a convenient way to toggle this in irma_mobile
var ForceHttps bool = false
const (
MinVersionHeader = "X-IRMA-MinProtocolVersion"
MaxVersionHeader = "X-IRMA-MaxProtocolVersion"
)
// ProtocolVersion encodes the IRMA protocol version of an IRMA session.
type ProtocolVersion struct {
Major int
Minor int
}
func NewVersion(major, minor int) *ProtocolVersion {
return &ProtocolVersion{major, minor}
}
func (v *ProtocolVersion) String() string {
return fmt.Sprintf("%d.%d", v.Major, v.Minor)
}
func (v *ProtocolVersion) UnmarshalJSON(b []byte) (err error) {
var str string
if err := json.Unmarshal(b, &str); err != nil {
str = string(b) // If b is not enclosed by quotes, try it directly
}
parts := strings.Split(str, ".")
if len(parts) != 2 {
return errors.New("Invalid protocol version number: not of form x.y")
}
if v.Major, err = strconv.Atoi(parts[0]); err != nil {
return
}
v.Minor, err = strconv.Atoi(parts[1])
return
}
func (v *ProtocolVersion) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
// Returns true if v is below the given version.
func (v *ProtocolVersion) Below(major, minor int) bool {
if v.Major < major {
return true
}
return v.Major == major && v.Minor < minor
}
func (v *ProtocolVersion) BelowVersion(other *ProtocolVersion) bool {
return v.Below(other.Major, other.Minor)
}
func (v *ProtocolVersion) Above(major, minor int) bool {
if v.Major > major {
return true
}
return v.Major == major && v.Minor > minor
}
func (v *ProtocolVersion) AboveVersion(other *ProtocolVersion) bool {
return v.Above(other.Major, other.Minor)
}
// GetMetadataVersion maps a chosen protocol version to a metadata version that
// the server will use.
func GetMetadataVersion(v *ProtocolVersion) byte {
if v.Below(2, 3) {
return 0x02 // no support for optional attributes
}
return 0x03 // current version
}
// Action encodes the session type of an IRMA session (e.g., disclosing).
type Action string
// ErrorType are session errors.
type ErrorType string
// SessionError is a protocol error.
type SessionError struct {
Err error
ErrorType
Info string
RemoteError *RemoteError
RemoteStatus int
}
// RemoteError is an error message returned by the API server on errors.
type RemoteError struct {
Status int `json:"status,omitempty"`
ErrorName string `json:"error,omitempty"`
Description string `json:"description,omitempty"`
Message string `json:"message,omitempty"`
Stacktrace string `json:"stacktrace,omitempty"`
}
type Validator interface {
Validate() error
}
// UnmarshalValidate json.Unmarshal's data, and validates it using the
// Validate() method if dest implements the Validator interface.
func UnmarshalValidate(data []byte, dest interface{}) error {
if err := json.Unmarshal(data, dest); err != nil {
return err
}
if v, ok := dest.(Validator); ok {
return v.Validate()
}
return nil
}
func UnmarshalValidateBinary(data []byte, dest interface{}) error {
if err := UnmarshalBinary(data, dest); err != nil {
return err
}
if v, ok := dest.(Validator); ok {
return v.Validate()
}
return nil
}
func MarshalBinary(message interface{}) ([]byte, error) {
return cbor.Marshal(message, cbor.EncOptions{})
}
func UnmarshalBinary(data []byte, dst interface{}) error {
return cbor.Unmarshal(data, dst)
}
func (err *RemoteError) Error() string {
var msg string
if err.Message != "" {
msg = fmt.Sprintf(" (%s)", err.Message)
}
return fmt.Sprintf("%s%s: %s", err.ErrorName, msg, err.Description)
}
// Qr contains the data of an IRMA session QR (as generated by irma_js),
// suitable for NewSession().
type Qr struct {
// Server with which to perform the session
URL string `json:"u"`
// Session type (disclosing, signing, issuing)
Type Action `json:"irmaqr"`
}
type SchemeManagerRequest Qr
// Statuses
const (
StatusConnected = Status("connected")
StatusCommunicating = Status("communicating")
StatusManualStarted = Status("manualStarted")
)
// Actions
const (
ActionSchemeManager = Action("schememanager")
ActionDisclosing = Action("disclosing")
ActionSigning = Action("signing")
ActionIssuing = Action("issuing")
ActionRedirect = Action("redirect")
ActionRevoking = Action("revoking")
ActionUnknown = Action("unknown")
)
// Protocol errors
const (
// Protocol version not supported
ErrorProtocolVersionNotSupported = ErrorType("protocolVersionNotSupported")
// Error in HTTP communication
ErrorTransport = ErrorType("transport")
// Invalid client JWT in first IRMA message
ErrorInvalidJWT = ErrorType("invalidJwt")
// Unkown session type (not disclosing, signing, or issuing)
ErrorUnknownAction = ErrorType("unknownAction")
// Crypto error during calculation of our response (second IRMA message)
ErrorCrypto = ErrorType("crypto")
// Error involving revocation or nonrevocation proofs
ErrorRevocation = ErrorType("revocation")
// Server rejected our response (second IRMA message)
ErrorRejected = ErrorType("rejected")
// (De)serializing of a message failed
ErrorSerialization = ErrorType("serialization")
// Error in keyshare protocol
ErrorKeyshare = ErrorType("keyshare")
// The user is not enrolled at one of the keyshare servers needed for the request
ErrorKeyshareUnenrolled = ErrorType("keyshareUnenrolled")
// API server error
ErrorApi = ErrorType("api")
// Server returned unexpected or malformed response
ErrorServerResponse = ErrorType("serverResponse")
// Credential type not present in our Configuration
ErrorUnknownIdentifier = ErrorType("unknownIdentifier")
// Non-optional attribute not present in credential
ErrorRequiredAttributeMissing = ErrorType("requiredAttributeMissing")
// Error during downloading of credential type, issuer, or public keys
ErrorConfigurationDownload = ErrorType("configurationDownload")
// IRMA requests refers to unknown scheme manager
ErrorUnknownSchemeManager = ErrorType("unknownSchemeManager")
// A session is requested involving a scheme manager that has some problem
ErrorInvalidSchemeManager = ErrorType("invalidSchemeManager")
// Invalid session request
ErrorInvalidRequest = ErrorType("invalidRequest")
// Recovered panic
ErrorPanic = ErrorType("panic")
)
type Disclosure struct {
Proofs gabi.ProofList `json:"proofs"`
Indices DisclosedAttributeIndices `json:"indices"`
}
// DisclosedAttributeIndices contains, for each conjunction of an attribute disclosure request,
// a list of attribute indices, pointing to where the disclosed attributes for that conjunction
// can be found within a gabi.ProofList.
type DisclosedAttributeIndices [][]*DisclosedAttributeIndex
// DisclosedAttributeIndex points to a specific attribute in a gabi.ProofList.
type DisclosedAttributeIndex struct {
CredentialIndex int `json:"cred"`
AttributeIndex int `json:"attr"`
Identifier CredentialIdentifier `json:"-"` // credential from which this attribute was disclosed
}
type IssueCommitmentMessage struct {
*gabi.IssueCommitmentMessage
Indices DisclosedAttributeIndices `json:"indices,omitempty"`
}
func (err ErrorType) Error() string {
return string(err)
}
func (e *SessionError) Error() string {
var buffer bytes.Buffer
typ := e.ErrorType
if typ == "" {
typ = ErrorType("unknown")
}
buffer.WriteString("Error type: ")
buffer.WriteString(string(typ))
if e.Err != nil {
buffer.WriteString("\nDescription: ")
buffer.WriteString(e.Err.Error())
}
if e.RemoteStatus != 200 {
buffer.WriteString("\nStatus code: ")
buffer.WriteString(strconv.Itoa(e.RemoteStatus))
}
if e.RemoteError != nil {
buffer.WriteString("\nIRMA server error: ")
buffer.WriteString(e.RemoteError.Error())
}
return buffer.String()
}
func (e *SessionError) WrappedError() string {
if e.Err == nil {
return ""
}
return e.Err.Error()
}
func (e *SessionError) Stack() string {
if withStack, ok := e.Err.(*errors.Error); ok {
return string(withStack.Stack())
}
return ""
}
func (i *IssueCommitmentMessage) Disclosure() *Disclosure {
return &Disclosure{
Proofs: i.Proofs,
Indices: i.Indices,
}
}
// ParseRequestorJwt parses the specified JWT and returns the contents.
// Note: this function does not verify the signature! Do that elsewhere.
func ParseRequestorJwt(action string, requestorJwt string) (RequestorJwt, error) {
var retval RequestorJwt
switch action {
case "verification_request", string(ActionDisclosing):
retval = &ServiceProviderJwt{}
case "signature_request", string(ActionSigning):
retval = &SignatureRequestorJwt{}
case "issue_request", string(ActionIssuing):
retval = &IdentityProviderJwt{}
default:
return nil, errors.New("Invalid session type")
}
if _, _, err := new(jwt.Parser).ParseUnverified(requestorJwt, retval); err != nil {
return nil, err
}
if err := retval.RequestorRequest().Validate(); err != nil {
return nil, errors.WrapPrefix(err, "Invalid JWT body", 0)
}
return retval, nil
}
func (qr *Qr) Validate() (err error) {
if qr.URL == "" {
return errors.New("No URL specified")
}
var u *url.URL
if u, err = url.ParseRequestURI(qr.URL); err != nil {
return errors.Errorf("Invalid URL: %s", err.Error())
}
if ForceHttps && u.Scheme != "https" {
return errors.Errorf("URL did not begin with https")
}
switch qr.Type {
case ActionDisclosing: // nop
case ActionIssuing: // nop
case ActionSigning: // nop
case ActionRedirect: // nop
default:
return errors.New("Unsupported session type")
}
return nil
}
func (smr *SchemeManagerRequest) Validate() error {
if smr.Type != ActionSchemeManager {
return errors.New("Not a scheme manager request")
}
if smr.URL == "" {
return errors.New("No URL specified")
}
if _, err := url.ParseRequestURI(smr.URL); err != nil {
return errors.Errorf("Invalid URL: %s", err.Error())
}
return nil
}