messages.go 2.33 KB
Newer Older
Sietse Ringers's avatar
Sietse Ringers committed
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
package irmago

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
)

// Action encodes the session type of an IRMA session (e.g., disclosing).
type Action string

// ErrorCode are session errors.
type ErrorCode string

// Error is a protocol error.
type Error struct {
	Err error
	ErrorCode
	*ApiError
	Info   string
	Status int
}

// ApiError is an error message returned by the API server on errors.
type ApiError struct {
	Status      int    `json:"status"`
	ErrorName   string `json:"error"`
	Description string `json:"description"`
	Message     string `json:"message"`
	Stacktrace  string `json:"stacktrace"`
}

// Actions
const (
	ActionDisclosing = Action("disclosing")
	ActionSigning    = Action("signing")
	ActionIssuing    = Action("issuing")
	ActionUnknown    = Action("unknown")
)

// Protocol errors
const (
	// Protocol version not supported
	ErrorProtocolVersionNotSupported = ErrorCode("versionNotSupported")
	// Error in HTTP communication
	ErrorTransport = ErrorCode("httpError")
	// Invalid client JWT in first IRMA message
	ErrorInvalidJWT = ErrorCode("invalidJwt")
	// Unkown session type (not disclosing, signing, or issuing)
	ErrorUnknownAction = ErrorCode("unknownAction")
	// Crypto error during calculation of our response (second IRMA message)
	ErrorCrypto = ErrorCode("cryptoResponseError")
	// Server rejected our response (second IRMA message)
	ErrorRejected = ErrorCode("rejectedByServer")
	// (De)serializing of a message failed
	ErrorSerialization   = ErrorCode("serializationError")
	ErrorKeyshare        = ErrorCode("keyshare")
	ErrorKeyshareBlocked = ErrorCode("keyshareBlocked")
)

func (e *Error) Error() string {
	if e.Err != nil {
		return fmt.Sprintf("%s: %s", string(e.ErrorCode), e.Err.Error())
	}
	return string(e.ErrorCode)
}

func JwtDecode(jwt string, body interface{}) (string, error) {
	jwtparts := strings.Split(jwt, ".")
	if jwtparts == nil || len(jwtparts) < 2 {
		return "", errors.New("Not a JWT")
	}
	headerbytes, err := base64.RawStdEncoding.DecodeString(jwtparts[0])
	if err != nil {
		return "", err
	}
	var header struct {
		Issuer string `json:"iss"`
	}
	err = json.Unmarshal([]byte(headerbytes), &header)
	if err != nil {
		return "", err
	}

	bodybytes, err := base64.RawStdEncoding.DecodeString(jwtparts[1])
	if err != nil {
		return "", err
	}
	return header.Issuer, json.Unmarshal(bodybytes, body)
}