This repository has been archived by the owner on Apr 5, 2023. It is now read-only.
/
operations.go
2381 lines (1926 loc) · 74.5 KB
/
operations.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package operation
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
oidclib "github.com/coreos/go-oidc"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/hyperledger/aries-framework-go/pkg/client/didexchange"
"github.com/hyperledger/aries-framework-go/pkg/client/issuecredential"
"github.com/hyperledger/aries-framework-go/pkg/client/mediator"
"github.com/hyperledger/aries-framework-go/pkg/client/outofband"
"github.com/hyperledger/aries-framework-go/pkg/client/outofbandv2"
"github.com/hyperledger/aries-framework-go/pkg/client/presentproof"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/common/model"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/common/service"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/messaging/msghandler"
"github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/decorator"
didexdsvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/didexchange"
issuecredsvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/issuecredential"
mediatorsvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/mediator"
presentproofsvc "github.com/hyperledger/aries-framework-go/pkg/didcomm/protocol/presentproof"
"github.com/hyperledger/aries-framework-go/pkg/doc/cm"
"github.com/hyperledger/aries-framework-go/pkg/doc/did"
"github.com/hyperledger/aries-framework-go/pkg/doc/presexch"
"github.com/hyperledger/aries-framework-go/pkg/doc/util"
"github.com/hyperledger/aries-framework-go/pkg/doc/verifiable"
"github.com/hyperledger/aries-framework-go/pkg/framework/aries/api/vdr"
"github.com/hyperledger/aries-framework-go/pkg/store/connection"
"github.com/hyperledger/aries-framework-go/pkg/wallet"
"github.com/hyperledger/aries-framework-go/spi/storage"
"github.com/piprate/json-gold/ld"
"github.com/trustbloc/edge-core/pkg/log"
"golang.org/x/oauth2"
"github.com/trustbloc/edge-adapter/pkg/aries"
adaptercrypto "github.com/trustbloc/edge-adapter/pkg/crypto"
"github.com/trustbloc/edge-adapter/pkg/internal/common/support"
"github.com/trustbloc/edge-adapter/pkg/memcmdescriptor"
"github.com/trustbloc/edge-adapter/pkg/profile/issuer"
"github.com/trustbloc/edge-adapter/pkg/restapi"
commhttp "github.com/trustbloc/edge-adapter/pkg/restapi/internal/common/http"
walletops "github.com/trustbloc/edge-adapter/pkg/restapi/wallet/operation"
"github.com/trustbloc/edge-adapter/pkg/route"
adaptervc "github.com/trustbloc/edge-adapter/pkg/vc"
issuervc "github.com/trustbloc/edge-adapter/pkg/vc/issuer"
)
var logger = log.New("edge-adapter/issuerops")
const (
// API endpoints
issuerBasePath = "/issuer"
didCommBasePath = issuerBasePath + "/didcomm"
profileEndpoint = "/profile"
getProfileEndpoint = profileEndpoint + "/{id}"
walletConnectEndpoint = "/{id}/connect/wallet"
getCredentialInteractionRequestEndpoint = didCommBasePath + "/interaction/request"
validateConnectResponseEndpoint = "/connect/validate"
oidcAuthRequestEndpoint = "/oidc/request"
oidcCallbackEndpoint = "/oidc/cb"
// http params
idPathParam = "id"
txnIDQueryParam = "txnID"
stateQueryParam = "state"
redirectURLFmt = "%s?state=%s"
userIDQueryParam = "uID"
credScopeQueryParam = "cred"
txnStoreName = "issuer_txn"
tokenStoreName = "issuer_token"
oidcClientStoreName = "issuer_oidc_client"
refreshTokenStoreName = "issuer_refresh_token"
// oob invitation constants
oobGoalCode = "streamlined-vc"
// protocol
didExCompletedState = "completed"
// DIDConnectCHAPIQueryType CHAPI query type DIDConnect
DIDConnectCHAPIQueryType = "DIDConnect"
// credential custom fields
vcFieldName = "name"
vcFieldDescription = "description"
issuerWalletBridgeLabel = "issuer_wallet_bridge"
// WACI interaction constants
credentialManifestFormat = "dif/credential-manifest/manifest@v1.0"
credentialManifestVersion = "0.1.0"
credentialFulfillmentFormat = "dif/credential-manifest/fulfillment@v1.0"
offerCredentialAttachMediaType = "application/json"
redirectStatusOK = "OK"
redirectStatusError = "FAIL"
redirectErrorURL = "/error"
manifestIDSuffix = "_mID"
manifestDataPrefix = "manifest_"
presDefDataPrefix = "presDef_"
fulfillmentDataPrefix = "full_"
)
type connections interface {
GetConnectionIDByDIDs(string, string) (string, error)
GetConnectionRecord(string) (*connection.Record, error)
}
// PublicDIDCreator creates public DIDs.
type PublicDIDCreator interface {
Create() (*did.Doc, error)
CreateV2() (*did.Doc, error)
}
type mediatorClientProvider interface {
Service(id string) (interface{}, error)
}
type routeService interface {
GetDIDDoc(connID string, requiresBlindedRoute bool) (*did.Doc, error)
}
type didExClient interface {
RegisterActionEvent(chan<- service.DIDCommAction) error
RegisterMsgEvent(chan<- service.StateMsg) error
CreateConnection(string, *did.Doc, ...didexchange.ConnectionOption) (string, error)
GetConnection(connectionID string) (*didexchange.Connection, error)
}
type credentialOffered struct {
FulFillment *verifiable.Presentation
ManifestID string
PresentationDefID string
}
type cmDescriptorProvider interface {
FetchCMDescriptorsByScope(scope string) (*memcmdescriptor.CMAttachmentDescriptors, bool)
}
// Config defines configuration for issuer operations.
// TODO #580 Create helper function for cmDescriptors
type Config struct {
AriesCtx aries.CtxProvider
AriesMessenger service.Messenger
MsgRegistrar *msghandler.Registrar
UIEndpoint string
StoreProvider storage.Provider
PublicDIDCreator PublicDIDCreator
TLSConfig *tls.Config
WalletBridgeAppURL string
OIDCClientStoreKey []byte
ExternalURL string
DidDomain string
JSONLDDocumentLoader ld.DocumentLoader
CMDescriptors cmDescriptorProvider
}
// New returns issuer rest instance.
func New(config *Config) (*Operation, error) { // nolint:funlen,gocyclo,cyclop
oobClient, err := outofbandClient(config.AriesCtx)
if err != nil {
return nil, fmt.Errorf("failed to create aries outofband client : %w", err)
}
oobv2Client, err := outofbandV2Client(config.AriesCtx)
if err != nil {
return nil, fmt.Errorf("failed to create aries outofband v2 client : %w", err)
}
mediatorClient, err := mediatorClient(config.AriesCtx)
if err != nil {
return nil, fmt.Errorf("failed to create aries mediator client : %w", err)
}
stateMsgCh := make(chan service.StateMsg, 1)
didExClient, err := didExchangeClient(config.AriesCtx, stateMsgCh)
if err != nil {
return nil, fmt.Errorf("failed to create aries did exchange client : %w", err)
}
actionCh := make(chan service.DIDCommAction, 1)
issueCredClient, err := issueCredentialClient(config.AriesCtx, actionCh)
if err != nil {
return nil, fmt.Errorf("failed to create aries issue credential client : %w", err)
}
presentProofClient, err := presentProofClient(config.AriesCtx, actionCh)
if err != nil {
return nil, fmt.Errorf("failed to create aries present proof client : %w", err)
}
p, err := issuer.New(config.StoreProvider)
if err != nil {
return nil, fmt.Errorf("failed to init new issuer profile: %w", err)
}
txnStore, err := config.StoreProvider.OpenStore(txnStoreName)
if err != nil {
return nil, fmt.Errorf("failed to open store %s: %w", txnStoreName, err)
}
tokenStore, err := config.StoreProvider.OpenStore(tokenStoreName)
if err != nil {
return nil, fmt.Errorf("failed to open store %s: %w", tokenStoreName, err)
}
oidcClientStore, err := config.StoreProvider.OpenStore(oidcClientStoreName)
if err != nil {
return nil, fmt.Errorf("failed to open store %s: %w", oidcClientStoreName, err)
}
refreshStore, err := config.StoreProvider.OpenStore(refreshTokenStoreName)
if err != nil {
return nil, fmt.Errorf("failed to open store %s: %w", refreshTokenStoreName, err)
}
connectionLookup, err := connection.NewLookup(config.AriesCtx)
if err != nil {
return nil, fmt.Errorf("failed to initialize connection lookup : %w", err)
}
s, err := config.AriesCtx.Service(mediatorsvc.Coordination)
if err != nil {
return nil, fmt.Errorf("failed to lookup aries mediator coordination service: %w", err)
}
mediatorSvc, ok := s.(mediatorsvc.ProtocolService)
if !ok {
return nil, errors.New("cast service to Route Service failed")
}
routeSvc, err := route.New(&route.Config{
VDRIRegistry: config.AriesCtx.VDRegistry(),
AriesMessenger: config.AriesMessenger,
MsgRegistrar: config.MsgRegistrar,
DIDExchangeClient: didExClient,
MediatorClient: mediatorClient,
ServiceEndpoint: config.AriesCtx.ServiceEndpoint(),
Store: config.StoreProvider,
ConnectionLookup: connectionLookup,
MediatorSvc: mediatorSvc,
KeyManager: config.AriesCtx.KMS(),
KeyType: config.AriesCtx.KeyType(),
KeyAgrType: config.AriesCtx.KeyAgreementType(),
})
if err != nil {
return nil, fmt.Errorf("create message service : %w", err)
}
vccrypto := adaptercrypto.New(
config.AriesCtx.KMS(),
config.AriesCtx.Crypto(),
config.AriesCtx.VDRegistry(),
config.JSONLDDocumentLoader,
)
walletBridge, err := walletops.New(&walletops.Config{
AriesCtx: config.AriesCtx,
MsgRegistrar: config.MsgRegistrar,
WalletAppURL: config.WalletBridgeAppURL,
DefaultLabel: issuerWalletBridgeLabel,
})
if err != nil {
return nil, fmt.Errorf("failed to initialize wallet bridge : %w", err)
}
op := &Operation{
oobClient: oobClient,
oobV2Client: oobv2Client,
didExClient: didExClient,
issueCredClient: issueCredClient,
presentProofClient: presentProofClient,
uiEndpoint: config.UIEndpoint,
profileStore: p,
txnStore: txnStore,
tokenStore: tokenStore,
connectionLookup: connectionLookup,
vdriRegistry: config.AriesCtx.VDRegistry(),
serviceEndpoint: config.AriesCtx.ServiceEndpoint(),
vccrypto: vccrypto,
publicDIDCreator: config.PublicDIDCreator,
httpClient: &http.Client{Transport: &http.Transport{TLSClientConfig: config.TLSConfig}},
routeSvc: routeSvc,
messenger: config.AriesMessenger,
walletBridge: walletBridge,
tlsConfig: config.TLSConfig,
cachedOIDCClients: map[string]oidcClient{},
oidcClientStore: oidcClientStore,
oidcClientStoreKey: config.OIDCClientStoreKey,
oidcCallbackURL: config.ExternalURL + oidcCallbackEndpoint,
userTokens: map[string]*oauth2.Token{},
refreshTokenStore: refreshStore,
didDomain: config.DidDomain,
jsonldDocLoader: config.JSONLDDocumentLoader,
cmDescriptors: config.CMDescriptors,
}
op.createOIDCClientFunc = op.getOrCreateOIDCClient
op.getOIDCClientFunc = op.getOIDCClient
go op.didCommActionListener(actionCh)
go op.didCommStateMsgListener(stateMsgCh)
return op, nil
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
type oidcClient interface {
CreateOIDCRequest(state, scope string) string
HandleOIDCCallback(context.Context, string) (*oauth2.Token, *oidclib.IDToken, error)
CheckRefresh(tok *oauth2.Token) (*oauth2.Token, error)
}
// Operation defines handlers for rp operations.
type Operation struct {
oobClient *outofband.Client
oobV2Client *outofbandv2.Client
didExClient didExClient
issueCredClient *issuecredential.Client
presentProofClient *presentproof.Client
uiEndpoint string
profileStore *issuer.Profile
txnStore storage.Store
tokenStore storage.Store
connectionLookup connections
vdriRegistry vdr.Registry
vccrypto adaptervc.Crypto
serviceEndpoint string
publicDIDCreator PublicDIDCreator
httpClient httpClient
routeSvc routeService
messenger service.Messenger
walletBridge *walletops.Operation
tlsConfig *tls.Config
oidcCallbackURL string
cachedOIDCClients map[string]oidcClient
userTokens map[string]*oauth2.Token // keyed by the txn ID
oidcClientStore storage.Store
oidcClientStoreKey []byte
refreshTokenStore storage.Store
createOIDCClientFunc func(profileData *issuer.ProfileData) (oidcClient, error)
getOIDCClientFunc func(string, string) (oidcClient, error)
didDomain string
jsonldDocLoader ld.DocumentLoader
cmDescriptors cmDescriptorProvider
}
// GetRESTHandlers get all controller API handler available for this service.
func (o *Operation) GetRESTHandlers() []restapi.Handler {
return append([]restapi.Handler{
// profile
support.NewHTTPHandler(profileEndpoint, http.MethodPost, o.createIssuerProfileHandler),
support.NewHTTPHandler(getProfileEndpoint, http.MethodGet, o.getIssuerProfileHandler),
// didcomm
support.NewHTTPHandler(walletConnectEndpoint, http.MethodGet, o.walletConnectHandler),
support.NewHTTPHandler(validateConnectResponseEndpoint, http.MethodPost, o.validateWalletResponseHandler),
support.NewHTTPHandler(getCredentialInteractionRequestEndpoint, http.MethodGet, o.getCredentialInteractionRequestHandler), // nolint:lll
support.NewHTTPHandler(oidcAuthRequestEndpoint, http.MethodGet, o.requestOIDCAuthHandler),
support.NewHTTPHandler(oidcCallbackEndpoint, http.MethodGet, o.oidcAuthCallback),
}, o.walletBridge.GetRESTHandlers()...)
}
// TODO #581 Validate and check Waci profile creation that each scope has output descriptors configured.
func (o *Operation) createIssuerProfileHandler( // nolint:funlen,gocyclo,cyclop
rw http.ResponseWriter, req *http.Request) {
data := &ProfileDataRequest{}
if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("invalid request: %s", err.Error()), profileEndpoint, logger)
return
}
var newDidDoc *did.Doc
var err error
if data.IsDIDCommV1 {
newDidDoc, err = o.publicDIDCreator.Create()
} else {
newDidDoc, err = o.publicDIDCreator.CreateV2()
}
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to create public did : %s", err.Error()), profileEndpoint, logger)
return
}
profileData, err := mapProfileReqToData(data, newDidDoc)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to map request to issuer profile: %s", err.Error()),
profileEndpoint, logger)
return
}
if profileData.SupportsWACI {
for _, pCredScope := range profileData.CredentialScopes {
if _, ok := o.cmDescriptors.FetchCMDescriptorsByScope(pCredScope); !ok {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("failed to find the allowed cred scope in credential manifest output descriptor "+
"object -> %s", pCredScope), profileEndpoint, logger)
return
}
}
}
if profileData.OIDCProviderURL != "" {
_, err = o.createOIDCClientFunc(profileData)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to create oidc client: %s", err.Error()), profileEndpoint, logger)
return
}
}
err = o.profileStore.SaveProfile(profileData)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("failed to create profile: %s", err.Error()), profileEndpoint, logger)
return
}
rw.WriteHeader(http.StatusCreated)
commhttp.WriteResponseWithLog(rw, profileData, profileEndpoint, logger)
}
func (o *Operation) getIssuerProfileHandler(rw http.ResponseWriter, req *http.Request) {
profileID := mux.Vars(req)[idPathParam]
profile, err := o.profileStore.GetProfile(profileID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("id=%s - %s", profileID, err.Error()), getProfileEndpoint, logger)
return
}
commhttp.WriteResponseWithLog(rw, profile, getProfileEndpoint, logger)
}
func (o *Operation) walletConnectHandler(rw http.ResponseWriter, req *http.Request) {
profileID := mux.Vars(req)[idPathParam]
profile, err := o.profileStore.GetProfile(profileID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("id=%s - %s", profileID, err.Error()), walletConnectEndpoint, logger)
return
}
state := req.URL.Query().Get(stateQueryParam)
cred := strings.Trim(req.FormValue(credScopeQueryParam), " ")
switch {
case state != "":
o.walletConnectStateFlow(rw, req, profile, state)
case cred != "":
o.credScopeHandler(rw, req, profile, cred)
default:
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
"failed to get state from the url", walletConnectEndpoint, logger)
}
}
func (o *Operation) walletConnectStateFlow(
rw http.ResponseWriter, req *http.Request, profile *issuer.ProfileData, state string) {
tknResp, err := o.retrieveIssuerToken(profile, state)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to get token from to the issuer : %s", err.Error()), walletConnectEndpoint, logger)
return
}
if tknResp.Token == "" || tknResp.UserID == "" {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
"received empty token info from the issuer", walletConnectEndpoint, logger)
return
}
// store the txn data
txnID, err := o.createTxnWithState(profile, state, tknResp.Token)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to create txn : %s", err.Error()), walletConnectEndpoint, logger)
return
}
rURL := fmt.Sprintf("%s?%s=%s&%s=%s", o.uiEndpoint, txnIDQueryParam,
txnID, userIDQueryParam, tknResp.UserID)
// if we're using oidc, redirect to oidc initiation instead
if profile.OIDCProviderURL != "" {
rURL = fmt.Sprintf("%s?%s=%s&%s=%s", oidcAuthRequestEndpoint,
txnIDQueryParam, txnID, userIDQueryParam, tknResp.UserID)
}
http.Redirect(rw, req, rURL, http.StatusFound)
}
func (o *Operation) credScopeHandler(rw http.ResponseWriter, req *http.Request, profile *issuer.ProfileData,
credScope string) {
has := false
for _, scope := range profile.CredentialScopes {
if scope == credScope {
has = true
break
}
}
if !has {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
"issuer profile does not allow request of credential scope "+credScope, walletConnectEndpoint, logger)
return
}
txnID, err := o.createTxnWithCredScope(profile, credScope)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to create txn : %s", err.Error()), walletConnectEndpoint, logger)
return
}
rURL := fmt.Sprintf("%s?%s=%s", oidcAuthRequestEndpoint, txnIDQueryParam, txnID)
http.Redirect(rw, req, rURL, http.StatusFound)
}
// requestOIDCAuthHandler endpoint requests OIDC authorization from the current user
// expects a GET containing txnID and uID query parameters.
// responds with an http redirect to the requested oidc provider's authorization endpoint
func (o *Operation) requestOIDCAuthHandler(rw http.ResponseWriter, req *http.Request) { // nolint:funlen
txnID := req.FormValue(txnIDQueryParam)
if txnID == "" {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
"missing txn ID from request", oidcAuthRequestEndpoint, logger)
return
}
txn, err := o.getTxn(txnID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
"invalid txn ID", oidcAuthRequestEndpoint, logger)
return
}
profile, err := o.profileStore.GetProfile(txn.IssuerID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
"invalid request, issuer ID was not registered with adapter", oidcAuthRequestEndpoint, logger)
return
}
expire := time.Now().AddDate(0, 0, 1)
userID := req.FormValue(userIDQueryParam)
if userID != "" {
userIDCookie := http.Cookie{
Name: "userID",
Value: userID,
Expires: expire,
}
http.SetCookie(rw, &userIDCookie)
}
_, err = o.getOIDCAccessToken(txnID, profile)
if err == nil { // if there was NO error, we still have a valid access/refresh token, and can skip login&consent
rURL := fmt.Sprintf("%s?%s=%s&%s=%s", o.uiEndpoint,
txnIDQueryParam, txnID, userIDQueryParam, userID)
http.Redirect(rw, req, rURL, http.StatusFound)
return
}
client, err := o.getOIDCClientFunc(profile.ID, profile.OIDCProviderURL)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("get oidc client: %s", err.Error()), oidcAuthRequestEndpoint, logger)
return
}
// TODO: package and encrypt data cookies into a single ciphertext to create the state variable
stateBytes := make([]byte, 24)
_, err = rand.Read(stateBytes)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("create oidc state : %s", err.Error()), oidcAuthRequestEndpoint, logger)
return
}
state := base64.RawURLEncoding.EncodeToString(stateBytes)
stateCookie := http.Cookie{
Name: "oidcState",
Value: state,
Expires: expire,
}
http.SetCookie(rw, &stateCookie)
opURLCookie := http.Cookie{
Name: "oidcProvider",
Value: profile.OIDCProviderURL,
Expires: expire,
}
http.SetCookie(rw, &opURLCookie)
txnIDCookie := http.Cookie{
Name: "txnID",
Value: txnID,
Expires: expire,
}
http.SetCookie(rw, &txnIDCookie)
scopes := "openid offline_access"
if txn.CredScope != "" {
scopes += " " + txn.CredScope
}
authURL := client.CreateOIDCRequest(state, scopes)
http.Redirect(rw, req, authURL, http.StatusFound)
}
// OIDC callback from the OIDC provider through the auth code flow
func (o *Operation) oidcAuthCallback(rw http.ResponseWriter, req *http.Request) { // nolint:funlen,gocyclo,cyclop
stateCookie, err := req.Cookie("oidcState")
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("missing state cookie: %v", err), oidcCallbackEndpoint, logger)
return
}
cbState := req.FormValue("state")
if stateCookie.Value != cbState {
commhttp.WriteErrorResponseWithLog(rw, http.StatusUnauthorized,
"oauth state variable does not match", oidcCallbackEndpoint, logger)
return
}
txnCookie, err := req.Cookie("txnID")
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("missing txn id cookie: %v", err), oidcCallbackEndpoint, logger)
return
}
txn, err := o.getTxn(txnCookie.Value)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
"invalid txn ID", oidcAuthRequestEndpoint, logger)
return
}
authCode := req.FormValue("code")
profile, err := o.profileStore.GetProfile(txn.IssuerID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
"invalid request, issuer ID was not registered with adapter", oidcAuthRequestEndpoint, logger)
return
}
client, err := o.getOIDCClientFunc(txn.IssuerID, profile.OIDCProviderURL)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to initialize oidc client: %v", err), oidcCallbackEndpoint, logger)
return
}
token, _, err := client.HandleOIDCCallback(req.Context(), authCode)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to handle oidc callback: %v", err), oidcCallbackEndpoint, logger)
return
}
err = o.refreshTokenStore.Put(txnCookie.Value, []byte(token.RefreshToken))
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to save refresh token: %v", err), oidcCallbackEndpoint, logger)
return
}
o.userTokens[txnCookie.Value] = token
var userID string
userCookie, err := req.Cookie("userID")
if err == nil {
userID = userCookie.Value
} else if userID, err = o.retrieveUserID(profile.URL, token.AccessToken); err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("missing userID cookie, failed to fetch userID from issuer: %v", err),
oidcCallbackEndpoint, logger)
return
}
rURL := fmt.Sprintf("%s?%s=%s&%s=%s", o.uiEndpoint,
txnIDQueryParam, txnCookie.Value, userIDQueryParam, userID)
http.Redirect(rw, req, rURL, http.StatusFound)
}
func (o *Operation) retrieveUserID(issuerURL, bearerToken string) (string, error) {
req, err := http.NewRequest(http.MethodGet, getUserIDURL(issuerURL), nil)
if err != nil {
return "", fmt.Errorf("create userID request : %w", err)
}
respBytes, err := sendHTTPRequest(req, o.httpClient, http.StatusOK, bearerToken)
if err != nil {
return "", fmt.Errorf("call issuer userID service : %w", err)
}
var dataResp *IssuerTokenResp
err = json.Unmarshal(respBytes, &dataResp)
if err != nil {
return "", fmt.Errorf("issuer response parse error : %w", err)
}
return dataResp.UserID, nil
}
func (o *Operation) getOIDCAccessToken(txnID string, profile *issuer.ProfileData) (string, error) {
tok, ok := o.userTokens[txnID]
if !ok {
refresh, err := o.refreshTokenStore.Get(txnID)
if err != nil {
return "", fmt.Errorf("failed to fetch refresh token: %w", err)
}
tok = &oauth2.Token{RefreshToken: string(refresh)}
}
client, err := o.getOIDCClientFunc(profile.ID, profile.OIDCProviderURL)
if err != nil {
return "", fmt.Errorf("failed to fetch oidc client: %w", err)
}
tok2, err := client.CheckRefresh(tok)
if err != nil {
return "", fmt.Errorf("failed to check refresh token: %w", err)
}
o.userTokens[txnID] = tok2
if tok2.RefreshToken != tok.RefreshToken {
err = o.refreshTokenStore.Put(txnID, []byte(tok2.RefreshToken))
if err != nil {
return "", fmt.Errorf("failed to save refresh token: %w", err)
}
}
return tok2.AccessToken, nil
}
func (o *Operation) validateWalletResponseHandler(rw http.ResponseWriter, req *http.Request) { // nolint: funlen
// get the txnID
txnID := req.URL.Query().Get(txnIDQueryParam)
if txnID == "" {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest, "failed to get txnID from the url",
validateConnectResponseEndpoint, logger)
return
}
// validate the response
connectResp := &WalletConnect{}
if err := json.NewDecoder(req.Body).Decode(&connectResp); err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("invalid request: %s", err.Error()), validateConnectResponseEndpoint, logger)
return
}
// get txnID data from the storage
txnData, err := o.getTxn(txnID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("txn data not found: %s", err.Error()), validateConnectResponseEndpoint, logger)
return
}
connectData, err := issuervc.ParseWalletResponse(connectResp.Resp, o.jsonldDocLoader)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("failed to validate presentation: %s", err.Error()), validateConnectResponseEndpoint, logger)
return
}
conn, err := o.validateAndGetConnection(connectData)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("failed to validate DIDComm connection: %s", err.Error()),
validateConnectResponseEndpoint, logger)
return
}
profile, err := o.profileStore.GetProfile(txnData.IssuerID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("profile not found: %s", err.Error()), validateConnectResponseEndpoint, logger)
return
}
userConnMap := &UserConnectionMapping{
ConnectionID: conn.ConnectionID,
IssuerID: txnData.IssuerID,
Token: txnData.Token,
TxnID: txnID,
}
err = o.storeUserConnectionMapping(userConnMap)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to store user connection mapping: %s", err.Error()),
validateConnectResponseEndpoint, logger)
return
}
redirectURL := fmt.Sprintf(redirectURLFmt, getCallBackURL(profile.URL), txnData.State)
rw.WriteHeader(http.StatusOK)
commhttp.WriteResponseWithLog(rw,
&ValidateConnectResp{RedirectURL: redirectURL}, validateConnectResponseEndpoint, logger)
}
func (o *Operation) getCredentialInteractionRequestHandler(rw http.ResponseWriter, req *http.Request) { // nolint:funlen,gocyclo,cyclop,lll
// get the txnID
txnID := req.URL.Query().Get(txnIDQueryParam)
if txnID == "" {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest, "failed to get txnID from the url",
getCredentialInteractionRequestEndpoint, logger)
return
}
// get txnID data from the storage
txnData, err := o.getTxn(txnID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusBadRequest,
fmt.Sprintf("txn data not found: %s", err.Error()), getCredentialInteractionRequestEndpoint, logger)
return
}
profile, err := o.profileStore.GetProfile(txnData.IssuerID)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("issuer not found: %s", err.Error()), getCredentialInteractionRequestEndpoint, logger)
return
}
manifestVC, err := issuervc.CreateManifestCredential(profile.Name, profile.SupportedVCContexts)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("error creating manifest vc : %s", err.Error()),
getCredentialInteractionRequestEndpoint, logger)
return
}
// optional oidc + oauth
oauthToken := ""
if profile.OIDCProviderURL != "" {
oauthToken, err = o.getOIDCAccessToken(txnID, profile)
if err != nil {
return
}
}
// if WACI enabled
if profile.SupportsWACI {
var walletRedirect string
if profile.LinkedWalletURL != "" {
invBytes, e := json.Marshal(txnData.DIDCommInvitation)
if e != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to unmarshal invitation : %s", err),
getCredentialInteractionRequestEndpoint, logger)
return
}
walletRedirect = fmt.Sprintf("%s?oob=%s", profile.LinkedWalletURL,
base64.URLEncoding.EncodeToString(invBytes))
}
err = o.storeUserInvitationMapping(&UserInvitationMapping{
InvitationID: txnData.DIDCommInvitation.ID,
IssuerID: txnData.IssuerID,
TxID: txnID,
TxToken: txnData.Token,
State: txnData.State,
})
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("failed to save user invitation mapping : %s", err),
getCredentialInteractionRequestEndpoint, logger)
return
}
commhttp.WriteResponseWithLog(rw, &CredentialHandlerRequest{
WACI: true,
WalletRedirect: walletRedirect,
DIDCommInvitation: txnData.DIDCommInvitation,
}, getCredentialInteractionRequestEndpoint, logger)
logger.Debugf("[waci] wallet redirect: %+v", walletRedirect)
return
}
// prepare credentials to be sent and append manifest credential
credentials := append([]json.RawMessage{}, manifestVC)
if profile.SupportsAssuranceCredential {
vcBytes, err := o.createReferenceCredential(txnData.Token, oauthToken, profile)
if err != nil {
commhttp.WriteErrorResponseWithLog(rw, http.StatusInternalServerError,
fmt.Sprintf("error creating reference credential : %s", err.Error()),
getCredentialInteractionRequestEndpoint, logger)
return
}
credentials = append(credentials, vcBytes)
}