helpers.go 6.96 KB
Newer Older
1
package servercore
Sietse Ringers's avatar
Sietse Ringers committed
2
3

import (
4
	"crypto/sha256"
5
	"encoding/json"
6
	"fmt"
7
	"net/http"
8
	"reflect"
Sietse Ringers's avatar
Sietse Ringers committed
9
10
11
12
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/go-errors/errors"
13
	"github.com/privacybydesign/gabi"
Sietse Ringers's avatar
Sietse Ringers committed
14
	"github.com/privacybydesign/irmago"
Sietse Ringers's avatar
Sietse Ringers committed
15
	"github.com/privacybydesign/irmago/server"
16
	"github.com/sirupsen/logrus"
17
	"gopkg.in/antage/eventsource.v1"
Sietse Ringers's avatar
Sietse Ringers committed
18
19
20
21
22
23
)

// Session helpers

func (session *session) markAlive() {
	session.lastActive = time.Now()
24
	session.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Debugf("Session marked active, expiry delayed")
Sietse Ringers's avatar
Sietse Ringers committed
25
26
}

Sietse Ringers's avatar
Sietse Ringers committed
27
func (session *session) setStatus(status server.Status) {
28
	session.conf.Logger.WithFields(logrus.Fields{"session": session.token, "prevStatus": session.prevStatus, "status": status}).
29
		Info("Session status updated")
Sietse Ringers's avatar
Sietse Ringers committed
30
	session.status = status
Sietse Ringers's avatar
Sietse Ringers committed
31
	session.result.Status = status
32
	session.sessions.update(session)
33
34
35
36
}

func (session *session) onUpdate() {
	if session.evtSource != nil {
37
		session.conf.Logger.WithFields(logrus.Fields{"session": session.token, "status": session.status}).
38
			Debug("Sending status to SSE listeners")
39
40
		// We send JSON like the other APIs, so quote
		session.evtSource.SendEventMessage(fmt.Sprintf(`"%s"`, session.status), "", "")
41
	}
Sietse Ringers's avatar
Sietse Ringers committed
42
43
}

Sietse Ringers's avatar
Sietse Ringers committed
44
45
46
func (session *session) fail(err server.Error, message string) *irma.RemoteError {
	rerr := server.RemoteError(err, message)
	session.setStatus(server.StatusCancelled)
47
	session.result = &server.SessionResult{Err: rerr, Token: session.token, Status: server.StatusCancelled, Type: session.action}
Sietse Ringers's avatar
Sietse Ringers committed
48
49
50
	return rerr
}

51
const retryTimeLimit = 10 * time.Second
52
53
54
55

// checkCache returns a previously cached response, for replaying against multiple requests from
// irmago's retryablehttp client, if:
// - the same was POSTed as last time
56
57
// - last time was not more than 10 seconds ago (retryablehttp client gives up before this)
// - the session status is what it is expected to be when receiving the request for a second time.
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
func (session *session) checkCache(message []byte, expectedStatus server.Status) (int, []byte) {
	if len(session.responseCache.response) > 0 {
		if session.responseCache.sessionStatus != expectedStatus {
			// don't replay a cache value that was set in a previous session state
			session.responseCache = responseCache{}
			return 0, nil
		}
		if sha256.Sum256(session.responseCache.message) != sha256.Sum256(message) ||
			session.lastActive.Before(time.Now().Add(-retryTimeLimit)) ||
			session.status != expectedStatus {
			return server.JsonResponse(nil, session.fail(server.ErrorUnexpectedRequest, ""))
		}
		return session.responseCache.status, session.responseCache.response
	}
	return 0, nil
}

Sietse Ringers's avatar
Sietse Ringers committed
75
76
// Issuance helpers

77
func (s *Server) validateIssuanceRequest(request *irma.IssuanceRequest) error {
Sietse Ringers's avatar
Sietse Ringers committed
78
79
80
	for _, cred := range request.Credentials {
		// Check that we have the appropriate private key
		iss := cred.CredentialTypeID.IssuerIdentifier()
81
		privatekey, err := s.conf.PrivateKey(iss)
82
83
84
85
		if err != nil {
			return err
		}
		if privatekey == nil {
86
			return errors.Errorf("missing private key of issuer %s", iss.String())
Sietse Ringers's avatar
Sietse Ringers committed
87
		}
88
		pubkey, err := s.conf.IrmaConfiguration.PublicKey(iss, int(privatekey.Counter))
Sietse Ringers's avatar
Sietse Ringers committed
89
90
91
92
		if err != nil {
			return err
		}
		if pubkey == nil {
93
			return errors.Errorf("missing public key of issuer %s", iss.String())
Sietse Ringers's avatar
Sietse Ringers committed
94
95
96
97
		}
		cred.KeyCounter = int(privatekey.Counter)

		// Ensure the credential has an expiry date
98
		defaultValidity := irma.Timestamp(time.Now().AddDate(0, 6, 0))
Sietse Ringers's avatar
Sietse Ringers committed
99
100
101
102
103
104
105
106
107
108
109
		if cred.Validity == nil {
			cred.Validity = &defaultValidity
		}
		if cred.Validity.Before(irma.Timestamp(time.Now())) {
			return errors.New("cannot issue expired credentials")
		}
	}

	return nil
}

