-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathcontrollers.go
1663 lines (1305 loc) · 56.6 KB
/
controllers.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package skus
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
"github.com/asaskevich/govalidator"
"github.com/go-chi/chi"
"github.com/go-chi/cors"
"github.com/go-playground/validator/v10"
uuid "github.com/satori/go.uuid"
"github.com/stripe/stripe-go/v72/webhook"
appctx "github.com/brave-intl/bat-go/libs/context"
"github.com/brave-intl/bat-go/libs/handlers"
"github.com/brave-intl/bat-go/libs/inputs"
"github.com/brave-intl/bat-go/libs/logging"
"github.com/brave-intl/bat-go/libs/middleware"
"github.com/brave-intl/bat-go/libs/requestutils"
"github.com/brave-intl/bat-go/libs/responses"
"github.com/brave-intl/bat-go/services/skus/handler"
"github.com/brave-intl/bat-go/services/skus/model"
"github.com/brave-intl/bat-go/services/skus/radom"
)
const (
reqBodyLimit10MB = 10 << 20
)
type middlewareFn func(next http.Handler) http.Handler
func Router(
svc *Service,
authMwr middlewareFn,
metricsMwr middleware.InstrumentHandlerDef,
copts cors.Options,
) chi.Router {
r := chi.NewRouter()
orderh := handler.NewOrder(svc)
corsMwrPost := NewCORSMwr(copts, http.MethodPost)
if os.Getenv("ENV") == "local" {
r.Method(
http.MethodOptions,
"/",
metricsMwr("CreateOrderOptions", corsMwrPost(nil)),
)
r.Method(
http.MethodPost,
"/",
metricsMwr(
"CreateOrder",
corsMwrPost(handlers.AppHandler(orderh.Create)),
),
)
} else {
r.Method(http.MethodPost, "/", metricsMwr("CreateOrder", handlers.AppHandler(orderh.Create)))
}
{
corsMwrGet := NewCORSMwr(copts, http.MethodGet)
r.Method(http.MethodOptions, "/{orderID}", metricsMwr("GetOrderOptions", corsMwrGet(nil)))
r.Method(http.MethodGet, "/{orderID}", metricsMwr("GetOrder", corsMwrGet(handleGetOrder(svc))))
}
r.Method(
http.MethodDelete,
"/{orderID}",
metricsMwr("CancelOrder", NewCORSMwr(copts, http.MethodDelete)(authMwr(CancelOrder(svc)))),
)
r.Method(
http.MethodPatch,
"/{orderID}/set-trial",
metricsMwr("SetOrderTrialDays", NewCORSMwr(copts, http.MethodPatch)(authMwr(handleSetOrderTrialDays(svc)))),
)
r.Method(http.MethodGet, "/{orderID}/transactions", metricsMwr("GetTransactions", GetTransactions(svc)))
r.Method(http.MethodPost, "/{orderID}/transactions/uphold", metricsMwr("CreateUpholdTransaction", CreateUpholdTransaction(svc)))
r.Method(http.MethodPost, "/{orderID}/transactions/gemini", metricsMwr("CreateGeminiTransaction", CreateGeminiTransaction(svc)))
r.Method(
http.MethodPost,
"/{orderID}/transactions/anonymousCard",
metricsMwr("CreateAnonCardTransaction", CreateAnonCardTransaction(svc)),
)
// Receipt validation.
{
valid := validator.New()
// /submit-receipt is deprecated.
// Use /receipt instead.
// It received 0 requests in June 2024.
r.Method(http.MethodPost, "/{orderID}/submit-receipt", metricsMwr("SubmitReceipt", corsMwrPost(handleSubmitReceipt(svc, valid))))
r.Method(http.MethodPost, "/receipt", metricsMwr("createOrderFromReceipt", corsMwrPost(handleCreateOrderFromReceipt(svc, valid))))
r.Method(http.MethodPost, "/{orderID}/receipt", metricsMwr("checkOrderReceipt", authMwr(handleCheckOrderReceipt(svc, valid))))
}
credh := handler.NewCred(svc)
r.Route("/{orderID}/credentials", func(cr chi.Router) {
cr.Use(NewCORSMwr(copts, http.MethodGet, http.MethodPost))
cr.Method(http.MethodGet, "/", metricsMwr("GetOrderCreds", GetOrderCreds(svc)))
cr.Method(http.MethodPost, "/", metricsMwr("CreateOrderCreds", CreateOrderCreds(svc)))
cr.Method(http.MethodDelete, "/", metricsMwr("DeleteOrderCreds", authMwr(deleteOrderCreds(svc))))
// For now, this endpoint is placed directly under /credentials.
// It would make sense to put it under /items/item_id, had the caller known the item id.
// However, the caller of this endpoint does not possess that knowledge, and it would have to call the order endpoint to get it.
// This extra round-trip currently does not make sense.
// So until Bundles came along we can benefit from the fact that there is one item per order.
// By the time Bundles arrive, the caller would either have to fetch order anyway, or this can be communicated in another way.
cr.Method(http.MethodGet, "/batches/count", metricsMwr("CountBatches", authMwr(handlers.AppHandler(credh.CountBatches))))
// Handle the old endpoint while the new is being rolled out:
// - true: the handler uses itemID as the request id, which is the old mode;
// - false: the handler uses the requestID from the URI.
cr.Method(http.MethodGet, "/{itemID}", metricsMwr("GetOrderCredsByID", getOrderCredsByID(svc, true)))
cr.Method(http.MethodGet, "/items/{itemID}/batches/{requestID}", metricsMwr("GetOrderCredsByID", getOrderCredsByID(svc, false)))
cr.Method(http.MethodPut, "/items/{itemID}/batches/{requestID}", metricsMwr("CreateOrderItemCreds", createItemCreds(svc)))
})
return r
}
// CredentialRouter handles requests to /v1/credentials.
func CredentialRouter(svc *Service, authMwr middlewareFn) chi.Router {
r := chi.NewRouter()
valid := validator.New()
r.Method(
http.MethodPost,
"/subscription/verifications",
middleware.InstrumentHandler("handleVerifyCredV1", authMwr(handleVerifyCredV1(svc, valid))),
)
return r
}
// CredentialV2Router handles requests to /v2/credentials.
func CredentialV2Router(svc *Service, authMwr middlewareFn) chi.Router {
r := chi.NewRouter()
valid := validator.New()
r.Method(
http.MethodPost,
"/subscription/verifications",
middleware.InstrumentHandler("handleVerifyCredV2", authMwr(handleVerifyCredV2(svc, valid))),
)
return r
}
// MerchantRouter handles calls made for the merchant
func MerchantRouter(service *Service) chi.Router {
r := chi.NewRouter()
if os.Getenv("ENV") != "local" {
r.Use(middleware.SimpleTokenAuthorizedOnly)
}
// Once instrument handler is refactored https://github.com/brave-intl/bat-go/issues/291
// We can use this service context instead of having
r.Use(middleware.NewServiceCtx(service))
// RESTy routes for "merchant" resource
r.Route("/", func(r chi.Router) {
r.Route("/{merchantID}", func(mr chi.Router) {
mr.Route("/keys", func(kr chi.Router) {
kr.Method("GET", "/", middleware.InstrumentHandler("GetKeys", GetKeys(service)))
kr.Method("POST", "/", middleware.InstrumentHandler("CreateKey", CreateKey(service)))
kr.Method("DELETE", "/{id}", middleware.InstrumentHandler("DeleteKey", DeleteKey(service)))
})
mr.Route("/transactions", func(kr chi.Router) {
kr.Method("GET", "/", middleware.InstrumentHandler("MerchantTransactions", MerchantTransactions(service)))
})
})
})
return r
}
// DeleteKeyRequest includes information needed to delete a key
type DeleteKeyRequest struct {
DelaySeconds int `json:"delaySeconds" valid:"-"`
}
// CreateKeyRequest includes information needed to create a key
type CreateKeyRequest struct {
Name string `json:"name" valid:"required"`
}
// CreateKeyResponse includes information about the created key
type CreateKeyResponse struct {
*Key
SecretKey string `json:"secretKey"`
}
// CreateKey is the handler for creating keys for a merchant
func CreateKey(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
reqMerchant := chi.URLParam(r, "merchantID")
var req CreateKeyRequest
err := requestutils.ReadJSON(r.Context(), r.Body, &req)
if err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
encrypted, nonce, err := GenerateSecret()
if err != nil {
return handlers.WrapError(err, "Could not generate a secret key ", http.StatusInternalServerError)
}
key, err := service.Datastore.CreateKey(reqMerchant, req.Name, encrypted, nonce)
if err != nil {
return handlers.WrapError(err, "Error create api keys", http.StatusInternalServerError)
}
sk, err := key.GetSecretKey()
if err != nil {
return handlers.WrapError(err, "Error create api keys", http.StatusInternalServerError)
}
if sk == nil {
err = errors.New("secret key was nil")
return handlers.WrapError(err, "Error create api keys", http.StatusInternalServerError)
}
resp := CreateKeyResponse{
Key: key,
SecretKey: *sk,
}
return handlers.RenderContent(r.Context(), resp, w, http.StatusOK)
})
}
// DeleteKey deletes a key
func DeleteKey(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
var id = new(inputs.ID)
if err := inputs.DecodeAndValidateString(context.Background(), id, chi.URLParam(r, "id")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"id": err.Error(),
},
)
}
var req DeleteKeyRequest
err := requestutils.ReadJSON(r.Context(), r.Body, &req)
if err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
_, err = govalidator.ValidateStruct(req)
if err != nil {
return handlers.WrapValidationError(err)
}
key, err := service.Datastore.DeleteKey(*id.UUID(), req.DelaySeconds)
if err != nil {
return handlers.WrapError(err, "Error updating keys for the merchant", http.StatusInternalServerError)
}
status := http.StatusOK
if key == nil {
status = http.StatusNotFound
}
return handlers.RenderContent(r.Context(), key, w, status)
})
}
// GetKeys returns all keys for a specified merchant
func GetKeys(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
merchantID := chi.URLParam(r, "merchantID")
expired := r.URL.Query().Get("expired")
showExpired := expired == "true"
var keys *[]Key
keys, err := service.Datastore.GetKeysByMerchant(merchantID, showExpired)
if err != nil {
return handlers.WrapError(err, "Error Getting Keys for Merchant", http.StatusInternalServerError)
}
return handlers.RenderContent(r.Context(), keys, w, http.StatusOK)
})
}
// VoteRouter for voting endpoint
func VoteRouter(service *Service, instrumentHandler middleware.InstrumentHandlerDef) chi.Router {
r := chi.NewRouter()
r.Method("POST", "/", instrumentHandler("MakeVote", MakeVote(service)))
return r
}
func handleSetOrderTrialDays(svc *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
orderID, err := uuid.FromString(chi.URLParamFromCtx(ctx, "orderID"))
if err != nil {
return handlers.ValidationError("request", map[string]interface{}{"orderID": err.Error()})
}
data, err := io.ReadAll(io.LimitReader(r.Body, reqBodyLimit10MB))
if err != nil {
return handlers.WrapError(err, "failed to read request body", http.StatusBadRequest)
}
req := &model.SetTrialDaysRequest{}
if err := json.Unmarshal(data, req); err != nil {
return handlers.WrapError(err, "failed to parse request", http.StatusBadRequest)
}
now := time.Now().UTC()
if err := svc.setOrderTrialDays(ctx, orderID, req, now); err != nil {
return handlers.WrapError(err, "Error setting the trial days on the order", http.StatusInternalServerError)
}
return handlers.RenderContent(ctx, struct{}{}, w, http.StatusOK)
})
}
// CancelOrder handles requests for cancelling orders.
func CancelOrder(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
orderID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{"orderID": err.Error()},
)
}
oid := *orderID.UUID()
if err := service.validateOrderMerchantAndCaveats(ctx, oid); err != nil {
return handlers.WrapError(err, "Error validating auth merchant and caveats", http.StatusForbidden)
}
if err := service.CancelOrderLegacy(oid); err != nil {
return handlers.WrapError(err, "Error retrieving the order", http.StatusInternalServerError)
}
return handlers.RenderContent(ctx, struct{}{}, w, http.StatusOK)
})
}
func handleGetOrder(svc *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
orderID, err := uuid.FromString(chi.URLParamFromCtx(ctx, "orderID"))
if err != nil {
return handlers.ValidationError("request", map[string]interface{}{"orderID": err.Error()})
}
order, err := svc.getTransformOrder(ctx, orderID)
if err != nil {
switch {
case errors.Is(err, context.Canceled):
return handlers.WrapError(model.ErrSomethingWentWrong, "request has been cancelled", model.StatusClientClosedConn)
case errors.Is(err, model.ErrOrderNotFound):
return handlers.WrapError(err, "order not found", http.StatusNotFound)
default:
return handlers.WrapError(err, "Error retrieving the order", http.StatusInternalServerError)
}
}
return handlers.RenderContent(ctx, order, w, http.StatusOK)
})
}
// GetTransactions is the handler for listing the transactions for an order
func GetTransactions(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
var orderID = new(inputs.ID)
if err := inputs.DecodeAndValidateString(context.Background(), orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
transactions, err := service.Datastore.GetTransactions(*orderID.UUID())
if err != nil {
return handlers.WrapError(err, "Error retrieving the transactions", http.StatusInternalServerError)
}
return handlers.RenderContent(r.Context(), transactions, w, http.StatusOK)
})
}
// CreateTransactionRequest includes information needed to create a transaction
type CreateTransactionRequest struct {
ExternalTransactionID string `json:"externalTransactionId" valid:"required,uuid"`
}
// CreateGeminiTransaction creates a transaction against an order
func CreateGeminiTransaction(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
var req CreateTransactionRequest
err := requestutils.ReadJSON(r.Context(), r.Body, &req)
if err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
var orderID = new(inputs.ID)
if err := inputs.DecodeAndValidateString(context.Background(), orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
_, err = govalidator.ValidateStruct(req)
if err != nil {
return handlers.WrapValidationError(err)
}
// Ensure the external transaction ID hasn't already been added to any orders.
transaction, err := service.Datastore.GetTransaction(req.ExternalTransactionID)
if err != nil {
return handlers.WrapError(err, "externalTransactinID has already been submitted to an order", http.StatusConflict)
}
if transaction != nil {
// if the transaction is already added, then do an update
transaction, err = service.UpdateTransactionFromRequest(r.Context(), req, *orderID.UUID(), service.getGeminiCustodialTx)
if err != nil {
return handlers.WrapError(err, "Error updating the transaction", http.StatusBadRequest)
}
// return 200 in event of already created transaction
return handlers.RenderContent(r.Context(), transaction, w, http.StatusOK)
}
transaction, err = service.CreateTransactionFromRequest(r.Context(), req, *orderID.UUID(), service.getGeminiCustodialTx)
if err != nil {
return handlers.WrapError(err, "Error creating the transaction", http.StatusBadRequest)
}
return handlers.RenderContent(r.Context(), transaction, w, http.StatusCreated)
})
}
// CreateUpholdTransaction creates a transaction against an order
func CreateUpholdTransaction(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
var req CreateTransactionRequest
err := requestutils.ReadJSON(r.Context(), r.Body, &req)
if err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
var orderID = new(inputs.ID)
if err := inputs.DecodeAndValidateString(context.Background(), orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
_, err = govalidator.ValidateStruct(req)
if err != nil {
return handlers.WrapValidationError(err)
}
// Ensure the external transaction ID hasn't already been added to any orders.
transaction, err := service.Datastore.GetTransaction(req.ExternalTransactionID)
if err != nil {
return handlers.WrapError(err, "externalTransactinID has already been submitted to an order", http.StatusConflict)
}
if transaction != nil {
// if the transaction is already added, then do an update
transaction, err = service.UpdateTransactionFromRequest(r.Context(), req, *orderID.UUID(), getUpholdCustodialTxWithRetries)
if err != nil {
return handlers.WrapError(err, "Error updating the transaction", http.StatusBadRequest)
}
// return 200 in event of already created transaction
return handlers.RenderContent(r.Context(), transaction, w, http.StatusOK)
}
transaction, err = service.CreateTransactionFromRequest(r.Context(), req, *orderID.UUID(), getUpholdCustodialTxWithRetries)
if err != nil {
return handlers.WrapError(err, "Error creating the transaction", http.StatusBadRequest)
}
return handlers.RenderContent(r.Context(), transaction, w, http.StatusCreated)
})
}
// CreateAnonCardTransactionRequest includes information needed to create a anon card transaction
type CreateAnonCardTransactionRequest struct {
WalletID uuid.UUID `json:"paymentId"`
Transaction string `json:"transaction"`
}
// CreateAnonCardTransaction creates a transaction against an order
func CreateAnonCardTransaction(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
sublogger := logging.Logger(ctx, "payments").With().
Str("func", "CreateAnonCardTransaction").
Logger()
var req CreateAnonCardTransactionRequest
err := requestutils.ReadJSON(r.Context(), r.Body, &req)
if err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
var orderID = new(inputs.ID)
if err := inputs.DecodeAndValidateString(context.Background(), orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
transaction, err := service.CreateAnonCardTransaction(r.Context(), req.WalletID, req.Transaction, *orderID.UUID())
if err != nil {
sublogger.Error().Err(err).Msg("failed to create anon card transaction")
return handlers.WrapError(err, "Error creating anon card transaction", http.StatusInternalServerError)
}
return handlers.RenderContent(r.Context(), transaction, w, http.StatusCreated)
})
}
// CreateOrderCredsRequest includes the item ID and blinded credentials which to be signed.
type CreateOrderCredsRequest struct {
ItemID uuid.UUID `json:"itemId" valid:"-"`
BlindedCreds []string `json:"blindedCreds" valid:"base64"`
}
// CreateOrderCreds handles requests for creating credentials.
func CreateOrderCreds(svc *Service) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
lg := logging.Logger(ctx, "skus.CreateOrderCreds")
req := &CreateOrderCredsRequest{}
if err := requestutils.ReadJSON(ctx, r.Body, req); err != nil {
lg.Error().Err(err).Msg("failed to read body payload")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
if _, err := govalidator.ValidateStruct(req); err != nil {
lg.Error().Err(err).Msg("failed to validate struct")
return handlers.WrapValidationError(err)
}
orderID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, orderID, chi.URLParam(r, "orderID")); err != nil {
lg.Error().Err(err).Msg("failed to validate order id")
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
// Use the itemID for the request id so the old credential uniqueness constraint remains enforced.
reqID := req.ItemID
if err := svc.CreateOrderItemCredentials(ctx, *orderID.UUID(), req.ItemID, reqID, req.BlindedCreds); err != nil {
lg.Err(err).Msg("failed to create the order credentials")
switch {
case errors.Is(err, model.ErrOrderNotFound):
return handlers.WrapError(err, "order not found", http.StatusNotFound)
case errors.Is(err, errCredsAlreadySubmittedMismatch):
return handlers.WrapError(err, "Order credentials already exist", http.StatusConflict)
default:
return handlers.WrapError(err, "Error creating order creds", http.StatusBadRequest)
}
}
return handlers.RenderContent(ctx, struct{}{}, w, http.StatusOK)
}
}
// createItemCredsRequest includes the blinded credentials to be signed.
type createItemCredsRequest struct {
BlindedCreds []string `json:"blindedCreds" valid:"base64"`
}
// createItemCreds handles requests for creating credentials for an item.
func createItemCreds(svc *Service) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
b, err := io.ReadAll(io.LimitReader(r.Body, reqBodyLimit10MB))
if err != nil {
return handlers.WrapError(err, "error reading body", http.StatusBadRequest)
}
req := &createItemCredsRequest{}
if err := json.Unmarshal(b, req); err != nil {
return handlers.WrapError(err, "error decoding body", http.StatusBadRequest)
}
ctx := r.Context()
lg := logging.Logger(ctx, "skus.createItemCreds")
if _, err := govalidator.ValidateStruct(req); err != nil {
lg.Error().Err(err).Msg("failed to validate struct")
return handlers.WrapValidationError(err)
}
orderID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, orderID, chi.URLParamFromCtx(ctx, "orderID")); err != nil {
lg.Error().Err(err).Msg("failed to validate order id")
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"orderID": err.Error(),
})
}
itemID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, itemID, chi.URLParamFromCtx(ctx, "itemID")); err != nil {
lg.Error().Err(err).Msg("failed to validate item id")
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"itemID": err.Error(),
})
}
reqID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, reqID, chi.URLParamFromCtx(ctx, "requestID")); err != nil {
lg.Error().Err(err).Msg("failed to validate request id")
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"requestID": err.Error(),
})
}
if err := svc.CreateOrderItemCredentials(ctx, *orderID.UUID(), *itemID.UUID(), *reqID.UUID(), req.BlindedCreds); err != nil {
lg.Err(err).Msg("failed to create the order credentials")
switch {
case errors.Is(err, model.ErrOrderNotFound):
return handlers.WrapError(err, "order not found", http.StatusNotFound)
case errors.Is(err, errCredsAlreadySubmittedMismatch):
return handlers.WrapError(err, "Order credentials already exist", http.StatusConflict)
default:
return handlers.WrapError(err, "Error creating order creds", http.StatusBadRequest)
}
}
return handlers.RenderContent(ctx, struct{}{}, w, http.StatusOK)
}
}
// GetOrderCreds is the handler for fetching all order credentials associated with an order.
// This endpoint handles the retrieval of all order credential types i.e. single-use, time-limited and time-limited-v2.
func GetOrderCreds(service *Service) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
var orderID = new(inputs.ID)
if err := inputs.DecodeAndValidateString(ctx, orderID, chi.URLParam(r, "orderID")); err != nil {
return handlers.ValidationError(
"Error validating request url parameter",
map[string]interface{}{
"orderID": err.Error(),
},
)
}
l := logging.Logger(ctx, "skus").With().Str("func", "GetOrderCreds").Logger()
creds, status, err := service.GetCredentials(ctx, *orderID.UUID())
if err != nil {
if errors.Is(err, errSetRetryAfter) {
// error specifies a retry after period, add to response header
avg, err := service.Datastore.GetOutboxMovAvgDurationSeconds()
if err != nil {
return handlers.WrapError(err, "Error getting credential retry-after", status)
}
w.Header().Set("Retry-After", strconv.FormatInt(avg, 10))
} else {
l.Error().Err(err).Str("orderID", orderID.String()).Int("status", status).Msg("failed to get order creds")
return handlers.WrapError(err, "Error getting credentials", status)
}
}
return handlers.RenderContent(ctx, creds, w, status)
}
}
// deleteOrderCreds handles requests for deleting order credentials.
func deleteOrderCreds(service *Service) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
orderID, err := uuid.FromString(chi.URLParamFromCtx(ctx, "orderID"))
if err != nil {
return handlers.ValidationError("orderID", map[string]interface{}{"orderID": err.Error()})
}
if err := service.validateOrderMerchantAndCaveats(ctx, orderID); err != nil {
return handlers.WrapError(err, "Error validating auth merchant and caveats", http.StatusForbidden)
}
isSigned := r.URL.Query().Get("isSigned") == "true"
if err := service.DeleteOrderCreds(ctx, orderID, isSigned); err != nil {
switch {
case errors.Is(err, context.Canceled):
return handlers.WrapError(err, "cliend ended request", model.StatusClientClosedConn)
case errors.Is(err, model.ErrOrderNotFound):
return handlers.WrapError(err, "order not found", http.StatusNotFound)
case errors.Is(err, model.ErrInvalidOrderNoItems):
return handlers.WrapError(err, "order has no items", http.StatusBadRequest)
default:
return handlers.WrapError(model.ErrSomethingWentWrong, "failed to delete credentials", http.StatusBadRequest)
}
}
return handlers.RenderContent(ctx, "Order credentials successfully deleted", w, http.StatusOK)
}
}
// getOrderCredsByID handles requests for fetching order credentials by an item id.
//
// Requests may come in via two endpoints:
// - /{itemID} – legacyMode, reqID == itemID
// - /items/{itemID}/batches/{requestID} – new mode, reqID == requestID.
//
// The legacy mode will be gone after confirming a successful rollout.
//
// TODO: Clean up the legacy mode.
func getOrderCredsByID(svc *Service, legacyMode bool) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
orderID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, orderID, chi.URLParamFromCtx(ctx, "orderID")); err != nil {
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"orderID": err.Error(),
})
}
itemID := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, itemID, chi.URLParamFromCtx(ctx, "itemID")); err != nil {
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"itemID": err.Error(),
})
}
var reqID uuid.UUID
if legacyMode {
reqID = *itemID.UUID()
} else {
reqIDRaw := &inputs.ID{}
if err := inputs.DecodeAndValidateString(ctx, reqIDRaw, chi.URLParamFromCtx(ctx, "requestID")); err != nil {
return handlers.ValidationError("Error validating request url parameter", map[string]interface{}{
"requestID": err.Error(),
})
}
reqID = *reqIDRaw.UUID()
}
l := logging.Logger(ctx, "skus").With().Str("func", "getOrderCredsByID").Logger()
itemIDv := *itemID.UUID()
creds, status, err := svc.GetItemCredentials(ctx, *orderID.UUID(), itemIDv, reqID)
if err != nil {
if !errors.Is(err, errSetRetryAfter) {
l.Error().Err(err).Str("orderID", orderID.String()).Str("itemID", itemIDv.String()).Int("status", status).Msg("failed to get item creds")
return handlers.WrapError(err, "Error getting credentials", status)
}
// Add to response header as error specifies a retry after period.
avg, err := svc.Datastore.GetOutboxMovAvgDurationSeconds()
if err != nil {
return handlers.WrapError(err, "Error getting credential retry-after", status)
}
w.Header().Set("Retry-After", strconv.FormatInt(avg, 10))
}
if legacyMode {
suCreds, ok := creds.([]OrderCreds)
if !ok {
return handlers.WrapError(err, "Error getting credentials", http.StatusInternalServerError)
}
for i := range suCreds {
if uuid.Equal(suCreds[i].ID, itemIDv) {
return handlers.RenderContent(ctx, suCreds[i], w, status)
}
}
return handlers.WrapError(err, "Error getting credentials", http.StatusNotFound)
}
if creds == nil {
return handlers.RenderContent(ctx, map[string]interface{}{}, w, status)
}
return handlers.RenderContent(ctx, creds, w, status)
})
}
// VoteRequest includes a suggestion payload and credentials to be redeemed
type VoteRequest struct {
Vote string `json:"vote" valid:"base64"`
Credentials []CredentialBinding `json:"credentials"`
}
// MakeVote is the handler for making a vote using credentials
func MakeVote(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
req := VoteRequest{}
if err := requestutils.ReadJSON(ctx, r.Body, &req); err != nil {
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
if _, err := govalidator.ValidateStruct(req); err != nil {
return handlers.WrapValidationError(err)
}
lg := logging.Logger(ctx, "skus").With().Str("func", "MakeVote").Logger()
if err := service.Vote(ctx, req.Credentials, req.Vote); err != nil {
switch err.(type) {
case govalidator.Error:
lg.Warn().Err(err).Msg("failed vote validation")
return handlers.WrapValidationError(err)
case govalidator.Errors:
lg.Warn().Err(err).Msg("failed multiple vote validation")
return handlers.WrapValidationError(err)
default:
// check for custom vote invalidations
if errors.Is(err, ErrInvalidSKUToken) {
verr := handlers.ValidationError("failed to validate sku token", nil)
data := []string{}
if errors.Is(err, ErrInvalidSKUTokenSKU) {
data = append(data, "invalid sku value")
}
if errors.Is(err, ErrInvalidSKUTokenBadMerchant) {
data = append(data, "invalid merchant value")
}
verr.Data = data
lg.Warn().Err(err).Msg("failed sku validations")
return verr
}
lg.Warn().Err(err).Msg("failed to perform vote")
return handlers.WrapError(err, "Error making vote", http.StatusBadRequest)
}
}
w.WriteHeader(http.StatusOK)
return nil
})
}
// MerchantTransactions is the handler for getting paginated merchant transactions
func MerchantTransactions(service *Service) handlers.AppHandler {
return handlers.AppHandler(func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
// inputs
// /merchants/{merchantID}/transactions?page=1&items=50&order=id
var (
merchantID, mIDErr = inputs.NewMerchantID(r.Context(), chi.URLParam(r, "merchantID"))
ctx, pagination, pIDErr = inputs.NewPagination(r.Context(), r.URL.String(), new(Transaction))
)
// Check Validation Errors
if mIDErr != nil {
return handlers.WrapValidationError(mIDErr)
}
if pIDErr != nil {
return handlers.WrapValidationError(pIDErr)
}
// Get Paginated Results
transactions, total, err := service.Datastore.GetPagedMerchantTransactions(
ctx, merchantID.UUID(), pagination)
if err != nil {
return handlers.WrapError(err, "error getting transactions", http.StatusInternalServerError)
}
// Build Response
response := &responses.PaginationResponse{
Page: pagination.Page,
Items: pagination.Items,
MaxPage: total/pagination.Items - 1, // 0 indexed
Ordered: pagination.RawOrder,
Data: transactions,
}
// render response
if err := response.Render(ctx, w, http.StatusOK); err != nil {
return handlers.WrapError(err, "error rendering response", http.StatusInternalServerError)
}
return nil
})
}
func handleVerifyCredV2(svc *Service, valid *validator.Validate) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
lg := logging.Logger(ctx, "skus").With().Str("func", "handleVerifyCredV2").Logger()
data, err := io.ReadAll(io.LimitReader(r.Body, reqBodyLimit10MB))
if err != nil {
lg.Warn().Err(err).Msg("failed to read body")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
req, err := parseVerifyCredRequestV2(data)
if err != nil {
lg.Warn().Err(err).Msg("failed to parse request")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
if err := validateVerifyCredRequestV2(valid, req); err != nil {
lg.Warn().Err(err).Msg("failed to validate request")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
aerr := svc.verifyCredential(ctx, req, w)
if aerr != nil {
lg.Err(aerr).Msg("failed to verify credential")
}
return aerr
}
}
func handleVerifyCredV1(svc *Service, valid *validator.Validate) handlers.AppHandler {
return func(w http.ResponseWriter, r *http.Request) *handlers.AppError {
ctx := r.Context()
lg := logging.Logger(ctx, "skus").With().Str("func", "handleVerifyCredV1").Logger()
data, err := io.ReadAll(io.LimitReader(r.Body, reqBodyLimit10MB))
if err != nil {
lg.Warn().Err(err).Msg("failed to read body")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}
req := &model.VerifyCredentialRequestV1{}
if err := json.Unmarshal(data, req); err != nil {
lg.Warn().Err(err).Msg("failed to parse request")
return handlers.WrapError(err, "Error in request body", http.StatusBadRequest)
}