forked from privacypass/challenge-bypass-server
/
signed_token_redeem_handler.go
455 lines (427 loc) · 14.4 KB
/
signed_token_redeem_handler.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package kafka
import (
"bytes"
"errors"
"fmt"
"github.com/brave-intl/challenge-bypass-server/model"
"strings"
"time"
crypto "github.com/brave-intl/challenge-bypass-ristretto-ffi"
avroSchema "github.com/brave-intl/challenge-bypass-server/avro/generated"
"github.com/brave-intl/challenge-bypass-server/btd"
cbpServer "github.com/brave-intl/challenge-bypass-server/server"
"github.com/brave-intl/challenge-bypass-server/utils"
"github.com/rs/zerolog"
"github.com/segmentio/kafka-go"
)
/*
SignedTokenRedeemHandler emits payment tokens that correspond to the signed confirmation
tokens provided. If it encounters a permanent error, it emits a permanent result for that
item. If the error is temporary, an error is returned to indicate that progress cannot be
made.
*/
type SignedIssuerToken struct {
issuer model.Issuer
signingKey *crypto.SigningKey
}
func SignedTokenRedeemHandler(
msg kafka.Message,
producer *kafka.Writer,
server *cbpServer.Server,
log *zerolog.Logger,
) error {
data := msg.Value
// Deserialize request into usable struct
tokenRedeemRequestSet, err := avroSchema.DeserializeRedeemRequestSet(bytes.NewReader(data))
if err != nil {
message := fmt.Sprintf("request %s: failed avro deserialization", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
logger := log.With().Str("request_id", tokenRedeemRequestSet.Request_id).Logger()
var redeemedTokenResults []avroSchema.RedeemResult
// For the time being, we are only accepting one message at a time in this data set.
// Therefore, we will error if more than a single message is present in the message.
if len(tokenRedeemRequestSet.Data) > 1 {
// NOTE: When we start supporting multiple requests we will need to review
// errors and return values as well.
message := fmt.Sprintf("request %s: data array unexpectedly contained more than a single message. This array is intended to make future extension easier, but no more than a single value is currently expected", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
errors.New("multiple messages"),
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
issuers, err := server.FetchAllIssuers()
if err != nil {
if processingError, ok := err.(*utils.ProcessingError); ok && processingError.Temporary {
return processingError
}
message := fmt.Sprintf("request %s: failed to fetch all issuers", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
// Create a lookup for issuers & signing keys based on public key
signedTokens := make(map[string]SignedIssuerToken)
for _, issuer := range issuers {
if !issuer.ExpiresAtTime().IsZero() && issuer.ExpiresAtTime().Before(time.Now()) {
continue
}
for _, issuerKey := range issuer.Keys {
// Don't use keys outside their start/end dates
if issuerTimeIsNotValid(issuerKey.StartAt, issuerKey.EndAt) {
continue
}
signingKey := issuerKey.CryptoSigningKey()
issuerPublicKey := signingKey.PublicKey()
marshaledPublicKey, mErr := issuerPublicKey.MarshalText()
// Unmarshalling failure is a data issue and is probably permanent.
if mErr != nil {
message := fmt.Sprintf("request %s: could not unmarshal issuer public key into text", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
signedTokens[string(marshaledPublicKey)] = SignedIssuerToken{
issuer: issuer,
signingKey: signingKey,
}
}
}
// Iterate over requests (only one at this point but the schema can support more
// in the future if needed)
for _, request := range tokenRedeemRequestSet.Data {
var (
verified = false
verifiedIssuer = &model.Issuer{}
verifiedCohort int32
)
if request.Public_key == "" {
logger.Error().
Err(fmt.Errorf("request %s: missing public key", tokenRedeemRequestSet.Request_id)).
Msg("signed token redeem handler")
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: "",
Issuer_cohort: 0,
Status: avroSchema.RedeemResultStatusError,
Associated_data: request.Associated_data,
})
continue
}
// preimage, signature, and binding are all required to proceed
if request.Token_preimage == "" || request.Signature == "" || request.Binding == "" {
logger.Error().
Err(fmt.Errorf("request %s: empty request", tokenRedeemRequestSet.Request_id)).
Msg("signed token redeem handler")
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: "",
Issuer_cohort: 0,
Status: avroSchema.RedeemResultStatusError,
Associated_data: request.Associated_data,
})
continue
}
tokenPreimage := crypto.TokenPreimage{}
err = tokenPreimage.UnmarshalText([]byte(request.Token_preimage))
// Unmarshaling failure is a data issue and is probably permanent.
if err != nil {
message := fmt.Sprintf("request %s: could not unmarshal text into preimage", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
verificationSignature := crypto.VerificationSignature{}
err = verificationSignature.UnmarshalText([]byte(request.Signature))
// Unmarshaling failure is a data issue and is probably permanent.
if err != nil {
message := fmt.Sprintf("request %s: could not unmarshal text into verification signature", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
if signedToken, ok := signedTokens[request.Public_key]; ok {
logger.
Trace().
Str("requestID", tokenRedeemRequestSet.Request_id).
Str("publicKey", request.Public_key).
Msg("attempting token redemption verification")
issuer := signedToken.issuer
if err := btd.VerifyTokenRedemption(
&tokenPreimage,
&verificationSignature,
request.Binding,
[]*crypto.SigningKey{signedToken.signingKey},
); err == nil {
verified = true
verifiedIssuer = &issuer
verifiedCohort = int32(issuer.IssuerCohort)
}
}
if !verified {
logger.Error().
Err(fmt.Errorf("request %s: could not verify that the token redemption is valid",
tokenRedeemRequestSet.Request_id)).
Msg("signed token redeem handler")
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: "",
Issuer_cohort: 0,
Status: avroSchema.RedeemResultStatusUnverified,
Associated_data: request.Associated_data,
})
continue
} else {
logger.Info().Msg(fmt.Sprintf("request %s: validated", tokenRedeemRequestSet.Request_id))
}
redemption, equivalence, err := server.CheckRedeemedTokenEquivalence(verifiedIssuer, &tokenPreimage, request.Binding, msg.Offset)
if err != nil {
var processingError *utils.ProcessingError
if errors.As(err, &processingError) {
if processingError.Temporary {
return err
}
}
message := fmt.Sprintf("request %s: failed to check redemption equivalence", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
// Continue if there is a duplicate
switch equivalence {
case cbpServer.IDEquivalence:
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: verifiedIssuer.IssuerType,
Issuer_cohort: int32(verifiedIssuer.IssuerCohort),
Status: avroSchema.RedeemResultStatusDuplicate_redemption,
Associated_data: request.Associated_data,
})
continue
case cbpServer.BindingEquivalence:
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: verifiedIssuer.IssuerType,
Issuer_cohort: int32(verifiedIssuer.IssuerCohort),
Status: avroSchema.RedeemResultStatusIdempotent_redemption,
Associated_data: request.Associated_data,
})
continue
}
// If no equivalent record was found in the database, persist.
if err := server.PersistRedemption(*redemption); err != nil {
logger.Error().Err(err).Msgf("request %s: token redemption failed: %e", tokenRedeemRequestSet.Request_id, err)
// In the unlikely event that there is a race condition that results
// in a duplicate error upon save that was not detected previously
// we will check equivalence upon receipt of a duplicate error.
if strings.Contains(err.Error(), "Duplicate") {
_, equivalence, err := server.CheckRedeemedTokenEquivalence(verifiedIssuer, &tokenPreimage, request.Binding, msg.Offset)
if err != nil {
message := fmt.Sprintf("request %s: failed to check redemption equivalence", tokenRedeemRequestSet.Request_id)
var processingError *utils.ProcessingError
if errors.As(err, &processingError) {
if processingError.Temporary {
return err
}
}
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
logger.Error().Err(fmt.Errorf("request %s: duplicate redemption: %w",
tokenRedeemRequestSet.Request_id, err)).
Msg("signed token redeem handler")
// Continue if there is a duplicate
switch equivalence {
case cbpServer.IDEquivalence:
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: verifiedIssuer.IssuerType,
Issuer_cohort: int32(verifiedIssuer.IssuerCohort),
Status: avroSchema.RedeemResultStatusDuplicate_redemption,
Associated_data: request.Associated_data,
})
continue
case cbpServer.BindingEquivalence:
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: verifiedIssuer.IssuerType,
Issuer_cohort: int32(verifiedIssuer.IssuerCohort),
Status: avroSchema.RedeemResultStatusIdempotent_redemption,
Associated_data: request.Associated_data,
})
continue
}
}
logger.Error().Err(fmt.Errorf("request %s: could not mark token redemption",
tokenRedeemRequestSet.Request_id)).
Msg("signed token redeem handler")
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: verifiedIssuer.IssuerType,
Issuer_cohort: int32(verifiedIssuer.IssuerCohort),
Status: avroSchema.RedeemResultStatusError,
Associated_data: request.Associated_data,
})
continue
}
logger.Trace().Msgf("request %s: redeemed", tokenRedeemRequestSet.Request_id)
issuerName := verifiedIssuer.IssuerType
redeemedTokenResults = append(redeemedTokenResults, avroSchema.RedeemResult{
Issuer_name: issuerName,
Issuer_cohort: verifiedCohort,
Status: avroSchema.RedeemResultStatusOk,
Associated_data: request.Associated_data,
})
}
resultSet := avroSchema.RedeemResultSet{
Request_id: tokenRedeemRequestSet.Request_id,
Data: redeemedTokenResults,
}
var resultSetBuffer bytes.Buffer
err = resultSet.Serialize(&resultSetBuffer)
if err != nil {
message := fmt.Sprintf("request %s: failed to serialize result set", tokenRedeemRequestSet.Request_id)
handlePermanentRedemptionError(
message,
err,
msg,
producer,
tokenRedeemRequestSet.Request_id,
int32(avroSchema.RedeemResultStatusError),
log,
)
return nil
}
err = Emit(producer, resultSetBuffer.Bytes(), log)
if err != nil {
message := fmt.Sprintf(
"request %s: failed to emit results to topic %s",
resultSet.Request_id,
producer.Topic,
)
log.Error().Err(err).Msgf(message)
return err
}
return nil
}
func issuerTimeIsNotValid(start *time.Time, end *time.Time) bool {
if start != nil && end != nil {
now := time.Now()
startIsNotZeroAndAfterNow := !start.IsZero() && start.After(now)
endIsNotZeroAndBeforeNow := !end.IsZero() && end.Before(now)
return startIsNotZeroAndAfterNow || endIsNotZeroAndBeforeNow
}
// Both times being nil is valid
bothTimesAreNil := start == nil && end == nil
return !bothTimesAreNil
}
// avroRedeemErrorResultFromError returns a ProcessingResult that is constructed from the
// provided values.
func avroRedeemErrorResultFromError(
message string,
msg kafka.Message,
producer *kafka.Writer,
requestID string,
redeemResultStatus int32,
logger *zerolog.Logger,
) *ProcessingResult {
redeemResult := avroSchema.RedeemResult{
Issuer_name: "",
Issuer_cohort: 0,
Status: avroSchema.RedeemResultStatus(redeemResultStatus),
Associated_data: []byte(message),
}
resultSet := avroSchema.RedeemResultSet{
Request_id: "",
Data: []avroSchema.RedeemResult{redeemResult},
}
var resultSetBuffer bytes.Buffer
err := resultSet.Serialize(&resultSetBuffer)
if err != nil {
message := fmt.Sprintf("request %s: failed to serialize result set", requestID)
return &ProcessingResult{
Message: []byte(message),
ResultProducer: producer,
RequestID: requestID,
}
}
return &ProcessingResult{
Message: resultSetBuffer.Bytes(),
ResultProducer: producer,
RequestID: requestID,
}
}
// handleRedemptionError is a convenience function that executes a call pattern shared
// when handling all errors in the redeem flow
func handlePermanentRedemptionError(
message string,
cause error,
msg kafka.Message,
producer *kafka.Writer,
requestID string,
redeemResultStatus int32,
logger *zerolog.Logger,
) {
logger.Error().Err(cause).Msgf("encountered permanent redemption failure: %v", message)
processingResult := avroRedeemErrorResultFromError(
message,
msg,
producer,
requestID,
int32(avroSchema.RedeemResultStatusError),
logger,
)
if err := Emit(producer, processingResult.Message, logger); err != nil {
logger.Error().Err(err).Msg("failed to emit")
}
}