Sietse Ringers's avatar
Sietse Ringers committed
110
func (session *session) getProofP(commitments *irma.IssueCommitmentMessage, scheme irma.SchemeManagerIdentifier) (*gabi.ProofP, error) {
Sietse Ringers's avatar
Sietse Ringers committed
111
112
113
114
115
116
117
118
119
	if session.kssProofs == nil {
		session.kssProofs = make(map[irma.SchemeManagerIdentifier]*gabi.ProofP)
	}

	if _, contains := session.kssProofs[scheme]; !contains {
		str, contains := commitments.ProofPjwts[scheme.Name()]
		if !contains {
			return nil, errors.Errorf("no keyshare proof included for scheme %s", scheme.Name())
		}
120
		session.conf.Logger.Debug("Parsing keyshare ProofP JWT: ", str)
Sietse Ringers's avatar
Sietse Ringers committed
121
122
123
124
		claims := &struct {
			jwt.StandardClaims
			ProofP *gabi.ProofP
		}{}
125
		token, err := jwt.ParseWithClaims(str, claims, session.conf.IrmaConfiguration.KeyshareServerKeyFunc(scheme))
Sietse Ringers's avatar
Sietse Ringers committed
126
127
128
129
130
131
132
133
134
135
136
137
		if err != nil {
			return nil, err
		}
		if !token.Valid {
			return nil, errors.Errorf("invalid keyshare proof included for scheme %s", scheme.Name())
		}
		session.kssProofs[scheme] = claims.ProofP
	}

	return session.kssProofs[scheme], nil
}

138
139
140
141
142
143
144
var eventHeaders = [][]byte{[]byte("Access-Control-Allow-Origin: *")}

func (session *session) eventSource() eventsource.EventSource {
	if session.evtSource != nil {
		return session.evtSource
	}

145
	session.conf.Logger.WithFields(logrus.Fields{"session": session.token}).Debug("Making server sent event source")
146
147
148
149
	session.evtSource = eventsource.New(nil, func(_ *http.Request) [][]byte { return eventHeaders })
	return session.evtSource
}

Sietse Ringers's avatar
Sietse Ringers committed
150
151
// Other

152
153
154
155
156
func (session *session) chooseProtocolVersion(minClient, maxClient *irma.ProtocolVersion) (*irma.ProtocolVersion, error) {
	// Set our minimum supported version to 2.5 if condiscon compatibility is required
	minServer := minProtocolVersion
	if !session.legacyCompatible {
		minServer = &irma.ProtocolVersion{2, 5}
Sietse Ringers's avatar
Sietse Ringers committed
157
	}
158
159
160
161
162

	if minClient.AboveVersion(maxProtocolVersion) || maxClient.BelowVersion(minServer) || maxClient.BelowVersion(minClient) {
		return nil, server.LogWarning(errors.Errorf("Protocol version negotiation failed, min=%s max=%s minServer=%s maxServer=%s", minClient.String(), maxClient.String(), minServer.String(), maxProtocolVersion.String()))
	}
	if maxClient.AboveVersion(maxProtocolVersion) {
Sietse Ringers's avatar
Sietse Ringers committed
163
164
		return maxProtocolVersion, nil
	} else {
165
		return maxClient, nil
Sietse Ringers's avatar
Sietse Ringers committed
166
167
	}
}
168

169
170
// purgeRequest logs the request excluding any attribute values.
func purgeRequest(request irma.RequestorRequest) irma.RequestorRequest {
171
172
173
174
	// We want to log as much as possible of the request, but no attribute values.
	// We cannot just remove them from the request parameter as that would break the calling code.
	// So we create a deep copy of the request from which we can then safely remove whatever we want to.
	// Ugly hack alert: the easiest way to do this seems to be to convert it to JSON and then back.
175
	// As we do not know the precise type of request, we use reflection to create a new instance
176
177
178
179
180
181
	// of the same type as request, into which we then unmarshal our copy.
	cpy := reflect.New(reflect.TypeOf(request).Elem()).Interface()
	bts, _ := json.Marshal(request)
	_ = json.Unmarshal(bts, cpy)

	// Remove required attribute values from any attributes to be disclosed
182
183
184
185
186
187
188
	_ = cpy.(irma.RequestorRequest).SessionRequest().Disclosure().Disclose.Iterate(
		func(attr *irma.AttributeRequest) error {
			attr.Value = nil
			return nil
		},
	)

189
	// Remove attribute values from attributes to be issued
190
191
	if isreq, ok := cpy.(*irma.IdentityProviderRequest); ok {
		for _, cred := range isreq.Request.Credentials {
192
193
194
			cred.Attributes = nil
		}
	}
195
196

	return cpy.(irma.RequestorRequest)
197
}