From 055eacc47a340c907068b93875dc2b91d1bd932f Mon Sep 17 00:00:00 2001 From: Neal Date: Mon, 9 Jan 2023 11:32:11 -0600 Subject: [PATCH 1/5] ctx for db write --- pkg/server/router/credential.go | 4 +-- pkg/server/router/did.go | 2 +- pkg/server/router/issuance.go | 2 +- pkg/server/router/keystore.go | 2 +- pkg/server/router/manifest.go | 4 +-- pkg/server/router/presentation.go | 4 +-- pkg/server/router/schema.go | 2 +- pkg/service/credential/service.go | 23 +++++++------- pkg/service/credential/storage.go | 40 +++++++------------------ pkg/service/did/key.go | 7 +++-- pkg/service/did/service.go | 7 +++-- pkg/service/did/storage.go | 5 ++-- pkg/service/did/web.go | 7 +++-- pkg/service/issuing/service.go | 6 ++-- pkg/service/issuing/storage.go | 6 ++-- pkg/service/keystore/service.go | 5 ++-- pkg/service/keystore/storage.go | 12 ++++---- pkg/service/manifest/response.go | 5 ++-- pkg/service/manifest/service.go | 17 ++++++----- pkg/service/manifest/storage/storage.go | 13 ++++---- pkg/service/operation/storage.go | 5 ++-- pkg/service/presentation/service.go | 11 +++---- pkg/service/presentation/storage.go | 9 +++--- pkg/service/schema/service.go | 5 ++-- pkg/service/schema/storage.go | 5 ++-- pkg/storage/bolt.go | 3 +- pkg/storage/redis.go | 4 +-- pkg/storage/storage.go | 3 +- 28 files changed, 111 insertions(+), 107 deletions(-) diff --git a/pkg/server/router/credential.go b/pkg/server/router/credential.go index db5e4a394..eb77e0ad8 100644 --- a/pkg/server/router/credential.go +++ b/pkg/server/router/credential.go @@ -97,7 +97,7 @@ func (cr CredentialRouter) CreateCredential(ctx context.Context, w http.Response } req := request.ToServiceRequest() - createCredentialResponse, err := cr.service.CreateCredential(req) + createCredentialResponse, err := cr.service.CreateCredential(ctx, req) if err != nil { errMsg := "could not create credential" logrus.WithError(err).Error(errMsg) @@ -272,7 +272,7 @@ func (cr CredentialRouter) UpdateCredentialStatus(ctx context.Context, w http.Re } req := request.ToServiceRequest(*id) - gotCredential, err := cr.service.UpdateCredentialStatus(req) + gotCredential, err := cr.service.UpdateCredentialStatus(ctx, req) if err != nil { errMsg := fmt.Sprintf("could not update credential with id: %s", req.ID) diff --git a/pkg/server/router/did.go b/pkg/server/router/did.go index 152afd7b6..0347a8bc9 100644 --- a/pkg/server/router/did.go +++ b/pkg/server/router/did.go @@ -104,7 +104,7 @@ func (dr DIDRouter) CreateDIDByMethod(ctx context.Context, w http.ResponseWriter // TODO(gabe) check if the key type is supported for the method, to tell whether this is a bad req or internal error createDIDRequest := did.CreateDIDRequest{Method: didsdk.Method(*method), KeyType: request.KeyType, DIDWebID: request.DIDWebID} - createDIDResponse, err := dr.service.CreateDIDByMethod(createDIDRequest) + createDIDResponse, err := dr.service.CreateDIDByMethod(ctx, createDIDRequest) if err != nil { errMsg := fmt.Sprintf("could not create DID for method<%s> with key type: %s", *method, request.KeyType) logrus.WithError(err).Error(errMsg) diff --git a/pkg/server/router/issuance.go b/pkg/server/router/issuance.go index 10b7c72e1..3b39ae735 100644 --- a/pkg/server/router/issuance.go +++ b/pkg/server/router/issuance.go @@ -77,7 +77,7 @@ func (ir IssuanceRouter) CreateIssuanceTemplate(ctx context.Context, w http.Resp util.LoggingErrorMsg(err, errMsg), http.StatusBadRequest) } - template, err := ir.service.CreateIssuanceTemplate(request.ToServiceRequest()) + template, err := ir.service.CreateIssuanceTemplate(ctx, request.ToServiceRequest()) if err != nil { return framework.NewRequestError( util.LoggingErrorMsg(err, "creating issuance template"), http.StatusInternalServerError) diff --git a/pkg/server/router/keystore.go b/pkg/server/router/keystore.go index f22b0403d..16fb3c3d7 100644 --- a/pkg/server/router/keystore.go +++ b/pkg/server/router/keystore.go @@ -80,7 +80,7 @@ func (ksr *KeyStoreRouter) StoreKey(ctx context.Context, w http.ResponseWriter, return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusBadRequest) } - if err := ksr.service.StoreKey(*req); err != nil { + if err := ksr.service.StoreKey(ctx, *req); err != nil { errMsg := fmt.Sprintf("could not store key: %s, %s", request.ID, err.Error()) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) diff --git a/pkg/server/router/manifest.go b/pkg/server/router/manifest.go index 105638061..7c0599bf1 100644 --- a/pkg/server/router/manifest.go +++ b/pkg/server/router/manifest.go @@ -94,7 +94,7 @@ func (mr ManifestRouter) CreateManifest(ctx context.Context, w http.ResponseWrit } req := request.ToServiceRequest() - createManifestResponse, err := mr.service.CreateManifest(req) + createManifestResponse, err := mr.service.CreateManifest(ctx, req) if err != nil { errMsg := "could not create manifest" logrus.WithError(err).Error(errMsg) @@ -314,7 +314,7 @@ func (mr ManifestRouter) SubmitApplication(ctx context.Context, w http.ResponseW return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusBadRequest) } - op, err := mr.service.ProcessApplicationSubmission(*req) + op, err := mr.service.ProcessApplicationSubmission(ctx, *req) if err != nil { errMsg := "could not submit application" logrus.WithError(err).Error(errMsg) diff --git a/pkg/server/router/presentation.go b/pkg/server/router/presentation.go index f6bee6ff1..8cccd51cb 100644 --- a/pkg/server/router/presentation.go +++ b/pkg/server/router/presentation.go @@ -76,7 +76,7 @@ func (pr PresentationRouter) CreatePresentationDefinition(ctx context.Context, w logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusBadRequest) } - serviceResp, err := pr.service.CreatePresentationDefinition(model.CreatePresentationDefinitionRequest{PresentationDefinition: *def}) + serviceResp, err := pr.service.CreatePresentationDefinition(ctx, model.CreatePresentationDefinitionRequest{PresentationDefinition: *def}) if err != nil { logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) @@ -244,7 +244,7 @@ func (pr PresentationRouter) CreateSubmission(ctx context.Context, w http.Respon util.LoggingErrorMsg(err, "invalid create submission request"), http.StatusBadRequest) } - operation, err := pr.service.CreateSubmission(*req) + operation, err := pr.service.CreateSubmission(ctx, *req) if err != nil { return framework.NewRequestError( util.LoggingErrorMsg(err, "cannot create submission"), http.StatusInternalServerError) diff --git a/pkg/server/router/schema.go b/pkg/server/router/schema.go index bc7a78ecd..dbe76917d 100644 --- a/pkg/server/router/schema.go +++ b/pkg/server/router/schema.go @@ -71,7 +71,7 @@ func (sr SchemaRouter) CreateSchema(ctx context.Context, w http.ResponseWriter, } req := schema.CreateSchemaRequest{Author: request.Author, Name: request.Name, Schema: request.Schema, Sign: request.Sign} - createSchemaResponse, err := sr.service.CreateSchema(req) + createSchemaResponse, err := sr.service.CreateSchema(ctx, req) if err != nil { errMsg := fmt.Sprintf("could not create schema with authoring DID: %s", request.Author) logrus.WithError(err).Error(errMsg) diff --git a/pkg/service/credential/service.go b/pkg/service/credential/service.go index f0fc11165..d2af40175 100644 --- a/pkg/service/credential/service.go +++ b/pkg/service/credential/service.go @@ -1,6 +1,7 @@ package credential import ( + "context" "fmt" "strconv" "time" @@ -88,7 +89,7 @@ func NewCredentialService(config config.CredentialServiceConfig, s storage.Servi return &service, nil } -func (s Service) CreateCredential(request CreateCredentialRequest) (*CreateCredentialResponse, error) { +func (s Service) CreateCredential(ctx context.Context, request CreateCredentialRequest) (*CreateCredentialResponse, error) { logrus.Debugf("creating credential: %+v", request) @@ -154,12 +155,12 @@ func (s Service) CreateCredential(request CreateCredentialRequest) (*CreateCrede issuerID := request.Issuer schemaID := request.JSONSchema - statusListCredential, err := getStatusListCredential(s, issuerID, schemaID) + statusListCredential, err := getStatusListCredential(ctx, s, issuerID, schemaID) if err != nil { return nil, util.LoggingErrorMsgf(err, "problem with getting status list credential") } - statusListIndex, err := s.storage.GetNextStatusListRandomIndex() + statusListIndex, err := s.storage.GetNextStatusListRandomIndex(ctx) if err != nil { return nil, util.LoggingErrorMsg(err, "problem with getting status list index") } @@ -208,7 +209,7 @@ func (s Service) CreateCredential(request CreateCredentialRequest) (*CreateCrede Container: container, } - if err = s.storage.StoreCredential(storageRequest); err != nil { + if err = s.storage.StoreCredential(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store credential") } @@ -217,7 +218,7 @@ func (s Service) CreateCredential(request CreateCredentialRequest) (*CreateCrede return &response, nil } -func getStatusListCredential(s Service, issuerID string, schemaID string) (*credential.VerifiableCredential, error) { +func getStatusListCredential(ctx context.Context, s Service, issuerID string, schemaID string) (*credential.VerifiableCredential, error) { storedStatusListCreds, err := s.storage.GetStatusListCredentialsByIssuerAndSchema(issuerID, schemaID) if err != nil { return nil, util.LoggingNewErrorf("problem with getting status list credential for issuer: %s schema: %s", issuerID, schemaID) @@ -254,7 +255,7 @@ func getStatusListCredential(s Service, issuerID string, schemaID string) (*cred Container: statusListContainer, } - if err = s.storage.StoreStatusListCredential(storageRequest); err != nil { + if err = s.storage.StoreStatusListCredential(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store credential") } @@ -459,7 +460,7 @@ func (s Service) GetCredentialStatusList(request GetCredentialStatusListRequest) return &response, nil } -func (s Service) UpdateCredentialStatus(request UpdateCredentialStatusRequest) (*UpdateCredentialStatusResponse, error) { +func (s Service) UpdateCredentialStatus(ctx context.Context, request UpdateCredentialStatusRequest) (*UpdateCredentialStatusResponse, error) { logrus.Debugf("updating credential status: %s to Revoked: %v", request.ID, request.Revoked) gotCred, err := s.storage.GetCredential(request.ID) @@ -476,7 +477,7 @@ func (s Service) UpdateCredentialStatus(request UpdateCredentialStatusRequest) ( return &response, nil } - container, err := updateCredentialStatus(s, gotCred, request) + container, err := updateCredentialStatus(ctx, s, gotCred, request) if err != nil { return nil, util.LoggingNewError("problem updating credential") } @@ -485,7 +486,7 @@ func (s Service) UpdateCredentialStatus(request UpdateCredentialStatusRequest) ( return &response, nil } -func updateCredentialStatus(s Service, gotCred *StoredCredential, request UpdateCredentialStatusRequest) (*credint.Container, error) { +func updateCredentialStatus(ctx context.Context, s Service, gotCred *StoredCredential, request UpdateCredentialStatusRequest) (*credint.Container, error) { // store the credential with updated status container := credint.Container{ ID: gotCred.ID, @@ -498,7 +499,7 @@ func updateCredentialStatus(s Service, gotCred *StoredCredential, request Update Container: container, } - if err := s.storage.StoreCredential(storageRequest); err != nil { + if err := s.storage.StoreCredential(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store credential") } @@ -541,7 +542,7 @@ func updateCredentialStatus(s Service, gotCred *StoredCredential, request Update Container: statusListContainer, } - if err = s.storage.StoreStatusListCredential(storageRequest); err != nil { + if err = s.storage.StoreStatusListCredential(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store credential status list") } diff --git a/pkg/service/credential/storage.go b/pkg/service/credential/storage.go index 7a7715fa8..c801555f6 100644 --- a/pkg/service/credential/storage.go +++ b/pkg/service/credential/storage.go @@ -1,6 +1,7 @@ package credential import ( + "context" "fmt" "math/rand" "strings" @@ -78,32 +79,13 @@ func NewCredentialStorage(db storage.ServiceStorage) (*Storage, error) { return nil, errors.New("bolt db reference is nil") } - // TODO: (Neal) there is a current bug with our Bolt implementation where if we do a GET without anything in the db it will throw an error - // Doing initial writes and then deleting will "warm up" our database and when we do a GET after that it will not crash and return empty list - // https://github.com/TBD54566975/ssi-service/issues/176 - if err := db.Write(credentialNamespace, fakeKey, nil); err != nil { - return nil, util.LoggingErrorMsg(err, "problem writing status initial write to db") - - } - if err := db.Delete(credentialNamespace, fakeKey); err != nil { - return nil, util.LoggingErrorMsg(err, "problem with initial delete to db") - } - - if err := db.Write(statusListCredentialNamespace, fakeKey, nil); err != nil { - return nil, util.LoggingErrorMsg(err, "problem writing status initial write to db") - } - - if err := db.Delete(statusListCredentialNamespace, fakeKey); err != nil { - return nil, util.LoggingErrorMsg(err, "problem with initial delete to db") - } - randUniqueList := randomUniqueNum(bitStringLength) uniqueNumBytes, err := json.Marshal(randUniqueList) if err != nil { return nil, util.LoggingErrorMsg(err, "could not marshal random unique numbers") } - if err := db.Write(statusListIndexNamespace, statusListIndexesKey, uniqueNumBytes); err != nil { + if err := db.Write(context.Background(), statusListIndexNamespace, statusListIndexesKey, uniqueNumBytes); err != nil { return nil, util.LoggingErrorMsg(err, "problem writing status list indexes to db") } @@ -112,14 +94,14 @@ func NewCredentialStorage(db storage.ServiceStorage) (*Storage, error) { return nil, util.LoggingErrorMsg(err, "could not marshal status list index bytes") } - if err := db.Write(statusListIndexNamespace, currentListIndexKey, statusListIndexBytes); err != nil { + if err := db.Write(context.Background(), statusListIndexNamespace, currentListIndexKey, statusListIndexBytes); err != nil { return nil, util.LoggingErrorMsg(err, "problem writing current list index to db") } return &Storage{db: db}, nil } -func (cs *Storage) GetNextStatusListRandomIndex() (int, error) { +func (cs *Storage) GetNextStatusListRandomIndex(ctx context.Context) (int, error) { gotUniqueNumBytes, err := cs.db.Read(statusListIndexNamespace, statusListIndexesKey) if err != nil { @@ -150,22 +132,22 @@ func (cs *Storage) GetNextStatusListRandomIndex() (int, error) { return -1, util.LoggingErrorMsg(err, "could not marshal status list index bytes") } - if err := cs.db.Write(statusListIndexNamespace, currentListIndexKey, statusListIndexBytes); err != nil { + if err := cs.db.Write(ctx, statusListIndexNamespace, currentListIndexKey, statusListIndexBytes); err != nil { return -1, util.LoggingErrorMsg(err, "problem writing current list index to db") } return uniqueNums[statusListIndex.Index], nil } -func (cs *Storage) StoreCredential(request StoreCredentialRequest) error { - return cs.storeCredential(request, credentialNamespace) +func (cs *Storage) StoreCredential(ctx context.Context, request StoreCredentialRequest) error { + return cs.storeCredential(ctx, request, credentialNamespace) } -func (cs *Storage) StoreStatusListCredential(request StoreCredentialRequest) error { - return cs.storeCredential(request, statusListCredentialNamespace) +func (cs *Storage) StoreStatusListCredential(ctx context.Context, request StoreCredentialRequest) error { + return cs.storeCredential(ctx, request, statusListCredentialNamespace) } -func (cs *Storage) storeCredential(request StoreCredentialRequest, namespace string) error { +func (cs *Storage) storeCredential(ctx context.Context, request StoreCredentialRequest, namespace string) error { if !request.IsValid() { return util.LoggingNewError("store request request is not valid") } @@ -181,7 +163,7 @@ func (cs *Storage) storeCredential(request StoreCredentialRequest, namespace str return util.LoggingErrorMsgf(err, "could not store request: %s", storedCredential.CredentialID) } // TODO(gabe) conflict checking? - return cs.db.Write(namespace, storedCredential.ID, storedCredBytes) + return cs.db.Write(ctx, namespace, storedCredential.ID, storedCredBytes) } // buildStoredCredential generically parses a store credential request and returns the object to be stored diff --git a/pkg/service/did/key.go b/pkg/service/did/key.go index e1d8196c4..a1a207477 100644 --- a/pkg/service/did/key.go +++ b/pkg/service/did/key.go @@ -1,6 +1,7 @@ package did import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/crypto" @@ -21,7 +22,7 @@ type keyDIDHandler struct { keyStore *keystore.Service } -func (h *keyDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, error) { +func (h *keyDIDHandler) CreateDID(ctx context.Context, request CreateDIDRequest) (*CreateDIDResponse, error) { logrus.Debugf("creating DID: %+v", request) @@ -43,7 +44,7 @@ func (h *keyDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, ID: id, DID: *expanded, } - if err = h.storage.StoreDID(storedDID); err != nil { + if err = h.storage.StoreDID(ctx, storedDID); err != nil { return nil, errors.Wrap(err, "could not store did:key value") } @@ -62,7 +63,7 @@ func (h *keyDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, PrivateKeyBase58: privKeyBase58, } - if err = h.keyStore.StoreKey(keyStoreRequest); err != nil { + if err = h.keyStore.StoreKey(ctx, keyStoreRequest); err != nil { return nil, errors.Wrap(err, "could not store did:key private key") } diff --git a/pkg/service/did/service.go b/pkg/service/did/service.go index 3575038d7..a80a5418e 100644 --- a/pkg/service/did/service.go +++ b/pkg/service/did/service.go @@ -1,6 +1,7 @@ package did import ( + "context" "fmt" didsdk "github.com/TBD54566975/ssi-sdk/did" @@ -97,7 +98,7 @@ func NewDIDService(config config.DIDServiceConfig, s storage.ServiceStorage, key // MethodHandler describes the functionality of *all* possible DID service, regardless of method type MethodHandler interface { - CreateDID(request CreateDIDRequest) (*CreateDIDResponse, error) + CreateDID(ctx context.Context, request CreateDIDRequest) (*CreateDIDResponse, error) GetDID(request GetDIDRequest) (*GetDIDResponse, error) GetDIDs(method didsdk.Method) (*GetDIDsResponse, error) } @@ -137,12 +138,12 @@ func (s *Service) GetSupportedMethods() GetSupportedMethodsResponse { return GetSupportedMethodsResponse{Methods: methods} } -func (s *Service) CreateDIDByMethod(request CreateDIDRequest) (*CreateDIDResponse, error) { +func (s *Service) CreateDIDByMethod(ctx context.Context, request CreateDIDRequest) (*CreateDIDResponse, error) { handler, err := s.getHandler(request.Method) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get handler for method<%s>", request.Method) } - return handler.CreateDID(request) + return handler.CreateDID(ctx, request) } func (s *Service) GetDIDByMethod(request GetDIDRequest) (*GetDIDResponse, error) { diff --git a/pkg/service/did/storage.go b/pkg/service/did/storage.go index 8fb4bda1e..237c1ac9c 100644 --- a/pkg/service/did/storage.go +++ b/pkg/service/did/storage.go @@ -1,6 +1,7 @@ package did import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/did" @@ -41,7 +42,7 @@ func NewDIDStorage(db storage.ServiceStorage) (*Storage, error) { return &Storage{db: db}, nil } -func (ds *Storage) StoreDID(did StoredDID) error { +func (ds *Storage) StoreDID(ctx context.Context, did StoredDID) error { couldNotStoreDIDErr := fmt.Sprintf("could not store DID: %s", did.ID) ns, err := getNamespaceForDID(did.ID) if err != nil { @@ -51,7 +52,7 @@ func (ds *Storage) StoreDID(did StoredDID) error { if err != nil { return util.LoggingErrorMsg(err, couldNotStoreDIDErr) } - return ds.db.Write(ns, did.ID, didBytes) + return ds.db.Write(ctx, ns, did.ID, didBytes) } func (ds *Storage) GetDID(id string) (*StoredDID, error) { diff --git a/pkg/service/did/web.go b/pkg/service/did/web.go index d6f2b27c4..858cfabd9 100644 --- a/pkg/service/did/web.go +++ b/pkg/service/did/web.go @@ -1,6 +1,7 @@ package did import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/crypto" @@ -21,7 +22,7 @@ type webDIDHandler struct { keyStore *keystore.Service } -func (h *webDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, error) { +func (h *webDIDHandler) CreateDID(ctx context.Context, request CreateDIDRequest) (*CreateDIDResponse, error) { logrus.Debugf("creating DID: %+v", request) if request.DIDWebID == "" { @@ -55,7 +56,7 @@ func (h *webDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, ID: id, DID: *doc, } - if err = h.storage.StoreDID(storedDID); err != nil { + if err = h.storage.StoreDID(ctx, storedDID); err != nil { return nil, errors.Wrap(err, "could not store did:web value") } @@ -74,7 +75,7 @@ func (h *webDIDHandler) CreateDID(request CreateDIDRequest) (*CreateDIDResponse, PrivateKeyBase58: privKeyBase58, } - if err = h.keyStore.StoreKey(keyStoreRequest); err != nil { + if err = h.keyStore.StoreKey(ctx, keyStoreRequest); err != nil { return nil, errors.Wrap(err, "could not store did:key private key") } diff --git a/pkg/service/issuing/service.go b/pkg/service/issuing/service.go index 2cc223caa..052092af0 100644 --- a/pkg/service/issuing/service.go +++ b/pkg/service/issuing/service.go @@ -1,6 +1,8 @@ package issuing import ( + "context" + "github.com/google/uuid" "github.com/pkg/errors" "github.com/tbd54566975/ssi-service/config" @@ -50,7 +52,7 @@ func (s *Service) GetIssuanceTemplate(request *GetIssuanceTemplateRequest) (*Get IssuanceTemplate: serviceModel(*storedIssuanceTemplate)}, nil } -func (s *Service) CreateIssuanceTemplate(request *CreateIssuanceTemplateRequest) (*IssuanceTemplate, error) { +func (s *Service) CreateIssuanceTemplate(ctx context.Context, request *CreateIssuanceTemplateRequest) (*IssuanceTemplate, error) { if !request.IsValid() { return nil, errors.New("invalid create issuance template request") } @@ -78,7 +80,7 @@ func (s *Service) CreateIssuanceTemplate(request *CreateIssuanceTemplateRequest) } storedTemplate.IssuanceTemplate.ID = uuid.NewString() - if err := s.storage.StoreIssuanceTemplate(storedTemplate); err != nil { + if err := s.storage.StoreIssuanceTemplate(ctx, storedTemplate); err != nil { return nil, errors.Wrap(err, "storing issuance template") } diff --git a/pkg/service/issuing/storage.go b/pkg/service/issuing/storage.go index 0111992b8..9e3df9650 100644 --- a/pkg/service/issuing/storage.go +++ b/pkg/service/issuing/storage.go @@ -1,6 +1,8 @@ package issuing import ( + "context" + "github.com/goccy/go-json" "github.com/pkg/errors" "github.com/tbd54566975/ssi-service/pkg/storage" @@ -25,7 +27,7 @@ type StoredIssuanceTemplate struct { IssuanceTemplate IssuanceTemplate } -func (s Storage) StoreIssuanceTemplate(template StoredIssuanceTemplate) error { +func (s Storage) StoreIssuanceTemplate(ctx context.Context, template StoredIssuanceTemplate) error { if template.IssuanceTemplate.ID == "" { return errors.New("cannot store issuance template without an ID") } @@ -33,7 +35,7 @@ func (s Storage) StoreIssuanceTemplate(template StoredIssuanceTemplate) error { if err != nil { return errors.Wrap(err, "marshalling template") } - return s.db.Write(namespace, template.IssuanceTemplate.ID, data) + return s.db.Write(ctx, namespace, template.IssuanceTemplate.ID, data) } func (s Storage) GetIssuanceTemplate(id string) (*StoredIssuanceTemplate, error) { diff --git a/pkg/service/keystore/service.go b/pkg/service/keystore/service.go index 2df303707..e31abbf3e 100644 --- a/pkg/service/keystore/service.go +++ b/pkg/service/keystore/service.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "fmt" "time" @@ -70,7 +71,7 @@ func NewKeyStoreService(config config.KeyStoreServiceConfig, s storage.ServiceSt return &service, nil } -func (s Service) StoreKey(request StoreKeyRequest) error { +func (s Service) StoreKey(ctx context.Context, request StoreKeyRequest) error { logrus.Debugf("storing key: %+v", request) @@ -87,7 +88,7 @@ func (s Service) StoreKey(request StoreKeyRequest) error { Base58Key: request.PrivateKeyBase58, CreatedAt: time.Now().Format(time.RFC3339), } - if err := s.storage.StoreKey(key); err != nil { + if err := s.storage.StoreKey(ctx, key); err != nil { return util.LoggingErrorMsgf(err, "could not store key: %s", request.ID) } return nil diff --git a/pkg/service/keystore/storage.go b/pkg/service/keystore/storage.go index 1022b612c..193d2095d 100644 --- a/pkg/service/keystore/storage.go +++ b/pkg/service/keystore/storage.go @@ -1,6 +1,8 @@ package keystore import ( + "context" + "github.com/goccy/go-json" "github.com/mr-tron/base58" "github.com/pkg/errors" @@ -51,19 +53,19 @@ func NewKeyStoreStorage(db storage.ServiceStorage, key ServiceKey) (*Storage, er bolt := &Storage{db: db, serviceKey: keyBytes} // first, store the service key - if err = bolt.storeServiceKey(key); err != nil { + if err = bolt.storeServiceKey(context.Background(), key); err != nil { return nil, errors.Wrap(err, "could not store service key") } return bolt, nil } // TODO(gabe): support more robust service key operations, including rotation, and caching -func (kss *Storage) storeServiceKey(key ServiceKey) error { +func (kss *Storage) storeServiceKey(ctx context.Context, key ServiceKey) error { keyBytes, err := json.Marshal(key) if err != nil { return util.LoggingErrorMsg(err, "could not marshal service key") } - if err = kss.db.Write(namespace, skKey, keyBytes); err != nil { + if err = kss.db.Write(ctx, namespace, skKey, keyBytes); err != nil { return util.LoggingErrorMsg(err, "could store marshal service key") } return nil @@ -97,7 +99,7 @@ func (kss *Storage) getAndSetServiceKey() ([]byte, error) { return keyBytes, nil } -func (kss *Storage) StoreKey(key StoredKey) error { +func (kss *Storage) StoreKey(ctx context.Context, key StoredKey) error { id := key.ID if id == "" { return util.LoggingNewError("could not store key without an ID") @@ -120,7 +122,7 @@ func (kss *Storage) StoreKey(key StoredKey) error { return util.LoggingErrorMsgf(err, "could not encrypt key: %s", key.ID) } - return kss.db.Write(namespace, id, encryptedKey) + return kss.db.Write(ctx, namespace, id, encryptedKey) } func (kss *Storage) GetKey(id string) (*StoredKey, error) { diff --git a/pkg/service/manifest/response.go b/pkg/service/manifest/response.go index c3b8b0b4a..01f46e0a1 100644 --- a/pkg/service/manifest/response.go +++ b/pkg/service/manifest/response.go @@ -1,6 +1,7 @@ package manifest import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/credential/exchange" @@ -37,7 +38,7 @@ func (s Service) signCredentialResponseJWT(signingDID string, r CredentialRespon return responseToken, nil } -func (s Service) buildCredentialResponse(applicantDID, manifestID, applicationID string, credManifest manifest.CredentialManifest) (*manifest.CredentialResponse, []cred.Container, error) { +func (s Service) buildCredentialResponse(ctx context.Context, applicantDID, manifestID, applicationID string, credManifest manifest.CredentialManifest) (*manifest.CredentialResponse, []cred.Container, error) { // TODO(gabe) need to check if this can be fulfilled and conditionally return success/denial responseBuilder := manifest.NewCredentialResponseBuilder(manifestID) if err := responseBuilder.SetApplicationID(applicationID); err != nil { @@ -54,7 +55,7 @@ func (s Service) buildCredentialResponse(applicantDID, manifestID, applicationID Data: make(map[string]any), } - credentialResponse, err := s.credential.CreateCredential(credentialRequest) + credentialResponse, err := s.credential.CreateCredential(ctx, credentialRequest) if err != nil { return nil, nil, util.LoggingErrorMsg(err, "could not create credential") } diff --git a/pkg/service/manifest/service.go b/pkg/service/manifest/service.go index c42d19da4..35c4d059d 100644 --- a/pkg/service/manifest/service.go +++ b/pkg/service/manifest/service.go @@ -1,6 +1,7 @@ package manifest import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/credential/manifest" @@ -91,7 +92,7 @@ type CredentialManifestContainer struct { Manifest manifest.CredentialManifest `json:"credential_manifest"` } -func (s Service) CreateManifest(request model.CreateManifestRequest) (*model.CreateManifestResponse, error) { +func (s Service) CreateManifest(ctx context.Context, request model.CreateManifestRequest) (*model.CreateManifestResponse, error) { logrus.Debugf("creating manifest: %+v", request) @@ -158,7 +159,7 @@ func (s Service) CreateManifest(request model.CreateManifestRequest) (*model.Cre ManifestJWT: *manifestJWT, } - if err = s.storage.StoreManifest(storageRequest); err != nil { + if err = s.storage.StoreManifest(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store manifest") } @@ -227,7 +228,7 @@ type CredentialResponseContainer struct { Credentials []any `json:"verifiableCredentials,omitempty"` } -func (s Service) ProcessApplicationSubmission(request model.SubmitApplicationRequest) (*operation.Operation, error) { +func (s Service) ProcessApplicationSubmission(ctx context.Context, request model.SubmitApplicationRequest) (*operation.Operation, error) { // get the manifest associated with the application manifestID := request.Application.ManifestID gotManifest, err := s.storage.GetManifest(manifestID) @@ -258,7 +259,7 @@ func (s Service) ProcessApplicationSubmission(request model.SubmitApplicationReq Done: true, Response: sarData, } - if err := s.opsStorage.StoreOperation(storedOp); err != nil { + if err := s.opsStorage.StoreOperation(ctx, storedOp); err != nil { return nil, errors.Wrap(err, "storing operation") } @@ -278,12 +279,12 @@ func (s Service) ProcessApplicationSubmission(request model.SubmitApplicationReq Credentials: request.Credentials, ApplicationJWT: request.ApplicationJWT, } - if err = s.storage.StoreApplication(storageRequest); err != nil { + if err = s.storage.StoreApplication(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store application") } // build the credential response - credResp, creds, err := s.buildCredentialResponse(applicantDID, manifestID, applicationID, credManifest) + credResp, creds, err := s.buildCredentialResponse(ctx, applicantDID, manifestID, applicationID, credManifest) if err != nil { return nil, util.LoggingErrorMsg(err, "could not build credential response") } @@ -309,7 +310,7 @@ func (s Service) ProcessApplicationSubmission(request model.SubmitApplicationReq Credentials: creds, ResponseJWT: *responseJWT, } - if err = s.storage.StoreResponse(storeResponseRequest); err != nil { + if err = s.storage.StoreResponse(ctx, storeResponseRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store manifest response") } @@ -322,7 +323,7 @@ func (s Service) ProcessApplicationSubmission(request model.SubmitApplicationReq Done: true, Response: sarData, } - if err = s.opsStorage.StoreOperation(storedOp); err != nil { + if err = s.opsStorage.StoreOperation(ctx, storedOp); err != nil { return nil, errors.Wrap(err, "storing operation") } return operation.ServiceModel(storedOp) diff --git a/pkg/service/manifest/storage/storage.go b/pkg/service/manifest/storage/storage.go index 2c0bfdbbf..b58be9694 100644 --- a/pkg/service/manifest/storage/storage.go +++ b/pkg/service/manifest/storage/storage.go @@ -1,6 +1,7 @@ package storage import ( + "context" "fmt" "github.com/goccy/go-json" @@ -60,7 +61,7 @@ func NewManifestStorage(db storage.ServiceStorage) (*Storage, error) { return &Storage{db: db}, nil } -func (ms *Storage) StoreManifest(manifest StoredManifest) error { +func (ms *Storage) StoreManifest(ctx context.Context, manifest StoredManifest) error { id := manifest.Manifest.ID if id == "" { err := errors.New("could not store manifest without an ID") @@ -73,7 +74,7 @@ func (ms *Storage) StoreManifest(manifest StoredManifest) error { logrus.WithError(err).Error(errMsg) return errors.Wrapf(err, errMsg) } - return ms.db.Write(manifestNamespace, id, manifestBytes) + return ms.db.Write(ctx, manifestNamespace, id, manifestBytes) } func (ms *Storage) GetManifest(id string) (*StoredManifest, error) { @@ -126,7 +127,7 @@ func (ms *Storage) DeleteManifest(id string) error { return nil } -func (ms *Storage) StoreApplication(application StoredApplication) error { +func (ms *Storage) StoreApplication(ctx context.Context, application StoredApplication) error { id := application.Application.ID if id == "" { return util.LoggingNewError("could not store application without an ID") @@ -135,7 +136,7 @@ func (ms *Storage) StoreApplication(application StoredApplication) error { if err != nil { return util.LoggingErrorMsgf(err, "could not store application: %s", id) } - return ms.db.Write(credential.ApplicationNamespace, id, applicationBytes) + return ms.db.Write(ctx, credential.ApplicationNamespace, id, applicationBytes) } func (ms *Storage) GetApplication(id string) (*StoredApplication, error) { @@ -182,7 +183,7 @@ func (ms *Storage) DeleteApplication(id string) error { return nil } -func (ms *Storage) StoreResponse(response StoredResponse) error { +func (ms *Storage) StoreResponse(ctx context.Context, response StoredResponse) error { id := response.Response.ID if id == "" { return util.LoggingNewError("could not store response without an ID") @@ -191,7 +192,7 @@ func (ms *Storage) StoreResponse(response StoredResponse) error { if err != nil { return util.LoggingErrorMsgf(err, "could not store response: %s", id) } - return ms.db.Write(responseNamespace, id, responseBytes) + return ms.db.Write(ctx, responseNamespace, id, responseBytes) } func (ms *Storage) GetResponse(id string) (*StoredResponse, error) { diff --git a/pkg/service/operation/storage.go b/pkg/service/operation/storage.go index 2462eea3f..c1875aecb 100644 --- a/pkg/service/operation/storage.go +++ b/pkg/service/operation/storage.go @@ -1,6 +1,7 @@ package operation import ( + "context" "strings" "github.com/goccy/go-json" @@ -64,7 +65,7 @@ func (b Storage) CancelOperation(id string) (*opstorage.StoredOperation, error) return &op, nil } -func (b Storage) StoreOperation(op opstorage.StoredOperation) error { +func (b Storage) StoreOperation(ctx context.Context, op opstorage.StoredOperation) error { id := op.ID if id == "" { return util.LoggingNewError("ID is required for storing operations") @@ -73,7 +74,7 @@ func (b Storage) StoreOperation(op opstorage.StoredOperation) error { if err != nil { return util.LoggingErrorMsgf(err, "marshalling operation with id: %s", id) } - if err = b.db.Write(namespace.FromID(id), id, jsonBytes); err != nil { + if err = b.db.Write(ctx, namespace.FromID(id), id, jsonBytes); err != nil { return util.LoggingErrorMsg(err, "writing to db") } return nil diff --git a/pkg/service/presentation/service.go b/pkg/service/presentation/service.go index bbf6aa676..d6dbce082 100644 --- a/pkg/service/presentation/service.go +++ b/pkg/service/presentation/service.go @@ -1,6 +1,7 @@ package presentation import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/credential/exchange" @@ -83,7 +84,7 @@ func NewPresentationService(config config.PresentationServiceConfig, s storage.S // CreatePresentationDefinition houses the main service logic for presentation definition creation. It validates the input, and // produces a presentation definition value that conforms with the PresentationDefinition specification. -func (s Service) CreatePresentationDefinition(request model.CreatePresentationDefinitionRequest) (*model.CreatePresentationDefinitionResponse, error) { +func (s Service) CreatePresentationDefinition(ctx context.Context, request model.CreatePresentationDefinitionRequest) (*model.CreatePresentationDefinitionResponse, error) { logrus.Debugf("creating presentation definition: %+v", request) if !request.IsValid() { @@ -96,7 +97,7 @@ func (s Service) CreatePresentationDefinition(request model.CreatePresentationDe storedPresentation := StoredPresentation{ID: request.PresentationDefinition.ID, PresentationDefinition: request.PresentationDefinition} - if err := s.storage.StorePresentation(storedPresentation); err != nil { + if err := s.storage.StorePresentation(ctx, storedPresentation); err != nil { return nil, util.LoggingErrorMsg(err, "could not store presentation") } @@ -130,7 +131,7 @@ func (s Service) DeletePresentationDefinition(request model.DeletePresentationDe // CreateSubmission houses the main service logic for presentation submission creation. It validates the input, and // produces a presentation submission value that conforms with the Submission specification. -func (s Service) CreateSubmission(request model.CreateSubmissionRequest) (*operation.Operation, error) { +func (s Service) CreateSubmission(ctx context.Context, request model.CreateSubmissionRequest) (*operation.Operation, error) { if !request.IsValid() { return nil, errors.Errorf("invalid create presentation submission request: %+v", request) } @@ -183,7 +184,7 @@ func (s Service) CreateSubmission(request model.CreateSubmissionRequest) (*opera } // TODO(andres): IO requests should be done in parallel, once we have context wired up. - if err := s.storage.StoreSubmission(storedSubmission); err != nil { + if err := s.storage.StoreSubmission(ctx, storedSubmission); err != nil { return nil, errors.Wrap(err, "could not store presentation") } @@ -192,7 +193,7 @@ func (s Service) CreateSubmission(request model.CreateSubmissionRequest) (*opera ID: opID, Done: false, } - if err := s.opsStorage.StoreOperation(storedOp); err != nil { + if err := s.opsStorage.StoreOperation(ctx, storedOp); err != nil { return nil, errors.Wrap(err, "could not store operation") } diff --git a/pkg/service/presentation/storage.go b/pkg/service/presentation/storage.go index a5b1bdc86..1a42d7e46 100644 --- a/pkg/service/presentation/storage.go +++ b/pkg/service/presentation/storage.go @@ -1,6 +1,7 @@ package presentation import ( + "context" "fmt" "github.com/TBD54566975/ssi-sdk/credential/exchange" @@ -99,7 +100,7 @@ func NewPresentationStorage(db storage.ServiceStorage) (*Storage, error) { return &Storage{db: db}, nil } -func (ps *Storage) StorePresentation(presentation StoredPresentation) error { +func (ps *Storage) StorePresentation(ctx context.Context, presentation StoredPresentation) error { id := presentation.ID if id == "" { err := errors.New("could not store presentation definition without an ID") @@ -112,7 +113,7 @@ func (ps *Storage) StorePresentation(presentation StoredPresentation) error { logrus.WithError(err).Error(errMsg) return errors.Wrapf(err, errMsg) } - return ps.db.Write(presentationDefinitionNamespace, id, jsonBytes) + return ps.db.Write(ctx, presentationDefinitionNamespace, id, jsonBytes) } func (ps *Storage) GetPresentation(id string) (*StoredPresentation, error) { @@ -137,7 +138,7 @@ func (ps *Storage) DeletePresentation(id string) error { return nil } -func (ps Storage) StoreSubmission(s prestorage.StoredSubmission) error { +func (ps Storage) StoreSubmission(ctx context.Context, s prestorage.StoredSubmission) error { id := s.Submission.ID if id == "" { err := errors.New("could not store submission definition without an ID") @@ -148,7 +149,7 @@ func (ps Storage) StoreSubmission(s prestorage.StoredSubmission) error { if err != nil { return util.LoggingNewErrorf("could not store submission definition: %s", id) } - return ps.db.Write(opsubmission.Namespace, id, jsonBytes) + return ps.db.Write(ctx, opsubmission.Namespace, id, jsonBytes) } func (ps *Storage) GetSubmission(id string) (*prestorage.StoredSubmission, error) { diff --git a/pkg/service/schema/service.go b/pkg/service/schema/service.go index 4ddc667b4..aeb0a145e 100644 --- a/pkg/service/schema/service.go +++ b/pkg/service/schema/service.go @@ -1,6 +1,7 @@ package schema import ( + "context" "fmt" "time" @@ -81,7 +82,7 @@ func NewSchemaService(config config.SchemaServiceConfig, s storage.ServiceStorag // CreateSchema houses the main service logic for schema creation. It validates the input, and // produces a schema value that conforms with the VC JSON JSONSchema specification. // TODO(gabe) support data integrity proof generation on schemas, versioning, and more -func (s Service) CreateSchema(request CreateSchemaRequest) (*CreateSchemaResponse, error) { +func (s Service) CreateSchema(ctx context.Context, request CreateSchemaRequest) (*CreateSchemaResponse, error) { logrus.Debugf("creating schema: %+v", request) @@ -120,7 +121,7 @@ func (s Service) CreateSchema(request CreateSchemaRequest) (*CreateSchemaRespons storedSchema.SchemaJWT = signedSchema } - if err = s.storage.StoreSchema(storedSchema); err != nil { + if err = s.storage.StoreSchema(ctx, storedSchema); err != nil { return nil, util.LoggingErrorMsg(err, "could not store schema") } diff --git a/pkg/service/schema/storage.go b/pkg/service/schema/storage.go index c372a058d..8314c362a 100644 --- a/pkg/service/schema/storage.go +++ b/pkg/service/schema/storage.go @@ -1,6 +1,7 @@ package schema import ( + "context" "fmt" "github.com/goccy/go-json" @@ -34,7 +35,7 @@ func NewSchemaStorage(db storage.ServiceStorage) (*Storage, error) { return &Storage{db: db}, nil } -func (ss *Storage) StoreSchema(schema StoredSchema) error { +func (ss *Storage) StoreSchema(ctx context.Context, schema StoredSchema) error { id := schema.ID if id == "" { err := errors.New("could not store schema without an ID") @@ -47,7 +48,7 @@ func (ss *Storage) StoreSchema(schema StoredSchema) error { logrus.WithError(err).Error(errMsg) return errors.Wrapf(err, errMsg) } - return ss.db.Write(namespace, id, schemaBytes) + return ss.db.Write(ctx, namespace, id, schemaBytes) } func (ss *Storage) GetSchema(id string) (*StoredSchema, error) { diff --git a/pkg/storage/bolt.go b/pkg/storage/bolt.go index a7549914b..f3415c1fd 100644 --- a/pkg/storage/bolt.go +++ b/pkg/storage/bolt.go @@ -2,6 +2,7 @@ package storage import ( "bytes" + "context" "fmt" "strings" "time" @@ -72,7 +73,7 @@ func (b *BoltDB) Close() error { return b.db.Close() } -func (b *BoltDB) Write(namespace string, key string, value []byte) error { +func (b *BoltDB) Write(ctx context.Context, namespace string, key string, value []byte) error { return b.db.Update(func(tx *bolt.Tx) error { bucket, err := tx.CreateBucketIfNotExists([]byte(namespace)) if err != nil { diff --git a/pkg/storage/redis.go b/pkg/storage/redis.go index 177093ff3..a4a7a182f 100644 --- a/pkg/storage/redis.go +++ b/pkg/storage/redis.go @@ -64,10 +64,10 @@ func (b *RedisDB) Close() error { return b.db.Close() } -func (b *RedisDB) Write(namespace, key string, value []byte) error { +func (b *RedisDB) Write(ctx context.Context, namespace, key string, value []byte) error { nameSpaceKey := getRedisKey(namespace, key) // Zero expiration means the key has no expiration time. - return b.db.Set(b.ctx, nameSpaceKey, value, 0).Err() + return b.db.Set(ctx, nameSpaceKey, value, 0).Err() } func (b *RedisDB) WriteMany(namespaces, keys []string, values [][]byte) error { diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 27e453621..9b45a3ffa 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -1,6 +1,7 @@ package storage import ( + "context" "fmt" "reflect" ) @@ -23,7 +24,7 @@ type ServiceStorage interface { URI() string IsOpen() bool Close() error - Write(namespace, key string, value []byte) error + Write(ctx context.Context, namespace, key string, value []byte) error Read(namespace, key string) ([]byte, error) ReadAll(namespace string) (map[string][]byte, error) ReadPrefix(namespace, prefix string) (map[string][]byte, error) From 309b55af5ecf49bf24d53346d9e1c816eb38f2e1 Mon Sep 17 00:00:00 2001 From: Neal Date: Mon, 9 Jan 2023 17:08:16 -0600 Subject: [PATCH 2/5] builds --- internal/credential/verification.go | 13 ++--- internal/schema/resolver.go | 4 +- pkg/server/router/credential.go | 16 +++--- pkg/server/router/credential_test.go | 41 +++++++------- pkg/server/router/did.go | 4 +- pkg/server/router/did_test.go | 25 ++++----- pkg/server/router/issuance.go | 6 +-- pkg/server/router/keystore.go | 2 +- pkg/server/router/keystore_test.go | 9 ++-- pkg/server/router/manifest.go | 18 +++---- pkg/server/router/manifest_test.go | 15 +++--- pkg/server/router/operation.go | 6 +-- pkg/server/router/presentation.go | 10 ++-- pkg/server/router/presentation_test.go | 15 +++--- pkg/server/router/schema.go | 6 +-- pkg/server/router/schema_test.go | 27 +++++----- pkg/server/server_credential_test.go | 29 +++++----- pkg/server/server_issuance_test.go | 7 +-- pkg/server/server_manifest_test.go | 49 ++++++++--------- pkg/server/server_schema_test.go | 3 +- pkg/service/credential/service.go | 56 +++++++++---------- pkg/service/credential/storage.go | 62 ++++++++++----------- pkg/service/did/key.go | 8 +-- pkg/service/did/service.go | 12 ++--- pkg/service/did/storage.go | 12 ++--- pkg/service/did/web.go | 8 +-- pkg/service/issuing/service.go | 16 +++--- pkg/service/issuing/storage.go | 12 ++--- pkg/service/keystore/service.go | 8 +-- pkg/service/keystore/service_test.go | 5 +- pkg/service/keystore/storage.go | 16 +++--- pkg/service/manifest/application.go | 5 +- pkg/service/manifest/manifest.go | 6 ++- pkg/service/manifest/response.go | 4 +- pkg/service/manifest/service.go | 48 ++++++++--------- pkg/service/manifest/storage/storage.go | 39 +++++++------- pkg/service/operation/service.go | 13 ++--- pkg/service/operation/storage.go | 16 +++--- pkg/service/operation/storage_test.go | 7 +-- pkg/service/presentation/service.go | 28 +++++----- pkg/service/presentation/storage.go | 19 +++---- pkg/service/schema/service.go | 22 ++++---- pkg/service/schema/storage.go | 12 ++--- pkg/storage/bolt.go | 16 +++--- pkg/storage/db_test.go | 47 ++++++++-------- pkg/storage/redis.go | 72 ++++++++++++------------- pkg/storage/storage.go | 16 +++--- 47 files changed, 456 insertions(+), 434 deletions(-) diff --git a/internal/credential/verification.go b/internal/credential/verification.go index f00474dd6..07bf6eb15 100644 --- a/internal/credential/verification.go +++ b/internal/credential/verification.go @@ -1,6 +1,7 @@ package credential import ( + "context" "crypto" "fmt" @@ -49,7 +50,7 @@ func NewCredentialVerifier(didResolver *didsdk.Resolver, schemaResolver schema.R // VerifyJWTCredential first parses and checks the signature on the given JWT credential. Next, it runs // a set of static verification checks on the credential as per the credential service's configuration. -func (v Verifier) VerifyJWTCredential(token keyaccess.JWT) error { +func (v Verifier) VerifyJWTCredential(ctx context.Context, token keyaccess.JWT) error { // first, parse the token to see if it contains a valid verifiable credential cred, err := signing.ParseVerifiableCredentialFromJWT(token.String()) if err != nil { @@ -84,12 +85,12 @@ func (v Verifier) VerifyJWTCredential(token keyaccess.JWT) error { return util.LoggingErrorMsg(err, "could not verify credential's signature") } - return v.staticVerificationChecks(*cred) + return v.staticVerificationChecks(ctx, *cred) } // VerifyDataIntegrityCredential first checks the signature on the given data integrity credential. Next, it runs // a set of static verification checks on the credential as per the credential service's configuration. -func (v Verifier) VerifyDataIntegrityCredential(credential credsdk.VerifiableCredential) error { +func (v Verifier) VerifyDataIntegrityCredential(ctx context.Context, credential credsdk.VerifiableCredential) error { // resolve the issuer's key material kid, pubKey, err := v.resolveCredentialIssuerKey(credential) if err != nil { @@ -108,7 +109,7 @@ func (v Verifier) VerifyDataIntegrityCredential(credential credsdk.VerifiableCre return util.LoggingErrorMsg(err, "could not verify the credential's signature") } - return v.staticVerificationChecks(credential) + return v.staticVerificationChecks(ctx, credential) } func (v Verifier) VerifyJWT(did string, token keyaccess.JWT) error { @@ -144,12 +145,12 @@ func (v Verifier) resolveCredentialIssuerKey(credential credsdk.VerifiableCreden // staticVerificationChecks runs a set of static verification checks on the credential as per the credential // service's configuration, such as checking the credential's schema, expiration, and object validity. -func (v Verifier) staticVerificationChecks(credential credsdk.VerifiableCredential) error { +func (v Verifier) staticVerificationChecks(ctx context.Context, credential credsdk.VerifiableCredential) error { // if the credential has a schema, resolve it before it is to be used in verification var verificationOpts []verification.VerificationOption if credential.CredentialSchema != nil { schemaID := credential.CredentialSchema.ID - resolvedSchema, err := v.schemaResolver.Resolve(schemaID) + resolvedSchema, err := v.schemaResolver.Resolve(ctx, schemaID) if err != nil { return errors.Wrapf(err, "for credential<%s> failed to resolve schemas: %s", credential.ID, schemaID) } diff --git a/internal/schema/resolver.go b/internal/schema/resolver.go index 058151ff7..abfc1f00e 100644 --- a/internal/schema/resolver.go +++ b/internal/schema/resolver.go @@ -1,10 +1,12 @@ package schema import ( + "context" + "github.com/TBD54566975/ssi-sdk/credential/schema" ) // Resolution is an interface that defines a generic method of resolving a schema type Resolution interface { - Resolve(id string) (*schema.VCJSONSchema, error) + Resolve(ctx context.Context, id string) (*schema.VCJSONSchema, error) } diff --git a/pkg/server/router/credential.go b/pkg/server/router/credential.go index eb77e0ad8..087c3025e 100644 --- a/pkg/server/router/credential.go +++ b/pkg/server/router/credential.go @@ -132,7 +132,7 @@ func (cr CredentialRouter) GetCredential(ctx context.Context, w http.ResponseWri return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotCredential, err := cr.service.GetCredential(credential.GetCredentialRequest{ID: *id}) + gotCredential, err := cr.service.GetCredential(ctx, credential.GetCredentialRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get credential with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -169,7 +169,7 @@ func (cr CredentialRouter) GetCredentialStatus(ctx context.Context, w http.Respo return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - getCredentialStatusResponse, err := cr.service.GetCredentialStatus(credential.GetCredentialStatusRequest{ID: *id}) + getCredentialStatusResponse, err := cr.service.GetCredentialStatus(ctx, credential.GetCredentialStatusRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get credential with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -207,7 +207,7 @@ func (cr CredentialRouter) GetCredentialStatusList(ctx context.Context, w http.R return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotCredential, err := cr.service.GetCredentialStatusList(credential.GetCredentialStatusListRequest{ID: *id}) + gotCredential, err := cr.service.GetCredentialStatusList(ctx, credential.GetCredentialStatusListRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get credential status list with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -326,7 +326,7 @@ func (cr CredentialRouter) VerifyCredential(ctx context.Context, w http.Response return framework.NewRequestError(err, http.StatusBadRequest) } - verificationResult, err := cr.service.VerifyCredential(credential.VerifyCredentialRequest{ + verificationResult, err := cr.service.VerifyCredential(ctx, credential.VerifyCredentialRequest{ DataIntegrityCredential: request.DataIntegrityCredential, CredentialJWT: request.CredentialJWT, }) @@ -382,7 +382,7 @@ func (cr CredentialRouter) GetCredentials(ctx context.Context, w http.ResponseWr } func (cr CredentialRouter) getCredentialsByIssuer(ctx context.Context, issuer string, w http.ResponseWriter, _ *http.Request) error { - gotCredentials, err := cr.service.GetCredentialsByIssuer(credential.GetCredentialByIssuerRequest{Issuer: issuer}) + gotCredentials, err := cr.service.GetCredentialsByIssuer(ctx, credential.GetCredentialByIssuerRequest{Issuer: issuer}) if err != nil { errMsg := fmt.Sprintf("could not get credentials for issuer: %s", util.SanitizeLog(issuer)) logrus.WithError(err).Error(errMsg) @@ -394,7 +394,7 @@ func (cr CredentialRouter) getCredentialsByIssuer(ctx context.Context, issuer st } func (cr CredentialRouter) getCredentialsBySubject(ctx context.Context, subject string, w http.ResponseWriter, _ *http.Request) error { - gotCredentials, err := cr.service.GetCredentialsBySubject(credential.GetCredentialBySubjectRequest{Subject: subject}) + gotCredentials, err := cr.service.GetCredentialsBySubject(ctx, credential.GetCredentialBySubjectRequest{Subject: subject}) if err != nil { errMsg := fmt.Sprintf("could not get credentials for subject: %s", util.SanitizeLog(subject)) logrus.WithError(err).Error(errMsg) @@ -406,7 +406,7 @@ func (cr CredentialRouter) getCredentialsBySubject(ctx context.Context, subject } func (cr CredentialRouter) getCredentialsBySchema(ctx context.Context, schema string, w http.ResponseWriter, _ *http.Request) error { - gotCredentials, err := cr.service.GetCredentialsBySchema(credential.GetCredentialBySchemaRequest{Schema: schema}) + gotCredentials, err := cr.service.GetCredentialsBySchema(ctx, credential.GetCredentialBySchemaRequest{Schema: schema}) if err != nil { errMsg := fmt.Sprintf("could not get credentials for schema: %s", util.SanitizeLog(schema)) logrus.WithError(err).Error(errMsg) @@ -436,7 +436,7 @@ func (cr CredentialRouter) DeleteCredential(ctx context.Context, w http.Response return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := cr.service.DeleteCredential(credential.DeleteCredentialRequest{ID: *id}); err != nil { + if err := cr.service.DeleteCredential(ctx, credential.DeleteCredentialRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete credential with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) diff --git a/pkg/server/router/credential_test.go b/pkg/server/router/credential_test.go index d825bf8c3..8a6ea9ebb 100644 --- a/pkg/server/router/credential_test.go +++ b/pkg/server/router/credential_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "fmt" "testing" "time" @@ -52,13 +53,13 @@ func TestCredentialRouter(t *testing.T) { // create a credential - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) assert.NoError(tt, err) assert.NotEmpty(tt, issuerDID) issuer := issuerDID.DID.ID subject := "did:test:345" - createdCred, err := credService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuer, Subject: subject, Data: map[string]any{ @@ -80,7 +81,7 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, "Nakamoto", cred.CredentialSubject["lastName"]) // get it back - gotCred, err := credService.GetCredential(credential.GetCredentialRequest{ID: cred.ID}) + gotCred, err := credService.GetCredential(context.Background(), credential.GetCredentialRequest{ID: cred.ID}) assert.NoError(tt, err) assert.NotEmpty(tt, gotCred) @@ -88,18 +89,18 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, createdCred.CredentialJWT, gotCred.CredentialJWT) // get a cred that doesn't exist - _, err = credService.GetCredential(credential.GetCredentialRequest{ID: "bad"}) + _, err = credService.GetCredential(context.Background(), credential.GetCredentialRequest{ID: "bad"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "credential not found with id: bad") // get by schema - no schema - bySchema, err := credService.GetCredentialsBySchema(credential.GetCredentialBySchemaRequest{Schema: ""}) + bySchema, err := credService.GetCredentialsBySchema(context.Background(), credential.GetCredentialBySchemaRequest{Schema: ""}) assert.NoError(tt, err) assert.Len(tt, bySchema.Credentials, 1) assert.EqualValues(tt, cred.CredentialSchema, bySchema.Credentials[0].Credential.CredentialSchema) // get by subject - bySubject, err := credService.GetCredentialsBySubject(credential.GetCredentialBySubjectRequest{Subject: subject}) + bySubject, err := credService.GetCredentialsBySubject(context.Background(), credential.GetCredentialBySubjectRequest{Subject: subject}) assert.NoError(tt, err) assert.Len(tt, bySubject.Credentials, 1) @@ -107,7 +108,7 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, cred.CredentialSubject[credsdk.VerifiableCredentialIDProperty], bySubject.Credentials[0].Credential.CredentialSubject[credsdk.VerifiableCredentialIDProperty]) // get by issuer - byIssuer, err := credService.GetCredentialsByIssuer(credential.GetCredentialByIssuerRequest{Issuer: issuer}) + byIssuer, err := credService.GetCredentialsByIssuer(context.Background(), credential.GetCredentialByIssuerRequest{Issuer: issuer}) assert.NoError(tt, err) assert.Len(tt, byIssuer.Credentials, 1) @@ -115,7 +116,7 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, cred.Issuer, byIssuer.Credentials[0].Credential.Issuer) // create another cred with the same issuer, different subject, different schema that doesn't exist - _, err = credService.CreateCredential(credential.CreateCredentialRequest{ + _, err = credService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuer, Subject: "did:abcd:efghi", JSONSchema: "https://test-schema.com", @@ -138,12 +139,12 @@ func TestCredentialRouter(t *testing.T) { "required": []any{"email"}, "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: emailSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: emailSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // create another cred with the same issuer, different subject, different schema that does exist - createdCredWithSchema, err := credService.CreateCredential(credential.CreateCredentialRequest{ + createdCredWithSchema, err := credService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuer, Subject: "did:abcd:efghi", JSONSchema: createdSchema.ID, @@ -156,19 +157,19 @@ func TestCredentialRouter(t *testing.T) { assert.NotEmpty(tt, createdCredWithSchema) // get by issuer - byIssuer, err = credService.GetCredentialsByIssuer(credential.GetCredentialByIssuerRequest{Issuer: issuer}) + byIssuer, err = credService.GetCredentialsByIssuer(context.Background(), credential.GetCredentialByIssuerRequest{Issuer: issuer}) assert.NoError(tt, err) assert.Len(tt, byIssuer.Credentials, 2) // make sure the schema and subject queries are consistent - bySchema, err = credService.GetCredentialsBySchema(credential.GetCredentialBySchemaRequest{Schema: ""}) + bySchema, err = credService.GetCredentialsBySchema(context.Background(), credential.GetCredentialBySchemaRequest{Schema: ""}) assert.NoError(tt, err) assert.Len(tt, bySchema.Credentials, 1) assert.Equal(tt, cred.ID, bySchema.Credentials[0].ID) assert.EqualValues(tt, cred.CredentialSchema, bySchema.Credentials[0].Credential.CredentialSchema) - bySubject, err = credService.GetCredentialsBySubject(credential.GetCredentialBySubjectRequest{Subject: subject}) + bySubject, err = credService.GetCredentialsBySubject(context.Background(), credential.GetCredentialBySubjectRequest{Subject: subject}) assert.NoError(tt, err) assert.Len(tt, bySubject.Credentials, 1) @@ -176,15 +177,15 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, cred.CredentialSubject[credsdk.VerifiableCredentialIDProperty], bySubject.Credentials[0].Credential.CredentialSubject[credsdk.VerifiableCredentialIDProperty]) // delete a cred that doesn't exist (no error since idempotent) - err = credService.DeleteCredential(credential.DeleteCredentialRequest{ID: "bad"}) + err = credService.DeleteCredential(context.Background(), credential.DeleteCredentialRequest{ID: "bad"}) assert.NoError(tt, err) // delete a credential that does exist - err = credService.DeleteCredential(credential.DeleteCredentialRequest{ID: cred.ID}) + err = credService.DeleteCredential(context.Background(), credential.DeleteCredentialRequest{ID: cred.ID}) assert.NoError(tt, err) // get it back - _, err = credService.GetCredential(credential.GetCredentialRequest{ID: cred.ID}) + _, err = credService.GetCredential(context.Background(), credential.GetCredentialRequest{ID: cred.ID}) assert.Error(tt, err) assert.Contains(tt, err.Error(), fmt.Sprintf("credential not found with id: %s", cred.ID)) }) @@ -206,7 +207,7 @@ func TestCredentialRouter(t *testing.T) { assert.Equal(tt, framework.StatusReady, credService.Status().Status) // create a did - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) assert.NoError(tt, err) assert.NotEmpty(tt, issuerDID) @@ -222,14 +223,14 @@ func TestCredentialRouter(t *testing.T) { "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: emailSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: emailSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) issuer := issuerDID.DID.ID subject := "did:test:345" - createdCred, err := credService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuer, Subject: subject, JSONSchema: createdSchema.ID, @@ -251,7 +252,7 @@ func TestCredentialRouter(t *testing.T) { assert.Contains(tt, credStatusMap["statusListCredential"], "v1/credentials/status") assert.NotEmpty(tt, credStatusMap["statusListIndex"]) - createdCredTwo, err := credService.CreateCredential(credential.CreateCredentialRequest{ + createdCredTwo, err := credService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuer, Subject: subject, JSONSchema: createdSchema.ID, diff --git a/pkg/server/router/did.go b/pkg/server/router/did.go index 0347a8bc9..5685ca12b 100644 --- a/pkg/server/router/did.go +++ b/pkg/server/router/did.go @@ -152,7 +152,7 @@ func (dr DIDRouter) GetDIDByMethod(ctx context.Context, w http.ResponseWriter, _ // TODO(gabe) check if the method is supported, to tell whether this is a bad req or internal error // TODO(gabe) differentiate between internal errors and not found DIDs getDIDRequest := did.GetDIDRequest{Method: didsdk.Method(*method), ID: *id} - gotDID, err := dr.service.GetDIDByMethod(getDIDRequest) + gotDID, err := dr.service.GetDIDByMethod(ctx, getDIDRequest) if err != nil { errMsg := fmt.Sprintf("could not get DID for method<%s> with id: %s", *method, *id) logrus.WithError(err).Error(errMsg) @@ -188,7 +188,7 @@ func (dr DIDRouter) GetDIDsByMethod(ctx context.Context, w http.ResponseWriter, // TODO(gabe) check if the method is supported, to tell whether this is a bad req or internal error // TODO(gabe) differentiate between internal errors and not found DIDs getDIDsRequest := did.GetDIDsRequest{Method: didsdk.Method(*method)} - gotDIDs, err := dr.service.GetDIDsByMethod(getDIDsRequest) + gotDIDs, err := dr.service.GetDIDsByMethod(ctx, getDIDsRequest) if err != nil { errMsg := fmt.Sprintf("could not get DIDs for method: %s", *method) logrus.WithError(err).Error(errMsg) diff --git a/pkg/server/router/did_test.go b/pkg/server/router/did_test.go index c7e97a9d5..c182df170 100644 --- a/pkg/server/router/did_test.go +++ b/pkg/server/router/did_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "testing" "github.com/TBD54566975/ssi-sdk/crypto" @@ -44,7 +45,7 @@ func TestDIDRouter(t *testing.T) { assert.Equal(tt, framework.StatusReady, didService.Status().Status) // get unknown handler - _, err = didService.GetDIDByMethod(did.GetDIDRequest{Method: "bad"}) + _, err = didService.GetDIDByMethod(context.Background(), did.GetDIDRequest{Method: "bad"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "could not get handler for method") @@ -54,12 +55,12 @@ func TestDIDRouter(t *testing.T) { assert.Equal(tt, didsdk.KeyMethod, supported.Methods[0]) // bad key type - _, err = didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: "bad"}) + _, err = didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: "bad"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "could not create did:key") // good key type - createDIDResponse, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) + createDIDResponse, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) assert.NoError(tt, err) assert.NotEmpty(tt, createDIDResponse) @@ -67,7 +68,7 @@ func TestDIDRouter(t *testing.T) { assert.Contains(tt, createDIDResponse.DID.ID, "did:key") // get it back - getDIDResponse, err := didService.GetDIDByMethod(did.GetDIDRequest{Method: didsdk.KeyMethod, ID: createDIDResponse.DID.ID}) + getDIDResponse, err := didService.GetDIDByMethod(context.Background(), did.GetDIDRequest{Method: didsdk.KeyMethod, ID: createDIDResponse.DID.ID}) assert.NoError(tt, err) assert.NotEmpty(tt, getDIDResponse) @@ -75,12 +76,12 @@ func TestDIDRouter(t *testing.T) { assert.Equal(tt, createDIDResponse.DID.ID, getDIDResponse.DID.ID) // create a second DID - createDIDResponse2, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) + createDIDResponse2, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519}) assert.NoError(tt, err) assert.NotEmpty(tt, createDIDResponse2) // get all DIDs back - getDIDsResponse, err := didService.GetDIDsByMethod(did.GetDIDsRequest{Method: didsdk.KeyMethod}) + getDIDsResponse, err := didService.GetDIDsByMethod(context.Background(), did.GetDIDsRequest{Method: didsdk.KeyMethod}) assert.NoError(tt, err) assert.NotEmpty(tt, getDIDsResponse) assert.Len(tt, getDIDsResponse.DIDs, 2) @@ -113,7 +114,7 @@ func TestDIDRouter(t *testing.T) { assert.Equal(tt, framework.StatusReady, didService.Status().Status) // get unknown handler - _, err = didService.GetDIDByMethod(did.GetDIDRequest{Method: "bad"}) + _, err = didService.GetDIDByMethod(context.Background(), did.GetDIDRequest{Method: "bad"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "could not get handler for method") @@ -124,12 +125,12 @@ func TestDIDRouter(t *testing.T) { assert.ElementsMatch(tt, supported.Methods, []didsdk.Method{didsdk.KeyMethod, didsdk.WebMethod}) // bad key type - _, err = didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: "bad", DIDWebID: "did:web:example.com"}) + _, err = didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: "bad", DIDWebID: "did:web:example.com"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "could not generate key for did:web") // good key type - createDIDResponse, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: crypto.Ed25519, DIDWebID: "did:web:example.com"}) + createDIDResponse, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: crypto.Ed25519, DIDWebID: "did:web:example.com"}) assert.NoError(tt, err) assert.NotEmpty(tt, createDIDResponse) @@ -137,7 +138,7 @@ func TestDIDRouter(t *testing.T) { assert.Contains(tt, createDIDResponse.DID.ID, "did:web") // get it back - getDIDResponse, err := didService.GetDIDByMethod(did.GetDIDRequest{Method: didsdk.WebMethod, ID: createDIDResponse.DID.ID}) + getDIDResponse, err := didService.GetDIDByMethod(context.Background(), did.GetDIDRequest{Method: didsdk.WebMethod, ID: createDIDResponse.DID.ID}) assert.NoError(tt, err) assert.NotEmpty(tt, getDIDResponse) @@ -145,12 +146,12 @@ func TestDIDRouter(t *testing.T) { assert.Equal(tt, createDIDResponse.DID.ID, getDIDResponse.DID.ID) // create a second DID - createDIDResponse2, err := didService.CreateDIDByMethod(did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: crypto.Ed25519, DIDWebID: "did:web:tbd.website"}) + createDIDResponse2, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.WebMethod, KeyType: crypto.Ed25519, DIDWebID: "did:web:tbd.website"}) assert.NoError(tt, err) assert.NotEmpty(tt, createDIDResponse2) // get all DIDs back - getDIDsResponse, err := didService.GetDIDsByMethod(did.GetDIDsRequest{Method: didsdk.WebMethod}) + getDIDsResponse, err := didService.GetDIDsByMethod(context.Background(), did.GetDIDsRequest{Method: didsdk.WebMethod}) assert.NoError(tt, err) assert.NotEmpty(tt, getDIDsResponse) assert.Len(tt, getDIDsResponse.DIDs, 2) diff --git a/pkg/server/router/issuance.go b/pkg/server/router/issuance.go index 3b39ae735..7f44d7e4b 100644 --- a/pkg/server/router/issuance.go +++ b/pkg/server/router/issuance.go @@ -40,7 +40,7 @@ func (ir IssuanceRouter) GetIssuanceTemplate(ctx context.Context, w http.Respons util.LoggingNewError("cannot get issuance template without an ID"), http.StatusBadRequest) } - issuanceTemplate, err := ir.service.GetIssuanceTemplate(&issuing.GetIssuanceTemplateRequest{ID: *id}) + issuanceTemplate, err := ir.service.GetIssuanceTemplate(ctx, &issuing.GetIssuanceTemplateRequest{ID: *id}) if err != nil { return framework.NewRequestError( util.LoggingErrorMsg(err, "getting issuance template"), http.StatusInternalServerError) @@ -104,7 +104,7 @@ func (ir IssuanceRouter) DeleteIssuanceTemplate(ctx context.Context, w http.Resp util.LoggingNewError("cannot delete an issuance template without an ID parameter"), http.StatusBadRequest) } - if err := ir.service.DeleteIssuanceTemplate(&issuing.DeleteIssuanceTemplateRequest{ID: *id}); err != nil { + if err := ir.service.DeleteIssuanceTemplate(ctx, &issuing.DeleteIssuanceTemplateRequest{ID: *id}); err != nil { return framework.NewRequestError( util.LoggingErrorMsgf(err, "could not delete issuance template with id: %s", *id), http.StatusInternalServerError) } @@ -127,7 +127,7 @@ type ListIssuanceTemplatesResponse struct { // @Failure 500 {string} string "Internal server error" // @Router /v1/manifests [get] func (ir IssuanceRouter) ListIssuanceTemplates(ctx context.Context, w http.ResponseWriter, _ *http.Request) error { - gotManifests, err := ir.service.ListIssuanceTemplates(&issuing.ListIssuanceTemplatesRequest{}) + gotManifests, err := ir.service.ListIssuanceTemplates(ctx, &issuing.ListIssuanceTemplatesRequest{}) if err != nil { return framework.NewRequestError( diff --git a/pkg/server/router/keystore.go b/pkg/server/router/keystore.go index 16fb3c3d7..2d79637f5 100644 --- a/pkg/server/router/keystore.go +++ b/pkg/server/router/keystore.go @@ -114,7 +114,7 @@ func (ksr *KeyStoreRouter) GetKeyDetails(ctx context.Context, w http.ResponseWri return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotKeyDetails, err := ksr.service.GetKeyDetails(keystore.GetKeyDetailsRequest{ID: *id}) + gotKeyDetails, err := ksr.service.GetKeyDetails(ctx, keystore.GetKeyDetailsRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get key details for id: %s", *id) logrus.WithError(err).Error(errMsg) diff --git a/pkg/server/router/keystore_test.go b/pkg/server/router/keystore_test.go index 0434cc765..1b5b7fafe 100644 --- a/pkg/server/router/keystore_test.go +++ b/pkg/server/router/keystore_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "testing" "github.com/TBD54566975/ssi-sdk/crypto" @@ -45,7 +46,7 @@ func TestKeyStoreRouter(t *testing.T) { assert.Equal(tt, framework.StatusReady, keyStoreService.Status().Status) // store an invalid key type - err = keyStoreService.StoreKey(keystore.StoreKeyRequest{ + err = keyStoreService.StoreKey(context.Background(), keystore.StoreKeyRequest{ ID: "test-kid", Type: "bad", Controller: "me", @@ -62,7 +63,7 @@ func TestKeyStoreRouter(t *testing.T) { keyID := "did:test:me#key-1" privKeyBytes, err := crypto.PrivKeyToBytes(privKey) assert.NoError(tt, err) - err = keyStoreService.StoreKey(keystore.StoreKeyRequest{ + err = keyStoreService.StoreKey(context.Background(), keystore.StoreKeyRequest{ ID: keyID, Type: crypto.Ed25519, Controller: "did:test:me", @@ -71,13 +72,13 @@ func TestKeyStoreRouter(t *testing.T) { assert.NoError(tt, err) // get a key that doesn't exist - gotDetails, err := keyStoreService.GetKeyDetails(keystore.GetKeyDetailsRequest{ID: "bad"}) + gotDetails, err := keyStoreService.GetKeyDetails(context.Background(), keystore.GetKeyDetailsRequest{ID: "bad"}) assert.Error(tt, err) assert.Empty(tt, gotDetails) assert.Contains(tt, err.Error(), "could not get key details for key: bad") // get a key that exists - gotDetails, err = keyStoreService.GetKeyDetails(keystore.GetKeyDetailsRequest{ID: keyID}) + gotDetails, err = keyStoreService.GetKeyDetails(context.Background(), keystore.GetKeyDetailsRequest{ID: keyID}) assert.NoError(tt, err) assert.NotEmpty(tt, gotDetails) diff --git a/pkg/server/router/manifest.go b/pkg/server/router/manifest.go index daffca34e..7674191c3 100644 --- a/pkg/server/router/manifest.go +++ b/pkg/server/router/manifest.go @@ -129,7 +129,7 @@ func (mr ManifestRouter) GetManifest(ctx context.Context, w http.ResponseWriter, return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotManifest, err := mr.service.GetManifest(model.GetManifestRequest{ID: *id}) + gotManifest, err := mr.service.GetManifest(ctx, model.GetManifestRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get manifest with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -162,7 +162,7 @@ type GetManifestsResponse struct { // @Failure 500 {string} string "Internal server error" // @Router /v1/manifests [get] func (mr ManifestRouter) GetManifests(ctx context.Context, w http.ResponseWriter, _ *http.Request) error { - gotManifests, err := mr.service.GetManifests() + gotManifests, err := mr.service.GetManifests(ctx) if err != nil { errMsg := "could not get manifests" @@ -202,7 +202,7 @@ func (mr ManifestRouter) DeleteManifest(ctx context.Context, w http.ResponseWrit return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := mr.service.DeleteManifest(model.DeleteManifestRequest{ID: *id}); err != nil { + if err := mr.service.DeleteManifest(ctx, model.DeleteManifestRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete manifest with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) @@ -347,7 +347,7 @@ func (mr ManifestRouter) GetApplication(ctx context.Context, w http.ResponseWrit return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotApplication, err := mr.service.GetApplication(model.GetApplicationRequest{ID: *id}) + gotApplication, err := mr.service.GetApplication(ctx, model.GetApplicationRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get application with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -376,7 +376,7 @@ type GetApplicationsResponse struct { // @Failure 500 {string} string "Internal server error" // @Router /v1/manifests/applications [get] func (mr ManifestRouter) GetApplications(ctx context.Context, w http.ResponseWriter, _ *http.Request) error { - gotApplications, err := mr.service.GetApplications() + gotApplications, err := mr.service.GetApplications(ctx) if err != nil { errMsg := "could not get applications" @@ -410,7 +410,7 @@ func (mr ManifestRouter) DeleteApplication(ctx context.Context, w http.ResponseW return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := mr.service.DeleteApplication(model.DeleteApplicationRequest{ID: *id}); err != nil { + if err := mr.service.DeleteApplication(ctx, model.DeleteApplicationRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete application with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) @@ -442,7 +442,7 @@ func (mr ManifestRouter) GetResponse(ctx context.Context, w http.ResponseWriter, return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - gotResponse, err := mr.service.GetResponse(model.GetResponseRequest{ID: *id}) + gotResponse, err := mr.service.GetResponse(ctx, model.GetResponseRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get response with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -471,7 +471,7 @@ type GetResponsesResponse struct { // @Failure 500 {string} string "Internal server error" // @Router /v1/manifests/responses [get] func (mr ManifestRouter) GetResponses(ctx context.Context, w http.ResponseWriter, _ *http.Request) error { - gotResponses, err := mr.service.GetResponses() + gotResponses, err := mr.service.GetResponses(ctx) if err != nil { errMsg := "could not get responses" @@ -505,7 +505,7 @@ func (mr ManifestRouter) DeleteResponse(ctx context.Context, w http.ResponseWrit return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := mr.service.DeleteResponse(model.DeleteResponseRequest{ID: *id}); err != nil { + if err := mr.service.DeleteResponse(ctx, model.DeleteResponseRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete response with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) diff --git a/pkg/server/router/manifest_test.go b/pkg/server/router/manifest_test.go index dd88b47ef..adb5f120c 100644 --- a/pkg/server/router/manifest_test.go +++ b/pkg/server/router/manifest_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "testing" "github.com/TBD54566975/ssi-sdk/credential/exchange" @@ -57,11 +58,11 @@ func TestManifestRouter(t *testing.T) { Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, } - issuerDID, err := didService.CreateDIDByMethod(createDIDRequest) + issuerDID, err := didService.CreateDIDByMethod(context.Background(), createDIDRequest) assert.NoError(tt, err) assert.NotEmpty(tt, issuerDID) - applicantDID, err := didService.CreateDIDByMethod(createDIDRequest) + applicantDID, err := didService.CreateDIDByMethod(context.Background(), createDIDRequest) assert.NoError(tt, err) assert.NotEmpty(tt, applicantDID) @@ -75,12 +76,12 @@ func TestManifestRouter(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // issue a credential against the schema to the subject, from the issuer - createdCred, err := credentialService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credentialService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuerDID.DID.ID, Subject: applicantDID.DID.ID, JSONSchema: createdSchema.ID, @@ -91,7 +92,7 @@ func TestManifestRouter(t *testing.T) { // good manifest request, which asks for a single verifiable credential in the VC-JWT format createManifestRequest := getValidManifestRequest(issuerDID.DID.ID, createdSchema.ID) - createdManifest, err := manifestService.CreateManifest(createManifestRequest) + createdManifest, err := manifestService.CreateManifest(context.Background(), createManifestRequest) assert.NoError(tt, err) assert.NotEmpty(tt, createdManifest) @@ -123,11 +124,11 @@ func TestManifestRouter(t *testing.T) { submitApplicationRequest := SubmitApplicationRequest{ApplicationJWT: *signed} sar, err := submitApplicationRequest.ToServiceRequest() assert.NoError(tt, err) - createdApplicationResponseOp, err := manifestService.ProcessApplicationSubmission(*sar) + createdApplicationResponseOp, err := manifestService.ProcessApplicationSubmission(context.Background(), *sar) assert.NoError(tt, err) assert.False(tt, createdApplicationResponseOp.Done) - createdApplicationResponse, err := manifestService.ReviewApplication(model.ReviewApplicationRequest{ + createdApplicationResponse, err := manifestService.ReviewApplication(context.Background(), model.ReviewApplicationRequest{ ID: storage.StatusObjectID(createdApplicationResponseOp.ID), Approved: true, Reason: "ApprovalMan is here", diff --git a/pkg/server/router/operation.go b/pkg/server/router/operation.go index 2e3623cf6..82a0d828e 100644 --- a/pkg/server/router/operation.go +++ b/pkg/server/router/operation.go @@ -48,7 +48,7 @@ func (o OperationRouter) GetOperation(ctx context.Context, w http.ResponseWriter util.LoggingNewError("get operation request requires id"), http.StatusBadRequest) } - op, err := o.service.GetOperation(operation.GetOperationRequest{ID: *id}) + op, err := o.service.GetOperation(ctx, operation.GetOperationRequest{ID: *id}) if err != nil { return framework.NewRequestError( @@ -140,7 +140,7 @@ func (o OperationRouter) GetOperations(ctx context.Context, w http.ResponseWrite util.LoggingErrorMsg(err, "invalid get operations request"), http.StatusBadRequest) } - ops, err := o.service.GetOperations(req) + ops, err := o.service.GetOperations(ctx, req) if err != nil { logrus.WithError(err).Error("getting operations from service") return framework.NewRequestError(err, http.StatusInternalServerError) @@ -193,7 +193,7 @@ func (o OperationRouter) CancelOperation(ctx context.Context, w http.ResponseWri util.LoggingNewError("get operation request requires id"), http.StatusBadRequest) } - op, err := o.service.CancelOperation(operation.CancelOperationRequest{ID: *id}) + op, err := o.service.CancelOperation(ctx, operation.CancelOperationRequest{ID: *id}) if err != nil { return framework.NewRequestError( diff --git a/pkg/server/router/presentation.go b/pkg/server/router/presentation.go index 8cccd51cb..0e5097bc5 100644 --- a/pkg/server/router/presentation.go +++ b/pkg/server/router/presentation.go @@ -141,7 +141,7 @@ func (pr PresentationRouter) GetPresentationDefinition(ctx context.Context, w ht return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - def, err := pr.service.GetPresentationDefinition(model.GetPresentationDefinitionRequest{ID: *id}) + def, err := pr.service.GetPresentationDefinition(ctx, model.GetPresentationDefinitionRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get presentation with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -173,7 +173,7 @@ func (pr PresentationRouter) DeletePresentationDefinition(ctx context.Context, w return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := pr.service.DeletePresentationDefinition(model.DeletePresentationDefinitionRequest{ID: *id}); err != nil { + if err := pr.service.DeletePresentationDefinition(ctx, model.DeletePresentationDefinitionRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete presentation with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) @@ -277,7 +277,7 @@ func (pr PresentationRouter) GetSubmission(ctx context.Context, w http.ResponseW util.LoggingNewError("get submission request requires id"), http.StatusBadRequest) } - submission, err := pr.service.GetSubmission(model.GetSubmissionRequest{ID: *id}) + submission, err := pr.service.GetSubmission(ctx, model.GetSubmissionRequest{ID: *id}) if err != nil { return framework.NewRequestError( @@ -346,7 +346,7 @@ func (pr PresentationRouter) ListSubmissions(ctx context.Context, w http.Respons return framework.NewRequestError( util.LoggingErrorMsg(err, "invalid filter"), http.StatusBadRequest) } - resp, err := pr.service.ListSubmissions(model.ListSubmissionRequest{ + resp, err := pr.service.ListSubmissions(ctx, model.ListSubmissionRequest{ Filter: filter, }) if err != nil { @@ -398,7 +398,7 @@ func (pr PresentationRouter) ReviewSubmission(ctx context.Context, w http.Respon } req := request.toServiceRequest(*id) - submission, err := pr.service.ReviewSubmission(req) + submission, err := pr.service.ReviewSubmission(ctx, req) if err != nil { return framework.NewRequestError( util.LoggingErrorMsg(err, "failed reviewing submission"), http.StatusInternalServerError) diff --git a/pkg/server/router/presentation_test.go b/pkg/server/router/presentation_test.go index 1a00b9f77..e354a74cb 100644 --- a/pkg/server/router/presentation_test.go +++ b/pkg/server/router/presentation_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "testing" "github.com/TBD54566975/ssi-sdk/credential/exchange" @@ -41,17 +42,17 @@ func TestPresentationDefinitionService(t *testing.T) { t.Run("Create returns the created definition", func(t *testing.T) { pd := createPresentationDefinition(t) - created, err := service.CreatePresentationDefinition(model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) + created, err := service.CreatePresentationDefinition(context.Background(), model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) assert.NoError(t, err) assert.Equal(t, pd, &created.PresentationDefinition) }) t.Run("Get returns the created definition", func(t *testing.T) { pd := createPresentationDefinition(t) - _, err := service.CreatePresentationDefinition(model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) + _, err := service.CreatePresentationDefinition(context.Background(), model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) assert.NoError(t, err) - getPd, err := service.GetPresentationDefinition(model.GetPresentationDefinitionRequest{ID: pd.ID}) + getPd, err := service.GetPresentationDefinition(context.Background(), model.GetPresentationDefinitionRequest{ID: pd.ID}) assert.NoError(t, err) assert.Equal(t, pd.ID, getPd.ID) @@ -60,17 +61,17 @@ func TestPresentationDefinitionService(t *testing.T) { t.Run("Get does not return after deletion", func(t *testing.T) { pd := createPresentationDefinition(t) - _, err := service.CreatePresentationDefinition(model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) + _, err := service.CreatePresentationDefinition(context.Background(), model.CreatePresentationDefinitionRequest{PresentationDefinition: *pd}) assert.NoError(t, err) - assert.NoError(t, service.DeletePresentationDefinition(model.DeletePresentationDefinitionRequest{ID: pd.ID})) + assert.NoError(t, service.DeletePresentationDefinition(context.Background(), model.DeletePresentationDefinitionRequest{ID: pd.ID})) - _, err = service.GetPresentationDefinition(model.GetPresentationDefinitionRequest{ID: pd.ID}) + _, err = service.GetPresentationDefinition(context.Background(), model.GetPresentationDefinitionRequest{ID: pd.ID}) assert.Error(t, err) }) t.Run("Delete can be called with any ID", func(t *testing.T) { - err := service.DeletePresentationDefinition(model.DeletePresentationDefinitionRequest{ID: "some crazy ID"}) + err := service.DeletePresentationDefinition(context.Background(), model.DeletePresentationDefinitionRequest{ID: "some crazy ID"}) assert.NoError(t, err) }) } diff --git a/pkg/server/router/schema.go b/pkg/server/router/schema.go index dbe76917d..53bc27f6d 100644 --- a/pkg/server/router/schema.go +++ b/pkg/server/router/schema.go @@ -101,7 +101,7 @@ func (sr SchemaRouter) GetSchema(ctx context.Context, w http.ResponseWriter, r * } // TODO(gabe) differentiate between internal errors and not found schemas - gotSchema, err := sr.service.GetSchema(schema.GetSchemaRequest{ID: *id}) + gotSchema, err := sr.service.GetSchema(ctx, schema.GetSchemaRequest{ID: *id}) if err != nil { errMsg := fmt.Sprintf("could not get schema with id: %s", *id) logrus.WithError(err).Error(errMsg) @@ -126,7 +126,7 @@ type GetSchemasResponse struct { // @Failure 500 {string} string "Internal server error" // @Router /v1/schemas [get] func (sr SchemaRouter) GetSchemas(ctx context.Context, w http.ResponseWriter, r *http.Request) error { - gotSchemas, err := sr.service.GetSchemas() + gotSchemas, err := sr.service.GetSchemas(ctx) if err != nil { errMsg := "could not get schemas" logrus.WithError(err).Error(errMsg) @@ -204,7 +204,7 @@ func (sr SchemaRouter) DeleteSchema(ctx context.Context, w http.ResponseWriter, return framework.NewRequestErrorMsg(errMsg, http.StatusBadRequest) } - if err := sr.service.DeleteSchema(schema.DeleteSchemaRequest{ID: *id}); err != nil { + if err := sr.service.DeleteSchema(ctx, schema.DeleteSchemaRequest{ID: *id}); err != nil { errMsg := fmt.Sprintf("could not delete schema with id: %s", *id) logrus.WithError(err).Error(errMsg) return framework.NewRequestError(errors.Wrap(err, errMsg), http.StatusInternalServerError) diff --git a/pkg/server/router/schema_test.go b/pkg/server/router/schema_test.go index f408dd3a6..3d586c04d 100644 --- a/pkg/server/router/schema_test.go +++ b/pkg/server/router/schema_test.go @@ -1,6 +1,7 @@ package router import ( + "context" "testing" "github.com/TBD54566975/ssi-sdk/crypto" @@ -45,12 +46,12 @@ func TestSchemaRouter(t *testing.T) { assert.Equal(tt, framework.StatusReady, schemaService.Status().Status) // get all schemas (none) - gotSchemas, err := schemaService.GetSchemas() + gotSchemas, err := schemaService.GetSchemas(context.Background()) assert.NoError(tt, err) assert.Empty(tt, gotSchemas.Schemas) // get schema that doesn't exist - _, err = schemaService.GetSchema(schema.GetSchemaRequest{ID: "bad"}) + _, err = schemaService.GetSchema(context.Background(), schema.GetSchemaRequest{ID: "bad"}) assert.Error(tt, err) assert.Contains(tt, err.Error(), "error getting schema") @@ -65,7 +66,7 @@ func TestSchemaRouter(t *testing.T) { "required": []any{"foo"}, "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) assert.NotEmpty(tt, createdSchema.ID) @@ -73,19 +74,19 @@ func TestSchemaRouter(t *testing.T) { assert.Equal(tt, "simple schema", createdSchema.Schema.Name) // get schema by ID - gotSchema, err := schemaService.GetSchema(schema.GetSchemaRequest{ID: createdSchema.ID}) + gotSchema, err := schemaService.GetSchema(context.Background(), schema.GetSchemaRequest{ID: createdSchema.ID}) assert.NoError(tt, err) assert.NotEmpty(tt, gotSchema) assert.EqualValues(tt, createdSchema.Schema, gotSchema.Schema) // get all schemas, expect one - gotSchemas, err = schemaService.GetSchemas() + gotSchemas, err = schemaService.GetSchemas(context.Background()) assert.NoError(tt, err) assert.NotEmpty(tt, gotSchemas.Schemas) assert.Len(tt, gotSchemas.Schemas, 1) // store another - createdSchema, err = schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema 2", Schema: simpleSchema}) + createdSchema, err = schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema 2", Schema: simpleSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) assert.NotEmpty(tt, createdSchema.ID) @@ -93,7 +94,7 @@ func TestSchemaRouter(t *testing.T) { assert.Equal(tt, "simple schema 2", createdSchema.Schema.Name) // get all schemas, expect two - gotSchemas, err = schemaService.GetSchemas() + gotSchemas, err = schemaService.GetSchemas(context.Background()) assert.NoError(tt, err) assert.NotEmpty(tt, gotSchemas.Schemas) assert.Len(tt, gotSchemas.Schemas, 2) @@ -102,11 +103,11 @@ func TestSchemaRouter(t *testing.T) { assert.True(tt, gotSchemas.Schemas[0].ID != gotSchemas.Schemas[1].ID) // delete the first schema - err = schemaService.DeleteSchema(schema.DeleteSchemaRequest{ID: gotSchemas.Schemas[0].ID}) + err = schemaService.DeleteSchema(context.Background(), schema.DeleteSchemaRequest{ID: gotSchemas.Schemas[0].ID}) assert.NoError(tt, err) // get all schemas, expect one - gotSchemas, err = schemaService.GetSchemas() + gotSchemas, err = schemaService.GetSchemas(context.Background()) assert.NoError(tt, err) assert.NotEmpty(tt, gotSchemas.Schemas) assert.Len(tt, gotSchemas.Schemas, 1) @@ -141,7 +142,7 @@ func TestSchemaSigning(t *testing.T) { "required": []any{"foo"}, "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) assert.NotEmpty(tt, createdSchema.ID) @@ -150,20 +151,20 @@ func TestSchemaSigning(t *testing.T) { assert.Equal(tt, "simple schema", createdSchema.Schema.Name) // missing DID - createdSchema, err = schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema, Sign: true}) + createdSchema, err = schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema, Sign: true}) assert.Error(tt, err) assert.Empty(tt, createdSchema) assert.Contains(tt, err.Error(), "could not get key for signing schema for author") // create an author DID - authorDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + authorDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) assert.NoError(tt, err) assert.NotEmpty(tt, authorDID) - createdSchema, err = schemaService.CreateSchema(schema.CreateSchemaRequest{Author: authorDID.DID.ID, Name: "simple schema", Schema: simpleSchema, Sign: true}) + createdSchema, err = schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: authorDID.DID.ID, Name: "simple schema", Schema: simpleSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) assert.NotEmpty(tt, createdSchema.SchemaJWT) diff --git a/pkg/server/server_credential_test.go b/pkg/server/server_credential_test.go index 14ac92b51..9914030c4 100644 --- a/pkg/server/server_credential_test.go +++ b/pkg/server/server_credential_test.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "net/http" "net/http/httptest" @@ -32,7 +33,7 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -110,7 +111,7 @@ func TestCredentialAPI(t *testing.T) { w := httptest.NewRecorder() - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -131,7 +132,7 @@ func TestCredentialAPI(t *testing.T) { "required": []any{"firstName", "lastName"}, "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -220,7 +221,7 @@ func TestCredentialAPI(t *testing.T) { // reset recorder between calls w.Flush() - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -272,7 +273,7 @@ func TestCredentialAPI(t *testing.T) { w := httptest.NewRecorder() - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -293,7 +294,7 @@ func TestCredentialAPI(t *testing.T) { "required": []any{"firstName", "lastName"}, "additionalProperties": false, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: "me", Name: "simple schema", Schema: simpleSchema}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -345,7 +346,7 @@ func TestCredentialAPI(t *testing.T) { w := httptest.NewRecorder() - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -398,7 +399,7 @@ func TestCredentialAPI(t *testing.T) { w := httptest.NewRecorder() - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -451,7 +452,7 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -516,7 +517,7 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -583,14 +584,14 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) assert.NoError(tt, err) assert.NotEmpty(tt, issuerDID) - issuerDIDTwo, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDIDTwo, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -753,7 +754,7 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -825,7 +826,7 @@ func TestCredentialAPI(t *testing.T) { schemaService := testSchemaService(tt, bolt, keyStoreService, didService) credRouter := testCredentialRouter(tt, bolt, keyStoreService, didService, schemaService) - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) diff --git a/pkg/server/server_issuance_test.go b/pkg/server/server_issuance_test.go index 8eea0f58c..edc058683 100644 --- a/pkg/server/server_issuance_test.go +++ b/pkg/server/server_issuance_test.go @@ -1,6 +1,7 @@ package server import ( + "context" "net/http" "net/http/httptest" "testing" @@ -423,7 +424,7 @@ func setupAllThings(t *testing.T) (*did.CreateDIDResponse, *schema.CreateSchemaR credSvc := testCredentialService(t, s, keyStoreSvc, didSvc, schemaSvc) _, manifestSvc := testManifest(t, s, keyStoreSvc, didSvc, credSvc) - issuerResp, err := didSvc.CreateDIDByMethod(did.CreateDIDRequest{ + issuerResp, err := didSvc.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: "key", KeyType: crypto.Ed25519, }) @@ -438,10 +439,10 @@ func setupAllThings(t *testing.T) (*did.CreateDIDResponse, *schema.CreateSchemaR }, "additionalProperties": true, } - createdSchema, err := schemaSvc.CreateSchema(schema.CreateSchemaRequest{Author: issuerResp.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaSvc.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerResp.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(t, err) sillyName := "some silly name" - manifest, err := manifestSvc.CreateManifest(model.CreateManifestRequest{ + manifest, err := manifestSvc.CreateManifest(context.Background(), model.CreateManifestRequest{ Name: &sillyName, IssuerDID: issuerResp.DID.ID, ClaimFormat: &exchange.ClaimFormat{ diff --git a/pkg/server/server_manifest_test.go b/pkg/server/server_manifest_test.go index c4d812971..f7c996448 100644 --- a/pkg/server/server_manifest_test.go +++ b/pkg/server/server_manifest_test.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "net/http" "net/http/httptest" @@ -47,7 +48,7 @@ func TestManifestAPI(t *testing.T) { w.Flush() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -64,7 +65,7 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -121,7 +122,7 @@ func TestManifestAPI(t *testing.T) { w.Flush() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -138,7 +139,7 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -179,7 +180,7 @@ func TestManifestAPI(t *testing.T) { w := httptest.NewRecorder() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -196,7 +197,7 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -244,7 +245,7 @@ func TestManifestAPI(t *testing.T) { manifestRouter, _ := testManifest(tt, bolt, keyStoreService, didService, credentialService) // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -261,7 +262,7 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) @@ -334,7 +335,7 @@ func TestManifestAPI(t *testing.T) { w.Flush() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -342,7 +343,7 @@ func TestManifestAPI(t *testing.T) { assert.NotEmpty(tt, issuerDID) // create an applicant - applicantDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + applicantDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -359,12 +360,12 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // issue a credential against the schema to the subject, from the issuer - createdCred, err := credentialService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credentialService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuerDID.DID.ID, Subject: applicantDID.DID.ID, JSONSchema: createdSchema.ID, @@ -465,7 +466,7 @@ func TestManifestAPI(t *testing.T) { w.Flush() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -473,7 +474,7 @@ func TestManifestAPI(t *testing.T) { assert.NotEmpty(tt, issuerDID) // create an applicant - applicantDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + applicantDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -490,12 +491,12 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // issue a credential against the schema to the subject, from the issuer - createdCred, err := credentialService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credentialService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuerDID.DID.ID, Subject: applicantDID.DID.ID, JSONSchema: createdSchema.ID, @@ -615,7 +616,7 @@ func TestManifestAPI(t *testing.T) { w.Flush() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -623,7 +624,7 @@ func TestManifestAPI(t *testing.T) { assert.NotEmpty(tt, issuerDID) // create an applicant - applicantDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + applicantDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -640,12 +641,12 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // issue a credential against the schema to the subject, from the issuer - createdCred, err := credentialService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credentialService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuerDID.DID.ID, Subject: applicantDID.DID.ID, JSONSchema: createdSchema.ID, @@ -767,7 +768,7 @@ func TestManifestAPI(t *testing.T) { w := httptest.NewRecorder() // create an issuer - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -775,7 +776,7 @@ func TestManifestAPI(t *testing.T) { assert.NotEmpty(tt, issuerDID) // create an applicant - applicantDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + applicantDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) @@ -792,12 +793,12 @@ func TestManifestAPI(t *testing.T) { }, "additionalProperties": true, } - createdSchema, err := schemaService.CreateSchema(schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) + createdSchema, err := schemaService.CreateSchema(context.Background(), schema.CreateSchemaRequest{Author: issuerDID.DID.ID, Name: "license schema", Schema: licenseSchema, Sign: true}) assert.NoError(tt, err) assert.NotEmpty(tt, createdSchema) // issue a credential against the schema to the subject, from the issuer - createdCred, err := credentialService.CreateCredential(credential.CreateCredentialRequest{ + createdCred, err := credentialService.CreateCredential(context.Background(), credential.CreateCredentialRequest{ Issuer: issuerDID.DID.ID, Subject: applicantDID.DID.ID, JSONSchema: createdSchema.ID, diff --git a/pkg/server/server_schema_test.go b/pkg/server/server_schema_test.go index 87f696bff..1e68ed600 100644 --- a/pkg/server/server_schema_test.go +++ b/pkg/server/server_schema_test.go @@ -1,6 +1,7 @@ package server import ( + "context" "fmt" "net/http" "net/http/httptest" @@ -73,7 +74,7 @@ func TestSchemaAPI(t *testing.T) { assert.Contains(tt, err.Error(), "could not create schema with authoring DID: did:test") // create a DID - issuerDID, err := didService.CreateDIDByMethod(did.CreateDIDRequest{ + issuerDID, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{ Method: didsdk.KeyMethod, KeyType: crypto.Ed25519, }) diff --git a/pkg/service/credential/service.go b/pkg/service/credential/service.go index d2af40175..12b9a3080 100644 --- a/pkg/service/credential/service.go +++ b/pkg/service/credential/service.go @@ -123,7 +123,7 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR var knownSchema *schemalib.VCJSONSchema if request.JSONSchema != "" { // resolve schema and save it for validation later - gotSchema, err := s.schema.GetSchema(schema.GetSchemaRequest{ID: request.JSONSchema}) + gotSchema, err := s.schema.GetSchema(ctx, schema.GetSchemaRequest{ID: request.JSONSchema}) if err != nil { return nil, util.LoggingErrorMsgf(err, "failed to create credential; could not get schema: %s", request.JSONSchema) } @@ -192,7 +192,7 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR // TODO(gabe) support Data Integrity creds too https://github.com/TBD54566975/ssi-service/issues/105 // sign the credential - credJWT, err := s.signCredentialJWT(request.Issuer, *cred) + credJWT, err := s.signCredentialJWT(ctx, request.Issuer, *cred) if err != nil { return nil, util.LoggingErrorMsg(err, "could not sign credential") } @@ -219,7 +219,7 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR } func getStatusListCredential(ctx context.Context, s Service, issuerID string, schemaID string) (*credential.VerifiableCredential, error) { - storedStatusListCreds, err := s.storage.GetStatusListCredentialsByIssuerAndSchema(issuerID, schemaID) + storedStatusListCreds, err := s.storage.GetStatusListCredentialsByIssuerAndSchema(ctx, issuerID, schemaID) if err != nil { return nil, util.LoggingNewErrorf("problem with getting status list credential for issuer: %s schema: %s", issuerID, schemaID) } @@ -239,7 +239,7 @@ func getStatusListCredential(ctx context.Context, s Service, issuerID string, sc return nil, util.LoggingErrorMsg(err, "could not generate status list") } - statusListCredJWT, err := s.signCredentialJWT(issuerID, *generatedStatusListCredential) + statusListCredJWT, err := s.signCredentialJWT(ctx, issuerID, *generatedStatusListCredential) if err != nil { return nil, util.LoggingErrorMsg(err, "could not sign status list credential") } @@ -269,8 +269,8 @@ func getStatusListCredential(ctx context.Context, s Service, issuerID string, sc } // signCredentialJWT signs a credential and returns it as a vc-jwt -func (s Service) signCredentialJWT(issuer string, cred credential.VerifiableCredential) (*keyaccess.JWT, error) { - gotKey, err := s.keyStore.GetKey(keystore.GetKeyRequest{ID: issuer}) +func (s Service) signCredentialJWT(ctx context.Context, issuer string, cred credential.VerifiableCredential) (*keyaccess.JWT, error) { + gotKey, err := s.keyStore.GetKey(ctx, keystore.GetKeyRequest{ID: issuer}) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key for signing credential with key<%s>", issuer) } @@ -314,7 +314,7 @@ type VerifyCredentialResponse struct { // 4. If the credential has a schema, makes sure its data complies with the schema // LATER: Makes sure the credential has not been revoked, other checks. // Note: https://github.com/TBD54566975/ssi-sdk/issues/213 -func (s Service) VerifyCredential(request VerifyCredentialRequest) (*VerifyCredentialResponse, error) { +func (s Service) VerifyCredential(ctx context.Context, request VerifyCredentialRequest) (*VerifyCredentialResponse, error) { logrus.Debugf("verifying credential: %+v", request) @@ -323,11 +323,11 @@ func (s Service) VerifyCredential(request VerifyCredentialRequest) (*VerifyCrede } if request.CredentialJWT != nil { - if err := s.verifier.VerifyJWTCredential(*request.CredentialJWT); err != nil { + if err := s.verifier.VerifyJWTCredential(ctx, *request.CredentialJWT); err != nil { return &VerifyCredentialResponse{Verified: false, Reason: err.Error()}, nil } } else { - if err := s.verifier.VerifyDataIntegrityCredential(*request.DataIntegrityCredential); err != nil { + if err := s.verifier.VerifyDataIntegrityCredential(ctx, *request.DataIntegrityCredential); err != nil { return &VerifyCredentialResponse{Verified: false, Reason: err.Error()}, nil } } @@ -335,11 +335,11 @@ func (s Service) VerifyCredential(request VerifyCredentialRequest) (*VerifyCrede return &VerifyCredentialResponse{Verified: true}, nil } -func (s Service) GetCredential(request GetCredentialRequest) (*GetCredentialResponse, error) { +func (s Service) GetCredential(ctx context.Context, request GetCredentialRequest) (*GetCredentialResponse, error) { logrus.Debugf("getting credential: %s", request.ID) - gotCred, err := s.storage.GetCredential(request.ID) + gotCred, err := s.storage.GetCredential(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential: %s", request.ID) } @@ -356,11 +356,11 @@ func (s Service) GetCredential(request GetCredentialRequest) (*GetCredentialResp return &response, nil } -func (s Service) GetCredentialsByIssuer(request GetCredentialByIssuerRequest) (*GetCredentialsResponse, error) { +func (s Service) GetCredentialsByIssuer(ctx context.Context, request GetCredentialByIssuerRequest) (*GetCredentialsResponse, error) { logrus.Debugf("getting credential(s) for issuer: %s", util.SanitizeLog(request.Issuer)) - gotCreds, err := s.storage.GetCredentialsByIssuer(request.Issuer) + gotCreds, err := s.storage.GetCredentialsByIssuer(ctx, request.Issuer) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential(s) for issuer: %s", request.Issuer) } @@ -379,11 +379,11 @@ func (s Service) GetCredentialsByIssuer(request GetCredentialByIssuerRequest) (* return &response, nil } -func (s Service) GetCredentialsBySubject(request GetCredentialBySubjectRequest) (*GetCredentialsResponse, error) { +func (s Service) GetCredentialsBySubject(ctx context.Context, request GetCredentialBySubjectRequest) (*GetCredentialsResponse, error) { logrus.Debugf("getting credential(s) for subject: %s", util.SanitizeLog(request.Subject)) - gotCreds, err := s.storage.GetCredentialsBySubject(request.Subject) + gotCreds, err := s.storage.GetCredentialsBySubject(ctx, request.Subject) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential(s) for subject: %s", request.Subject) } @@ -401,11 +401,11 @@ func (s Service) GetCredentialsBySubject(request GetCredentialBySubjectRequest) return &response, nil } -func (s Service) GetCredentialsBySchema(request GetCredentialBySchemaRequest) (*GetCredentialsResponse, error) { +func (s Service) GetCredentialsBySchema(ctx context.Context, request GetCredentialBySchemaRequest) (*GetCredentialsResponse, error) { logrus.Debugf("getting credential(s) for schema: %s", util.SanitizeLog(request.Schema)) - gotCreds, err := s.storage.GetCredentialsBySchema(request.Schema) + gotCreds, err := s.storage.GetCredentialsBySchema(ctx, request.Schema) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential(s) for schema: %s", request.Schema) } @@ -423,10 +423,10 @@ func (s Service) GetCredentialsBySchema(request GetCredentialBySchemaRequest) (* return &response, nil } -func (s Service) GetCredentialStatus(request GetCredentialStatusRequest) (*GetCredentialStatusResponse, error) { +func (s Service) GetCredentialStatus(ctx context.Context, request GetCredentialStatusRequest) (*GetCredentialStatusResponse, error) { logrus.Debugf("getting credential status: %s", request.ID) - gotCred, err := s.storage.GetCredential(request.ID) + gotCred, err := s.storage.GetCredential(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential: %s", request.ID) } @@ -439,11 +439,11 @@ func (s Service) GetCredentialStatus(request GetCredentialStatusRequest) (*GetCr return &response, nil } -func (s Service) GetCredentialStatusList(request GetCredentialStatusListRequest) (*GetCredentialStatusListResponse, error) { +func (s Service) GetCredentialStatusList(ctx context.Context, request GetCredentialStatusListRequest) (*GetCredentialStatusListResponse, error) { logrus.Debugf("getting credential status list: %s", request.ID) credStatusListID := fmt.Sprintf(`%s/v1/credentials/status/%s`, s.config.ServiceEndpoint, request.ID) - gotCred, err := s.storage.GetStatusListCredential(credStatusListID) + gotCred, err := s.storage.GetStatusListCredential(ctx, credStatusListID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential: %s", request.ID) } @@ -463,7 +463,7 @@ func (s Service) GetCredentialStatusList(request GetCredentialStatusListRequest) func (s Service) UpdateCredentialStatus(ctx context.Context, request UpdateCredentialStatusRequest) (*UpdateCredentialStatusResponse, error) { logrus.Debugf("updating credential status: %s to Revoked: %v", request.ID, request.Revoked) - gotCred, err := s.storage.GetCredential(request.ID) + gotCred, err := s.storage.GetCredential(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential: %s", request.ID) } @@ -509,7 +509,7 @@ func updateCredentialStatus(ctx context.Context, s Service, gotCred *StoredCrede return nil, util.LoggingNewErrorf("problem with getting status list credential id") } - creds, err := s.storage.GetCredentialsByIssuerAndSchema(gotCred.Issuer, gotCred.Schema) + creds, err := s.storage.GetCredentialsByIssuerAndSchema(ctx, gotCred.Issuer, gotCred.Schema) if err != nil { return nil, util.LoggingNewErrorf("problem with getting status list credential for issuer: %s schema: %s", gotCred.Issuer, gotCred.Schema) } @@ -526,7 +526,7 @@ func updateCredentialStatus(ctx context.Context, s Service, gotCred *StoredCrede return nil, util.LoggingErrorMsg(err, "could not generate status list") } - statusListCredJWT, err := s.signCredentialJWT(gotCred.Issuer, *generatedStatusListCredential) + statusListCredJWT, err := s.signCredentialJWT(ctx, gotCred.Issuer, *generatedStatusListCredential) if err != nil { return nil, util.LoggingErrorMsg(err, "could not sign status list credential") } @@ -549,8 +549,8 @@ func updateCredentialStatus(ctx context.Context, s Service, gotCred *StoredCrede return &container, nil } -func (s Service) GetCredentialsByIssuerAndSchemaWithStatus(issuer string, schema string) ([]credential.VerifiableCredential, error) { - gotCreds, err := s.storage.GetCredentialsByIssuerAndSchema(issuer, schema) +func (s Service) GetCredentialsByIssuerAndSchemaWithStatus(ctx context.Context, issuer string, schema string) ([]credential.VerifiableCredential, error) { + gotCreds, err := s.storage.GetCredentialsByIssuerAndSchema(ctx, issuer, schema) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential(s) for issuer: %s", issuer) } @@ -565,11 +565,11 @@ func (s Service) GetCredentialsByIssuerAndSchemaWithStatus(issuer string, schema return creds, nil } -func (s Service) DeleteCredential(request DeleteCredentialRequest) error { +func (s Service) DeleteCredential(ctx context.Context, request DeleteCredentialRequest) error { logrus.Debugf("deleting credential: %s", request.ID) - if err := s.storage.DeleteCredential(request.ID); err != nil { + if err := s.storage.DeleteCredential(ctx, request.ID); err != nil { return util.LoggingErrorMsgf(err, "could not delete credential with id: %s", request.ID) } diff --git a/pkg/service/credential/storage.go b/pkg/service/credential/storage.go index c801555f6..2a76b8a51 100644 --- a/pkg/service/credential/storage.go +++ b/pkg/service/credential/storage.go @@ -103,7 +103,7 @@ func NewCredentialStorage(db storage.ServiceStorage) (*Storage, error) { func (cs *Storage) GetNextStatusListRandomIndex(ctx context.Context) (int, error) { - gotUniqueNumBytes, err := cs.db.Read(statusListIndexNamespace, statusListIndexesKey) + gotUniqueNumBytes, err := cs.db.Read(ctx, statusListIndexNamespace, statusListIndexesKey) if err != nil { return -1, util.LoggingErrorMsgf(err, "reading status list") } @@ -117,7 +117,7 @@ func (cs *Storage) GetNextStatusListRandomIndex(ctx context.Context) (int, error return -1, util.LoggingErrorMsgf(err, "could not unmarshal unique numbers") } - gotCurrentListIndexBytes, err := cs.db.Read(statusListIndexNamespace, currentListIndexKey) + gotCurrentListIndexBytes, err := cs.db.Read(ctx, statusListIndexNamespace, currentListIndexKey) if err != nil { return -1, util.LoggingErrorMsgf(err, "could not get list index") } @@ -203,16 +203,16 @@ func buildStoredCredential(request StoreCredentialRequest) (*StoredCredential, e }, nil } -func (cs *Storage) GetCredential(id string) (*StoredCredential, error) { - return cs.getCredential(id, credentialNamespace) +func (cs *Storage) GetCredential(ctx context.Context, id string) (*StoredCredential, error) { + return cs.getCredential(ctx, id, credentialNamespace) } -func (cs *Storage) GetStatusListCredential(id string) (*StoredCredential, error) { - return cs.getCredential(id, statusListCredentialNamespace) +func (cs *Storage) GetStatusListCredential(ctx context.Context, id string) (*StoredCredential, error) { + return cs.getCredential(ctx, id, statusListCredentialNamespace) } -func (cs *Storage) getCredential(id string, namespace string) (*StoredCredential, error) { - prefixValues, err := cs.db.ReadPrefix(namespace, id) +func (cs *Storage) getCredential(ctx context.Context, id string, namespace string) (*StoredCredential, error) { + prefixValues, err := cs.db.ReadPrefix(ctx, namespace, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get credential from storage: %s", id) } @@ -244,8 +244,8 @@ func (cs *Storage) getCredential(id string, namespace string) (*StoredCredential // GetCredentialsByIssuer gets all credentials stored with a prefix key containing the issuer value // The method is greedy, meaning if multiple values are found and some fail during processing, we will // return only the successful values and log an error for the failures. -func (cs *Storage) GetCredentialsByIssuer(issuer string) ([]StoredCredential, error) { - keys, err := cs.db.ReadAllKeys(credentialNamespace) +func (cs *Storage) GetCredentialsByIssuer(ctx context.Context, issuer string) ([]StoredCredential, error) { + keys, err := cs.db.ReadAllKeys(ctx, credentialNamespace) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not read credential storage while searching for creds for issuer: %s", issuer) } @@ -264,7 +264,7 @@ func (cs *Storage) GetCredentialsByIssuer(issuer string) ([]StoredCredential, er // now get each credential by key var storedCreds []StoredCredential for _, key := range issuerKeys { - credBytes, err := cs.db.Read(credentialNamespace, key) + credBytes, err := cs.db.Read(ctx, credentialNamespace, key) if err != nil { logrus.WithError(err).Errorf("could not read credential with key: %s", key) } else { @@ -286,8 +286,8 @@ func (cs *Storage) GetCredentialsByIssuer(issuer string) ([]StoredCredential, er // GetCredentialsBySubject gets all credentials stored with a prefix key containing the subject value // The method is greedy, meaning if multiple values are found...and some fail during processing, we will // return only the successful values and log an error for the failures. -func (cs *Storage) GetCredentialsBySubject(subject string) ([]StoredCredential, error) { - keys, err := cs.db.ReadAllKeys(credentialNamespace) +func (cs *Storage) GetCredentialsBySubject(ctx context.Context, subject string) ([]StoredCredential, error) { + keys, err := cs.db.ReadAllKeys(ctx, credentialNamespace) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not read credential storage while searching for creds for subject: %s", subject) } @@ -307,7 +307,7 @@ func (cs *Storage) GetCredentialsBySubject(subject string) ([]StoredCredential, // now get each credential by key var storedCreds []StoredCredential for _, key := range subjectKeys { - credBytes, err := cs.db.Read(credentialNamespace, key) + credBytes, err := cs.db.Read(ctx, credentialNamespace, key) if err != nil { logrus.WithError(err).Errorf("could not read credential with key: %s", key) } else { @@ -329,8 +329,8 @@ func (cs *Storage) GetCredentialsBySubject(subject string) ([]StoredCredential, // GetCredentialsBySchema gets all credentials stored with a prefix key containing the schema value // The method is greedy, meaning if multiple values are found...and some fail during processing, we will // return only the successful values and log an error for the failures. -func (cs *Storage) GetCredentialsBySchema(schema string) ([]StoredCredential, error) { - keys, err := cs.db.ReadAllKeys(credentialNamespace) +func (cs *Storage) GetCredentialsBySchema(ctx context.Context, schema string) ([]StoredCredential, error) { + keys, err := cs.db.ReadAllKeys(ctx, credentialNamespace) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not read credential storage while searching for creds for schema: %s", schema) } @@ -351,7 +351,7 @@ func (cs *Storage) GetCredentialsBySchema(schema string) ([]StoredCredential, er // now get each credential by key var storedCreds []StoredCredential for _, key := range schemaKeys { - credBytes, err := cs.db.Read(credentialNamespace, key) + credBytes, err := cs.db.Read(ctx, credentialNamespace, key) if err != nil { logrus.WithError(err).Errorf("could not read credential with key: %s", key) } else { @@ -373,16 +373,16 @@ func (cs *Storage) GetCredentialsBySchema(schema string) ([]StoredCredential, er // GetCredentialsByIssuerAndSchema gets all credentials stored with a prefix key containing the issuer value // The method is greedy, meaning if multiple values are found...and some fail during processing, we will // return only the successful values and log an error for the failures. -func (cs *Storage) GetCredentialsByIssuerAndSchema(issuer string, schema string) ([]StoredCredential, error) { - return cs.getCredentialsByIssuerAndSchema(issuer, schema, credentialNamespace) +func (cs *Storage) GetCredentialsByIssuerAndSchema(ctx context.Context, issuer string, schema string) ([]StoredCredential, error) { + return cs.getCredentialsByIssuerAndSchema(ctx, issuer, schema, credentialNamespace) } -func (cs *Storage) GetStatusListCredentialsByIssuerAndSchema(issuer string, schema string) ([]StoredCredential, error) { - return cs.getCredentialsByIssuerAndSchema(issuer, schema, statusListCredentialNamespace) +func (cs *Storage) GetStatusListCredentialsByIssuerAndSchema(ctx context.Context, issuer string, schema string) ([]StoredCredential, error) { + return cs.getCredentialsByIssuerAndSchema(ctx, issuer, schema, statusListCredentialNamespace) } -func (cs *Storage) getCredentialsByIssuerAndSchema(issuer string, schema string, namespace string) ([]StoredCredential, error) { - keys, err := cs.db.ReadAllKeys(namespace) +func (cs *Storage) getCredentialsByIssuerAndSchema(ctx context.Context, issuer string, schema string, namespace string) ([]StoredCredential, error) { + keys, err := cs.db.ReadAllKeys(ctx, namespace) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not read credential storage while searching for creds for issuer: %s", issuer) } @@ -403,7 +403,7 @@ func (cs *Storage) getCredentialsByIssuerAndSchema(issuer string, schema string, // now get each credential by key var storedCreds []StoredCredential for _, key := range issuerSchemaKeys { - credBytes, err := cs.db.Read(namespace, key) + credBytes, err := cs.db.Read(ctx, namespace, key) if err != nil { logrus.WithError(err).Errorf("could not read credential with key: %s", key) } else { @@ -422,19 +422,19 @@ func (cs *Storage) getCredentialsByIssuerAndSchema(issuer string, schema string, return storedCreds, nil } -func (cs *Storage) DeleteCredential(id string) error { - return cs.deleteCredential(id, credentialNamespace) +func (cs *Storage) DeleteCredential(ctx context.Context, id string) error { + return cs.deleteCredential(ctx, id, credentialNamespace) } -func (cs *Storage) DeleteStatusListCredential(id string) error { - return cs.deleteCredential(id, statusListCredentialNamespace) +func (cs *Storage) DeleteStatusListCredential(ctx context.Context, id string) error { + return cs.deleteCredential(ctx, id, statusListCredentialNamespace) } -func (cs *Storage) deleteCredential(id string, namespace string) error { +func (cs *Storage) deleteCredential(ctx context.Context, id string, namespace string) error { credDoesNotExistMsg := fmt.Sprintf("credential does not exist, cannot delete: %s", id) // first get the credential to regenerate the prefix key - gotCred, err := cs.GetCredential(id) + gotCred, err := cs.GetCredential(ctx, id) if err != nil { // no error on deletion for a non-existent credential if strings.Contains(err.Error(), credentialNotFoundErrMsg) { @@ -453,7 +453,7 @@ func (cs *Storage) deleteCredential(id string, namespace string) error { // re-create the prefix key to delete prefix := createPrefixKey(id, gotCred.Issuer, gotCred.Subject, gotCred.Schema) - if err = cs.db.Delete(namespace, prefix); err != nil { + if err = cs.db.Delete(ctx, namespace, prefix); err != nil { return util.LoggingErrorMsgf(err, "could not delete credential: %s", id) } return nil diff --git a/pkg/service/did/key.go b/pkg/service/did/key.go index a1a207477..91702def1 100644 --- a/pkg/service/did/key.go +++ b/pkg/service/did/key.go @@ -74,12 +74,12 @@ func (h *keyDIDHandler) CreateDID(ctx context.Context, request CreateDIDRequest) }, nil } -func (h *keyDIDHandler) GetDID(request GetDIDRequest) (*GetDIDResponse, error) { +func (h *keyDIDHandler) GetDID(ctx context.Context, request GetDIDRequest) (*GetDIDResponse, error) { logrus.Debugf("getting DID: %+v", request) id := request.ID - gotDID, err := h.storage.GetDID(id) + gotDID, err := h.storage.GetDID(ctx, id) if err != nil { return nil, fmt.Errorf("error getting DID: %s", id) } @@ -89,11 +89,11 @@ func (h *keyDIDHandler) GetDID(request GetDIDRequest) (*GetDIDResponse, error) { return &GetDIDResponse{DID: gotDID.DID}, nil } -func (h *keyDIDHandler) GetDIDs(method did.Method) (*GetDIDsResponse, error) { +func (h *keyDIDHandler) GetDIDs(ctx context.Context, method did.Method) (*GetDIDsResponse, error) { logrus.Debugf("getting DIDs for method: %s", method) - gotDIDs, err := h.storage.GetDIDs(string(method)) + gotDIDs, err := h.storage.GetDIDs(ctx, string(method)) if err != nil { return nil, fmt.Errorf("error getting DIDs for method: %s", method) } diff --git a/pkg/service/did/service.go b/pkg/service/did/service.go index a80a5418e..c17fc6a90 100644 --- a/pkg/service/did/service.go +++ b/pkg/service/did/service.go @@ -99,8 +99,8 @@ func NewDIDService(config config.DIDServiceConfig, s storage.ServiceStorage, key // MethodHandler describes the functionality of *all* possible DID service, regardless of method type MethodHandler interface { CreateDID(ctx context.Context, request CreateDIDRequest) (*CreateDIDResponse, error) - GetDID(request GetDIDRequest) (*GetDIDResponse, error) - GetDIDs(method didsdk.Method) (*GetDIDsResponse, error) + GetDID(ctx context.Context, request GetDIDRequest) (*GetDIDResponse, error) + GetDIDs(ctx context.Context, method didsdk.Method) (*GetDIDsResponse, error) } func (s *Service) instantiateHandlerForMethod(method didsdk.Method) error { @@ -146,21 +146,21 @@ func (s *Service) CreateDIDByMethod(ctx context.Context, request CreateDIDReques return handler.CreateDID(ctx, request) } -func (s *Service) GetDIDByMethod(request GetDIDRequest) (*GetDIDResponse, error) { +func (s *Service) GetDIDByMethod(ctx context.Context, request GetDIDRequest) (*GetDIDResponse, error) { handler, err := s.getHandler(request.Method) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get handler for method<%s>", request.Method) } - return handler.GetDID(request) + return handler.GetDID(ctx, request) } -func (s *Service) GetDIDsByMethod(request GetDIDsRequest) (*GetDIDsResponse, error) { +func (s *Service) GetDIDsByMethod(ctx context.Context, request GetDIDsRequest) (*GetDIDsResponse, error) { method := request.Method handler, err := s.getHandler(method) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get handler for method<%s>", method) } - return handler.GetDIDs(method) + return handler.GetDIDs(ctx, method) } func (s *Service) getHandler(method didsdk.Method) (MethodHandler, error) { diff --git a/pkg/service/did/storage.go b/pkg/service/did/storage.go index 237c1ac9c..52b5b66d9 100644 --- a/pkg/service/did/storage.go +++ b/pkg/service/did/storage.go @@ -55,13 +55,13 @@ func (ds *Storage) StoreDID(ctx context.Context, did StoredDID) error { return ds.db.Write(ctx, ns, did.ID, didBytes) } -func (ds *Storage) GetDID(id string) (*StoredDID, error) { +func (ds *Storage) GetDID(ctx context.Context, id string) (*StoredDID, error) { couldNotGetDIDErr := fmt.Sprintf("could not get DID: %s", id) ns, err := getNamespaceForDID(id) if err != nil { return nil, util.LoggingErrorMsg(err, couldNotGetDIDErr) } - docBytes, err := ds.db.Read(ns, id) + docBytes, err := ds.db.Read(ctx, ns, id) if err != nil { return nil, util.LoggingErrorMsg(err, couldNotGetDIDErr) } @@ -77,13 +77,13 @@ func (ds *Storage) GetDID(id string) (*StoredDID, error) { } // GetDIDs attempts to get all DIDs for a given method. It will return those it can even if it has trouble with some. -func (ds *Storage) GetDIDs(method string) ([]StoredDID, error) { +func (ds *Storage) GetDIDs(ctx context.Context, method string) ([]StoredDID, error) { couldNotGetDIDsErr := fmt.Sprintf("could not get DIDs for method: %s", method) ns, err := getNamespaceForMethod(method) if err != nil { return nil, util.LoggingErrorMsg(err, couldNotGetDIDsErr) } - gotDIDs, err := ds.db.ReadAll(ns) + gotDIDs, err := ds.db.ReadAll(ctx, ns) if err != nil { return nil, util.LoggingErrorMsg(err, couldNotGetDIDsErr) } @@ -101,13 +101,13 @@ func (ds *Storage) GetDIDs(method string) ([]StoredDID, error) { return stored, nil } -func (ds *Storage) DeleteDID(id string) error { +func (ds *Storage) DeleteDID(ctx context.Context, id string) error { couldNotGetDIDErr := fmt.Sprintf("could not delete DID: %s", id) ns, err := getNamespaceForDID(id) if err != nil { return util.LoggingErrorMsg(err, couldNotGetDIDErr) } - if err = ds.db.Delete(ns, id); err != nil { + if err = ds.db.Delete(ctx, ns, id); err != nil { return util.LoggingErrorMsgf(err, "could not delete DID: %s", id) } return nil diff --git a/pkg/service/did/web.go b/pkg/service/did/web.go index 858cfabd9..033e68091 100644 --- a/pkg/service/did/web.go +++ b/pkg/service/did/web.go @@ -86,12 +86,12 @@ func (h *webDIDHandler) CreateDID(ctx context.Context, request CreateDIDRequest) }, nil } -func (h *webDIDHandler) GetDID(request GetDIDRequest) (*GetDIDResponse, error) { +func (h *webDIDHandler) GetDID(ctx context.Context, request GetDIDRequest) (*GetDIDResponse, error) { logrus.Debugf("getting DID: %+v", request) id := request.ID - gotDID, err := h.storage.GetDID(id) + gotDID, err := h.storage.GetDID(ctx, id) if err != nil { return nil, fmt.Errorf("error getting DID: %s", id) } @@ -101,11 +101,11 @@ func (h *webDIDHandler) GetDID(request GetDIDRequest) (*GetDIDResponse, error) { return &GetDIDResponse{DID: gotDID.DID}, nil } -func (h *webDIDHandler) GetDIDs(method did.Method) (*GetDIDsResponse, error) { +func (h *webDIDHandler) GetDIDs(ctx context.Context, method did.Method) (*GetDIDsResponse, error) { logrus.Debugf("getting DIDs for method: %s", method) - gotDIDs, err := h.storage.GetDIDs(string(method)) + gotDIDs, err := h.storage.GetDIDs(ctx, string(method)) if err != nil { return nil, fmt.Errorf("error getting DIDs for method: %s", method) } diff --git a/pkg/service/issuing/service.go b/pkg/service/issuing/service.go index 052092af0..f0d116832 100644 --- a/pkg/service/issuing/service.go +++ b/pkg/service/issuing/service.go @@ -40,8 +40,8 @@ func NewIssuingService(config config.IssuingServiceConfig, s storage.ServiceStor }, nil } -func (s *Service) GetIssuanceTemplate(request *GetIssuanceTemplateRequest) (*GetIssuanceTemplateResponse, error) { - storedIssuanceTemplate, err := s.storage.GetIssuanceTemplate(request.ID) +func (s *Service) GetIssuanceTemplate(ctx context.Context, request *GetIssuanceTemplateRequest) (*GetIssuanceTemplateResponse, error) { + storedIssuanceTemplate, err := s.storage.GetIssuanceTemplate(ctx, request.ID) if err != nil { return nil, errors.Wrapf(err, "getting issuance template with id: %s", request.ID) } @@ -65,13 +65,13 @@ func (s *Service) CreateIssuanceTemplate(ctx context.Context, request *CreateIss return nil, errors.Errorf("ID cannot be empty at index %d", i) } if c.Schema != "" { - if _, err := s.schemaStorage.GetSchema(c.Schema); err != nil { + if _, err := s.schemaStorage.GetSchema(ctx, c.Schema); err != nil { return nil, errors.Wrapf(err, "getting schema at index %d", i) } } } - if _, err := s.manifestStorage.GetManifest(request.IssuanceTemplate.CredentialManifest); err != nil { + if _, err := s.manifestStorage.GetManifest(ctx, request.IssuanceTemplate.CredentialManifest); err != nil { return nil, errors.Wrap(err, "getting manifest") } @@ -91,19 +91,19 @@ func serviceModel(template StoredIssuanceTemplate) *IssuanceTemplate { return &template.IssuanceTemplate } -func (s *Service) DeleteIssuanceTemplate(request *DeleteIssuanceTemplateRequest) error { - if err := s.storage.DeleteIssuanceTemplate(request.ID); err != nil { +func (s *Service) DeleteIssuanceTemplate(ctx context.Context, request *DeleteIssuanceTemplateRequest) error { + if err := s.storage.DeleteIssuanceTemplate(ctx, request.ID); err != nil { return errors.Wrap(err, "deleting template from storage") } return nil } -func (s *Service) ListIssuanceTemplates(request *ListIssuanceTemplatesRequest) (*ListIssuanceTemplatesResponse, error) { +func (s *Service) ListIssuanceTemplates(ctx context.Context, request *ListIssuanceTemplatesRequest) (*ListIssuanceTemplatesResponse, error) { if err := request.Validate(); err != nil { return nil, errors.Wrap(err, "invalid request") } - ops, err := s.storage.ListIssuanceTemplates() + ops, err := s.storage.ListIssuanceTemplates(ctx) if err != nil { return nil, errors.Wrap(err, "fetching ops from storage") } diff --git a/pkg/service/issuing/storage.go b/pkg/service/issuing/storage.go index 9e3df9650..24e17887a 100644 --- a/pkg/service/issuing/storage.go +++ b/pkg/service/issuing/storage.go @@ -38,11 +38,11 @@ func (s Storage) StoreIssuanceTemplate(ctx context.Context, template StoredIssua return s.db.Write(ctx, namespace, template.IssuanceTemplate.ID, data) } -func (s Storage) GetIssuanceTemplate(id string) (*StoredIssuanceTemplate, error) { +func (s Storage) GetIssuanceTemplate(ctx context.Context, id string) (*StoredIssuanceTemplate, error) { if id == "" { return nil, errors.New("cannot fetch issuance template without an ID") } - data, err := s.db.Read(namespace, id) + data, err := s.db.Read(ctx, namespace, id) if err != nil { return nil, errors.Wrap(err, "reading from db") } @@ -56,18 +56,18 @@ func (s Storage) GetIssuanceTemplate(id string) (*StoredIssuanceTemplate, error) return &st, nil } -func (s Storage) DeleteIssuanceTemplate(id string) error { +func (s Storage) DeleteIssuanceTemplate(ctx context.Context, id string) error { if id == "" { return nil } - if err := s.db.Delete(namespace, id); err != nil { + if err := s.db.Delete(ctx, namespace, id); err != nil { return errors.Wrap(err, "deleting from db") } return nil } -func (s Storage) ListIssuanceTemplates() ([]IssuanceTemplate, error) { - m, err := s.db.ReadAll(namespace) +func (s Storage) ListIssuanceTemplates(ctx context.Context) ([]IssuanceTemplate, error) { + m, err := s.db.ReadAll(ctx, namespace) if err != nil { return nil, errors.Wrap(err, "reading all") } diff --git a/pkg/service/keystore/service.go b/pkg/service/keystore/service.go index e31abbf3e..ad5788cb3 100644 --- a/pkg/service/keystore/service.go +++ b/pkg/service/keystore/service.go @@ -94,12 +94,12 @@ func (s Service) StoreKey(ctx context.Context, request StoreKeyRequest) error { return nil } -func (s Service) GetKey(request GetKeyRequest) (*GetKeyResponse, error) { +func (s Service) GetKey(ctx context.Context, request GetKeyRequest) (*GetKeyResponse, error) { logrus.Debugf("getting key: %+v", request) id := request.ID - gotKey, err := s.storage.GetKey(id) + gotKey, err := s.storage.GetKey(ctx, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key for key: %s", id) } @@ -126,12 +126,12 @@ func (s Service) GetKey(request GetKeyRequest) (*GetKeyResponse, error) { }, nil } -func (s Service) GetKeyDetails(request GetKeyDetailsRequest) (*GetKeyDetailsResponse, error) { +func (s Service) GetKeyDetails(ctx context.Context, request GetKeyDetailsRequest) (*GetKeyDetailsResponse, error) { logrus.Debugf("getting key: %+v", request) id := request.ID - gotKeyDetails, err := s.storage.GetKeyDetails(id) + gotKeyDetails, err := s.storage.GetKeyDetails(ctx, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key details for key: %s", id) } diff --git a/pkg/service/keystore/service_test.go b/pkg/service/keystore/service_test.go index 9357db7e1..170ee6c02 100644 --- a/pkg/service/keystore/service_test.go +++ b/pkg/service/keystore/service_test.go @@ -1,6 +1,7 @@ package keystore import ( + "context" "os" "testing" @@ -120,7 +121,7 @@ func TestStoreAndGetKey(t *testing.T) { // store the key _, privKey, err := crypto.GenerateEd25519Key() assert.NoError(t, err) - err = keyStore.StoreKey(StoreKeyRequest{ + err = keyStore.StoreKey(context.Background(), StoreKeyRequest{ ID: "test-id", Type: crypto.Ed25519, Controller: "test-controller", @@ -129,7 +130,7 @@ func TestStoreAndGetKey(t *testing.T) { assert.NoError(t, err) // get it back - keyResponse, err := keyStore.GetKey(GetKeyRequest{ID: "test-id"}) + keyResponse, err := keyStore.GetKey(context.Background(), GetKeyRequest{ID: "test-id"}) assert.NoError(t, err) assert.NotEmpty(t, keyResponse) assert.Equal(t, privKey, keyResponse.Key) diff --git a/pkg/service/keystore/storage.go b/pkg/service/keystore/storage.go index 193d2095d..6206dbd02 100644 --- a/pkg/service/keystore/storage.go +++ b/pkg/service/keystore/storage.go @@ -72,12 +72,12 @@ func (kss *Storage) storeServiceKey(ctx context.Context, key ServiceKey) error { } // getAndSetServiceKey attempts to get the service key from memory, and if not available rehydrates it from the DB -func (kss *Storage) getAndSetServiceKey() ([]byte, error) { +func (kss *Storage) getAndSetServiceKey(ctx context.Context) ([]byte, error) { if len(kss.serviceKey) != 0 { return kss.serviceKey, nil } - storedKeyBytes, err := kss.db.Read(namespace, skKey) + storedKeyBytes, err := kss.db.Read(ctx, namespace, skKey) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get service key") } @@ -111,7 +111,7 @@ func (kss *Storage) StoreKey(ctx context.Context, key StoredKey) error { } // get service key - serviceKey, err := kss.getAndSetServiceKey() + serviceKey, err := kss.getAndSetServiceKey(ctx) if err != nil { return util.LoggingErrorMsgf(err, "could not get service key while storing key: %s", id) } @@ -125,8 +125,8 @@ func (kss *Storage) StoreKey(ctx context.Context, key StoredKey) error { return kss.db.Write(ctx, namespace, id, encryptedKey) } -func (kss *Storage) GetKey(id string) (*StoredKey, error) { - storedKeyBytes, err := kss.db.Read(namespace, id) +func (kss *Storage) GetKey(ctx context.Context, id string) (*StoredKey, error) { + storedKeyBytes, err := kss.db.Read(ctx, namespace, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key details for key: %s", id) } @@ -135,7 +135,7 @@ func (kss *Storage) GetKey(id string) (*StoredKey, error) { } // get service key - serviceKey, err := kss.getAndSetServiceKey() + serviceKey, err := kss.getAndSetServiceKey(ctx) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get service key while getting key: %s", id) } @@ -153,8 +153,8 @@ func (kss *Storage) GetKey(id string) (*StoredKey, error) { return &stored, nil } -func (kss *Storage) GetKeyDetails(id string) (*KeyDetails, error) { - stored, err := kss.GetKey(id) +func (kss *Storage) GetKeyDetails(ctx context.Context, id string) (*KeyDetails, error) { + stored, err := kss.GetKey(ctx, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key details for key: %s", id) } diff --git a/pkg/service/manifest/application.go b/pkg/service/manifest/application.go index 5cbfad1af..c89cae646 100644 --- a/pkg/service/manifest/application.go +++ b/pkg/service/manifest/application.go @@ -1,6 +1,7 @@ package manifest import ( + "context" "fmt" "strings" @@ -21,7 +22,7 @@ func (s Service) verifyApplicationJWT(did string, token keyaccess.JWT) error { // validateCredentialApplication validates the credential application's signature(s) in addition to making sure it // is a valid credential application, and complies with its corresponding manifest. it returns the ids of unfulfilled // input descriptors along with an error if validation fails. -func (s Service) validateCredentialApplication(credManifest manifest.CredentialManifest, request model.SubmitApplicationRequest) (inputDescriptorIDs []string, err error) { +func (s Service) validateCredentialApplication(ctx context.Context, credManifest manifest.CredentialManifest, request model.SubmitApplicationRequest) (inputDescriptorIDs []string, err error) { // validate the payload's signature if verificationErr := s.verifyApplicationJWT(request.ApplicantDID, request.ApplicationJWT); verificationErr != nil { err = util.LoggingErrorMsgf(err, "could not verify application<%s>'s signature", request.Application.ID) @@ -61,7 +62,7 @@ func (s Service) validateCredentialApplication(credManifest manifest.CredentialM // signature and validity checks for each credential submitted with the application for _, credentialContainer := range request.Credentials { - verificationResult, verificationErr := s.credential.VerifyCredential(credential.VerifyCredentialRequest{ + verificationResult, verificationErr := s.credential.VerifyCredential(ctx, credential.VerifyCredentialRequest{ DataIntegrityCredential: credentialContainer.Credential, CredentialJWT: credentialContainer.CredentialJWT, }) diff --git a/pkg/service/manifest/manifest.go b/pkg/service/manifest/manifest.go index bad98049a..780dc447c 100644 --- a/pkg/service/manifest/manifest.go +++ b/pkg/service/manifest/manifest.go @@ -1,6 +1,8 @@ package manifest import ( + "context" + "github.com/TBD54566975/ssi-sdk/credential/manifest" "github.com/goccy/go-json" "github.com/lestrrat-go/jwx/jwt" @@ -11,9 +13,9 @@ import ( "github.com/tbd54566975/ssi-service/pkg/service/keystore" ) -func (s Service) signManifestJWT(m CredentialManifestContainer) (*keyaccess.JWT, error) { +func (s Service) signManifestJWT(ctx context.Context, m CredentialManifestContainer) (*keyaccess.JWT, error) { issuerID := m.Manifest.Issuer.ID - gotKey, err := s.keyStore.GetKey(keystore.GetKeyRequest{ID: issuerID}) + gotKey, err := s.keyStore.GetKey(ctx, keystore.GetKeyRequest{ID: issuerID}) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key for signing manifest with key<%s>", issuerID) } diff --git a/pkg/service/manifest/response.go b/pkg/service/manifest/response.go index b7c93e4cd..6d8ac6fb9 100644 --- a/pkg/service/manifest/response.go +++ b/pkg/service/manifest/response.go @@ -21,8 +21,8 @@ const ( DenialResponse errresp.Type = "DenialResponse" ) -func (s Service) signCredentialResponseJWT(signingDID string, r CredentialResponseContainer) (*keyaccess.JWT, error) { - gotKey, err := s.keyStore.GetKey(keystore.GetKeyRequest{ID: signingDID}) +func (s Service) signCredentialResponseJWT(ctx context.Context, signingDID string, r CredentialResponseContainer) (*keyaccess.JWT, error) { + gotKey, err := s.keyStore.GetKey(ctx, keystore.GetKeyRequest{ID: signingDID}) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key for signing response with key<%s>", signingDID) } diff --git a/pkg/service/manifest/service.go b/pkg/service/manifest/service.go index 0a2aa2285..1ce606504 100644 --- a/pkg/service/manifest/service.go +++ b/pkg/service/manifest/service.go @@ -145,7 +145,7 @@ func (s Service) CreateManifest(ctx context.Context, request model.CreateManifes } // sign the manifest - manifestJWT, err := s.signManifestJWT(CredentialManifestContainer{Manifest: *m}) + manifestJWT, err := s.signManifestJWT(ctx, CredentialManifestContainer{Manifest: *m}) if err != nil { return nil, util.LoggingErrorMsg(err, "could not sign manifest") } @@ -181,11 +181,11 @@ func (s Service) VerifyManifest(request model.VerifyManifestRequest) (*model.Ver return &model.VerifyManifestResponse{Verified: true}, nil } -func (s Service) GetManifest(request model.GetManifestRequest) (*model.GetManifestResponse, error) { +func (s Service) GetManifest(ctx context.Context, request model.GetManifestRequest) (*model.GetManifestResponse, error) { logrus.Debugf("getting manifest: %s", request.ID) - gotManifest, err := s.storage.GetManifest(request.ID) + gotManifest, err := s.storage.GetManifest(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get manifest: %s", request.ID) } @@ -194,8 +194,8 @@ func (s Service) GetManifest(request model.GetManifestRequest) (*model.GetManife return &response, nil } -func (s Service) GetManifests() (*model.GetManifestsResponse, error) { - gotManifests, err := s.storage.GetManifests() +func (s Service) GetManifests(ctx context.Context) (*model.GetManifestsResponse, error) { + gotManifests, err := s.storage.GetManifests(ctx) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get manifests(s)") @@ -210,11 +210,11 @@ func (s Service) GetManifests() (*model.GetManifestsResponse, error) { return &response, nil } -func (s Service) DeleteManifest(request model.DeleteManifestRequest) error { +func (s Service) DeleteManifest(ctx context.Context, request model.DeleteManifestRequest) error { logrus.Debugf("deleting manifest: %s", request.ID) - if err := s.storage.DeleteManifest(request.ID); err != nil { + if err := s.storage.DeleteManifest(ctx, request.ID); err != nil { return util.LoggingErrorMsgf(err, "could not delete manifest with id: %s", request.ID) } @@ -235,7 +235,7 @@ type CredentialResponseContainer struct { func (s Service) ProcessApplicationSubmission(ctx context.Context, request model.SubmitApplicationRequest) (*operation.Operation, error) { // get the manifest associated with the application manifestID := request.Application.ManifestID - gotManifest, err := s.storage.GetManifest(manifestID) + gotManifest, err := s.storage.GetManifest(ctx, manifestID) applicationID := request.Application.ID if err != nil { return nil, util.LoggingErrorMsgf(err, "problem with retrieving manifest<%s> during application<%s>'s validation", manifestID, applicationID) @@ -246,7 +246,7 @@ func (s Service) ProcessApplicationSubmission(ctx context.Context, request model opID := opcredential.IDFromResponseID(applicationID) // validate the application - if unfulfilledInputDescriptorIDs, validationErr := s.validateCredentialApplication(gotManifest.Manifest, request); validationErr != nil { + if unfulfilledInputDescriptorIDs, validationErr := s.validateCredentialApplication(ctx, gotManifest.Manifest, request); validationErr != nil { resp := errresp.GetErrorResponse(validationErr) if resp.ErrorType == DenialResponse { denialResp, err := buildDenialCredentialResponse(manifestID, applicationID, resp.Err.Error(), unfulfilledInputDescriptorIDs...) @@ -298,13 +298,13 @@ func (s Service) ProcessApplicationSubmission(ctx context.Context, request model // ReviewApplication moves an application state and marks the operation associated with it as done. A credential // response is stored. func (s Service) ReviewApplication(ctx context.Context, request model.ReviewApplicationRequest) (*model.SubmitApplicationResponse, error) { - application, err := s.storage.GetApplication(request.ID) + application, err := s.storage.GetApplication(ctx, request.ID) if err != nil { return nil, errors.Wrap(err, "fetching application") } manifestID := application.ManifestID - gotManifest, err := s.storage.GetManifest(manifestID) + gotManifest, err := s.storage.GetManifest(ctx, manifestID) if err != nil { return nil, errors.Wrap(err, "fetching manifest") } @@ -325,7 +325,7 @@ func (s Service) ReviewApplication(ctx context.Context, request model.ReviewAppl credentials := credint.ContainersToInterface(creds) // sign the response before returning - responseJWT, err := s.signCredentialResponseJWT(gotManifest.Issuer, CredentialResponseContainer{ + responseJWT, err := s.signCredentialResponseJWT(ctx, gotManifest.Issuer, CredentialResponseContainer{ Response: *credResp, Credentials: credentials, }) @@ -352,11 +352,11 @@ func (s Service) ReviewApplication(ctx context.Context, request model.ReviewAppl return &m, nil } -func (s Service) GetApplication(request model.GetApplicationRequest) (*model.GetApplicationResponse, error) { +func (s Service) GetApplication(ctx context.Context, request model.GetApplicationRequest) (*model.GetApplicationResponse, error) { logrus.Debugf("getting application: %s", request.ID) - gotApp, err := s.storage.GetApplication(request.ID) + gotApp, err := s.storage.GetApplication(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get application: %s", request.ID) } @@ -365,11 +365,11 @@ func (s Service) GetApplication(request model.GetApplicationRequest) (*model.Get return &response, nil } -func (s Service) GetApplications() (*model.GetApplicationsResponse, error) { +func (s Service) GetApplications(ctx context.Context) (*model.GetApplicationsResponse, error) { logrus.Debugf("getting application(s)") - gotApps, err := s.storage.GetApplications() + gotApps, err := s.storage.GetApplications(ctx) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get application(s)") } @@ -383,22 +383,22 @@ func (s Service) GetApplications() (*model.GetApplicationsResponse, error) { return &response, nil } -func (s Service) DeleteApplication(request model.DeleteApplicationRequest) error { +func (s Service) DeleteApplication(ctx context.Context, request model.DeleteApplicationRequest) error { logrus.Debugf("deleting application: %s", request.ID) - if err := s.storage.DeleteApplication(request.ID); err != nil { + if err := s.storage.DeleteApplication(ctx, request.ID); err != nil { return util.LoggingErrorMsgf(err, "could not delete application with id: %s", request.ID) } return nil } -func (s Service) GetResponse(request model.GetResponseRequest) (*model.GetResponseResponse, error) { +func (s Service) GetResponse(ctx context.Context, request model.GetResponseRequest) (*model.GetResponseResponse, error) { logrus.Debugf("getting response: %s", request.ID) - gotResponse, err := s.storage.GetResponse(request.ID) + gotResponse, err := s.storage.GetResponse(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get response: %s", request.ID) } @@ -407,11 +407,11 @@ func (s Service) GetResponse(request model.GetResponseRequest) (*model.GetRespon return &response, nil } -func (s Service) GetResponses() (*model.GetResponsesResponse, error) { +func (s Service) GetResponses(ctx context.Context) (*model.GetResponsesResponse, error) { logrus.Debugf("getting response(s)") - gotResponses, err := s.storage.GetResponses() + gotResponses, err := s.storage.GetResponses(ctx) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get response(s)") } @@ -425,11 +425,11 @@ func (s Service) GetResponses() (*model.GetResponsesResponse, error) { return &response, nil } -func (s Service) DeleteResponse(request model.DeleteResponseRequest) error { +func (s Service) DeleteResponse(ctx context.Context, request model.DeleteResponseRequest) error { logrus.Debugf("deleting response: %s", request.ID) - if err := s.storage.DeleteResponse(request.ID); err != nil { + if err := s.storage.DeleteResponse(ctx, request.ID); err != nil { return util.LoggingErrorMsgf(err, "could not delete response with id: %s", request.ID) } diff --git a/pkg/service/manifest/storage/storage.go b/pkg/service/manifest/storage/storage.go index df589b427..e7d7865db 100644 --- a/pkg/service/manifest/storage/storage.go +++ b/pkg/service/manifest/storage/storage.go @@ -78,8 +78,8 @@ func (ms *Storage) StoreManifest(ctx context.Context, manifest StoredManifest) e return ms.db.Write(ctx, manifestNamespace, id, manifestBytes) } -func (ms *Storage) GetManifest(id string) (*StoredManifest, error) { - manifestBytes, err := ms.db.Read(manifestNamespace, id) +func (ms *Storage) GetManifest(ctx context.Context, id string) (*StoredManifest, error) { + manifestBytes, err := ms.db.Read(ctx, manifestNamespace, id) if err != nil { errMsg := fmt.Sprintf("could not get manifest: %s", id) logrus.WithError(err).Error(errMsg) @@ -100,8 +100,8 @@ func (ms *Storage) GetManifest(id string) (*StoredManifest, error) { } // GetManifests attempts to get all stored manifests. It will return those it can even if it has trouble with some. -func (ms *Storage) GetManifests() ([]StoredManifest, error) { - gotManifests, err := ms.db.ReadAll(manifestNamespace) +func (ms *Storage) GetManifests(ctx context.Context) ([]StoredManifest, error) { + gotManifests, err := ms.db.ReadAll(ctx, manifestNamespace) if err != nil { errMsg := "could not get all manifests" logrus.WithError(err).Error(errMsg) @@ -121,8 +121,8 @@ func (ms *Storage) GetManifests() ([]StoredManifest, error) { return stored, nil } -func (ms *Storage) DeleteManifest(id string) error { - if err := ms.db.Delete(manifestNamespace, id); err != nil { +func (ms *Storage) DeleteManifest(ctx context.Context, id string) error { + if err := ms.db.Delete(ctx, manifestNamespace, id); err != nil { return util.LoggingErrorMsgf(err, "could not delete manifest: %s", id) } return nil @@ -140,8 +140,8 @@ func (ms *Storage) StoreApplication(ctx context.Context, application StoredAppli return ms.db.Write(ctx, credential.ApplicationNamespace, id, applicationBytes) } -func (ms *Storage) GetApplication(id string) (*StoredApplication, error) { - applicationBytes, err := ms.db.Read(credential.ApplicationNamespace, id) +func (ms *Storage) GetApplication(ctx context.Context, id string) (*StoredApplication, error) { + applicationBytes, err := ms.db.Read(ctx, credential.ApplicationNamespace, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get application: %s", id) } @@ -156,8 +156,8 @@ func (ms *Storage) GetApplication(id string) (*StoredApplication, error) { } // GetApplications attempts to get all stored applications. It will return those it can even if it has trouble with some. -func (ms *Storage) GetApplications() ([]StoredApplication, error) { - gotApplications, err := ms.db.ReadAll(credential.ApplicationNamespace) +func (ms *Storage) GetApplications(ctx context.Context) ([]StoredApplication, error) { + gotApplications, err := ms.db.ReadAll(ctx, credential.ApplicationNamespace) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get all applications") } @@ -177,8 +177,8 @@ func (ms *Storage) GetApplications() ([]StoredApplication, error) { return stored, nil } -func (ms *Storage) DeleteApplication(id string) error { - if err := ms.db.Delete(credential.ApplicationNamespace, id); err != nil { +func (ms *Storage) DeleteApplication(ctx context.Context, id string) error { + if err := ms.db.Delete(ctx, credential.ApplicationNamespace, id); err != nil { return util.LoggingErrorMsgf(err, "could not delete application: %s", id) } return nil @@ -196,8 +196,8 @@ func (ms *Storage) StoreResponse(ctx context.Context, response StoredResponse) e return ms.db.Write(ctx, responseNamespace, id, responseBytes) } -func (ms *Storage) GetResponse(id string) (*StoredResponse, error) { - responseBytes, err := ms.db.Read(responseNamespace, id) +func (ms *Storage) GetResponse(ctx context.Context, id string) (*StoredResponse, error) { + responseBytes, err := ms.db.Read(ctx, responseNamespace, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get response: %s", id) } @@ -212,8 +212,8 @@ func (ms *Storage) GetResponse(id string) (*StoredResponse, error) { } // GetResponses attempts to get all stored responses. It will return those it can even if it has trouble with some. -func (ms *Storage) GetResponses() ([]StoredResponse, error) { - gotResponses, err := ms.db.ReadAll(responseNamespace) +func (ms *Storage) GetResponses(ctx context.Context) ([]StoredResponse, error) { + gotResponses, err := ms.db.ReadAll(ctx, responseNamespace) if err != nil { return nil, util.LoggingErrorMsg(err, "could not get all responses") } @@ -233,8 +233,8 @@ func (ms *Storage) GetResponses() ([]StoredResponse, error) { return stored, nil } -func (ms *Storage) DeleteResponse(id string) error { - if err := ms.db.Delete(responseNamespace, id); err != nil { +func (ms *Storage) DeleteResponse(ctx context.Context, id string) error { + if err := ms.db.Delete(ctx, responseNamespace, id); err != nil { return util.LoggingErrorMsgf(err, "could not delete response: %s", id) } return nil @@ -256,7 +256,7 @@ func (ms *Storage) ReviewApplication(ctx context.Context, id string, approved bo if approved { m["status"] = opsubmission.StatusApproved } - if _, err := ms.db.Update(credential.ApplicationNamespace, id, m); err != nil { + if _, err := ms.db.Update(ctx, credential.ApplicationNamespace, id, m); err != nil { return nil, nil, errors.Wrap(err, "updating application") } @@ -265,6 +265,7 @@ func (ms *Storage) ReviewApplication(ctx context.Context, id string, approved bo } responseData, operationData, err := ms.db.UpdateValueAndOperation( + ctx, responseNamespace, response.ID, storage.NewUpdater(m), diff --git a/pkg/service/operation/service.go b/pkg/service/operation/service.go index 5fe23e3b3..813ec2d2a 100644 --- a/pkg/service/operation/service.go +++ b/pkg/service/operation/service.go @@ -1,6 +1,7 @@ package operation import ( + "context" "fmt" "strings" @@ -42,12 +43,12 @@ func (s Service) Status() framework.Status { return framework.Status{Status: framework.StatusReady} } -func (s Service) GetOperations(request GetOperationsRequest) (*GetOperationsResponse, error) { +func (s Service) GetOperations(ctx context.Context, request GetOperationsRequest) (*GetOperationsResponse, error) { if err := request.Validate(); err != nil { return nil, errors.Wrap(err, "invalid request") } - ops, err := s.storage.GetOperations(request.Parent, request.Filter) + ops, err := s.storage.GetOperations(ctx, request.Parent, request.Filter) if err != nil { return nil, errors.Wrap(err, "fetching ops from storage") } @@ -102,24 +103,24 @@ func ServiceModel(op opstorage.StoredOperation) (*Operation, error) { return newOp, nil } -func (s Service) GetOperation(request GetOperationRequest) (*Operation, error) { +func (s Service) GetOperation(ctx context.Context, request GetOperationRequest) (*Operation, error) { if err := request.Validate(); err != nil { return nil, errors.Wrap(err, "invalid request") } - storedOp, err := s.storage.GetOperation(request.ID) + storedOp, err := s.storage.GetOperation(ctx, request.ID) if err != nil { return nil, errors.Wrap(err, "fetching from storage") } return ServiceModel(storedOp) } -func (s Service) CancelOperation(request CancelOperationRequest) (*Operation, error) { +func (s Service) CancelOperation(ctx context.Context, request CancelOperationRequest) (*Operation, error) { if err := request.Validate(); err != nil { return nil, errors.Wrap(err, "invalid request") } - storedOp, err := s.storage.CancelOperation(request.ID) + storedOp, err := s.storage.CancelOperation(ctx, request.ID) if err != nil { return nil, errors.Wrap(err, "marking as done") } diff --git a/pkg/service/operation/storage.go b/pkg/service/operation/storage.go index c1875aecb..0f275f064 100644 --- a/pkg/service/operation/storage.go +++ b/pkg/service/operation/storage.go @@ -24,12 +24,13 @@ type Storage struct { db storage.ServiceStorage } -func (b Storage) CancelOperation(id string) (*opstorage.StoredOperation, error) { +func (b Storage) CancelOperation(ctx context.Context, id string) (*opstorage.StoredOperation, error) { var opData []byte var err error switch { case strings.HasPrefix(id, submission.ParentResource): _, opData, err = b.db.UpdateValueAndOperation( + ctx, submission.Namespace, opstorage.StatusObjectID(id), storage.NewUpdater(map[string]any{ "status": submission.StatusCancelled, "reason": cancelledReason, @@ -41,6 +42,7 @@ func (b Storage) CancelOperation(id string) (*opstorage.StoredOperation, error) }) case strings.HasPrefix(id, credential.ParentResource): _, opData, err = b.db.UpdateValueAndOperation( + ctx, credential.ApplicationNamespace, opstorage.StatusObjectID(id), storage.NewUpdater(map[string]any{ "status": credential.StatusCancelled, "reason": cancelledReason, @@ -80,9 +82,9 @@ func (b Storage) StoreOperation(ctx context.Context, op opstorage.StoredOperatio return nil } -func (b Storage) GetOperation(id string) (opstorage.StoredOperation, error) { +func (b Storage) GetOperation(ctx context.Context, id string) (opstorage.StoredOperation, error) { var stored opstorage.StoredOperation - jsonBytes, err := b.db.Read(namespace.FromID(id), id) + jsonBytes, err := b.db.Read(ctx, namespace.FromID(id), id) if err != nil { return stored, util.LoggingErrorMsgf(err, "reading operation with id: %s", id) } @@ -95,8 +97,8 @@ func (b Storage) GetOperation(id string) (opstorage.StoredOperation, error) { return stored, nil } -func (b Storage) GetOperations(parent string, filter filtering.Filter) ([]opstorage.StoredOperation, error) { - operations, err := b.db.ReadAll(namespace.FromParent(parent)) +func (b Storage) GetOperations(ctx context.Context, parent string, filter filtering.Filter) ([]opstorage.StoredOperation, error) { + operations, err := b.db.ReadAll(ctx, namespace.FromParent(parent)) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get all operations") } @@ -120,8 +122,8 @@ func (b Storage) GetOperations(parent string, filter filtering.Filter) ([]opstor return stored, nil } -func (b Storage) DeleteOperation(id string) error { - if err := b.db.Delete(namespace.FromID(id), id); err != nil { +func (b Storage) DeleteOperation(ctx context.Context, id string) error { + if err := b.db.Delete(ctx, namespace.FromID(id), id); err != nil { return util.LoggingErrorMsgf(err, "deleting operation: %s", id) } return nil diff --git a/pkg/service/operation/storage_test.go b/pkg/service/operation/storage_test.go index 7d0dee4a3..bb7d74a8b 100644 --- a/pkg/service/operation/storage_test.go +++ b/pkg/service/operation/storage_test.go @@ -1,6 +1,7 @@ package operation import ( + "context" "os" "testing" @@ -33,7 +34,7 @@ func TestStorage_CancelOperation(t *testing.T) { s := setupTestDB(t) data, err := json.Marshal(manifeststg.StoredApplication{}) require.NoError(t, err) - require.NoError(t, s.Write(credential.ApplicationNamespace, "hello", data)) + require.NoError(t, s.Write(context.Background(), credential.ApplicationNamespace, "hello", data)) type fields struct { db storage.ServiceStorage @@ -92,12 +93,12 @@ func TestStorage_CancelOperation(t *testing.T) { Done: tt.done, }) require.NoError(t, err) - require.NoError(t, s.Write(namespace.FromParent("credentials/responses"), "credentials/responses/hello", opData)) + require.NoError(t, s.Write(context.Background(), namespace.FromParent("credentials/responses"), "credentials/responses/hello", opData)) b := Storage{ db: tt.fields.db, } - got, err := b.CancelOperation(tt.args.id) + got, err := b.CancelOperation(context.Background(), tt.args.id) if (err != nil) != tt.wantErr { t.Errorf("CancelOperation() error = %v, wantErr %v", err, tt.wantErr) return diff --git a/pkg/service/presentation/service.go b/pkg/service/presentation/service.go index d6dbce082..597923375 100644 --- a/pkg/service/presentation/service.go +++ b/pkg/service/presentation/service.go @@ -106,10 +106,10 @@ func (s Service) CreatePresentationDefinition(ctx context.Context, request model }, nil } -func (s Service) GetPresentationDefinition(request model.GetPresentationDefinitionRequest) (*model.GetPresentationDefinitionResponse, error) { +func (s Service) GetPresentationDefinition(ctx context.Context, request model.GetPresentationDefinitionRequest) (*model.GetPresentationDefinitionResponse, error) { logrus.Debugf("getting presentation definition: %s", request.ID) - storedPresentation, err := s.storage.GetPresentation(request.ID) + storedPresentation, err := s.storage.GetPresentation(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "error getting presentation definition: %s", request.ID) } @@ -119,10 +119,10 @@ func (s Service) GetPresentationDefinition(request model.GetPresentationDefiniti return &model.GetPresentationDefinitionResponse{ID: storedPresentation.ID, PresentationDefinition: storedPresentation.PresentationDefinition}, nil } -func (s Service) DeletePresentationDefinition(request model.DeletePresentationDefinitionRequest) error { +func (s Service) DeletePresentationDefinition(ctx context.Context, request model.DeletePresentationDefinitionRequest) error { logrus.Debugf("deleting presentation definition: %s", request.ID) - if err := s.storage.DeletePresentation(request.ID); err != nil { + if err := s.storage.DeletePresentation(ctx, request.ID); err != nil { return util.LoggingNewErrorf("could not delete presentation definition with id: %s", request.ID) } @@ -148,11 +148,11 @@ func (s Service) CreateSubmission(ctx context.Context, request model.CreateSubmi return nil, errors.Wrap(err, "verifying token from did") } - if _, err := s.storage.GetSubmission(request.Submission.ID); !errors.Is(err, presentationstorage.ErrSubmissionNotFound) { + if _, err := s.storage.GetSubmission(ctx, request.Submission.ID); !errors.Is(err, presentationstorage.ErrSubmissionNotFound) { return nil, errors.Errorf("submission with id %s already present", request.Submission.ID) } - definition, err := s.storage.GetPresentation(request.Submission.DefinitionID) + definition, err := s.storage.GetPresentation(ctx, request.Submission.DefinitionID) if err != nil { return nil, errors.Wrap(err, "getting presentation definition") } @@ -162,12 +162,12 @@ func (s Service) CreateSubmission(ctx context.Context, request model.CreateSubmi return nil, errors.Errorf("invalid credential %+v", cred) } if cred.CredentialJWT != nil { - if err := s.verifier.VerifyJWTCredential(*cred.CredentialJWT); err != nil { + if err := s.verifier.VerifyJWTCredential(ctx, *cred.CredentialJWT); err != nil { return nil, errors.Wrapf(err, "verifying jwt credential %s", cred.CredentialJWT) } } else { if cred.HasDataIntegrityCredential() { - if err := s.verifier.VerifyDataIntegrityCredential(*cred.Credential); err != nil { + if err := s.verifier.VerifyDataIntegrityCredential(ctx, *cred.Credential); err != nil { return nil, errors.Wrapf(err, "verifying data integrity credential %+v", cred.Credential) } } @@ -203,10 +203,10 @@ func (s Service) CreateSubmission(ctx context.Context, request model.CreateSubmi }, nil } -func (s Service) GetSubmission(request model.GetSubmissionRequest) (*model.GetSubmissionResponse, error) { +func (s Service) GetSubmission(ctx context.Context, request model.GetSubmissionRequest) (*model.GetSubmissionResponse, error) { logrus.Debugf("getting presentation submission: %s", request.ID) - storedSubmission, err := s.storage.GetSubmission(request.ID) + storedSubmission, err := s.storage.GetSubmission(ctx, request.ID) if err != nil { return nil, errors.Wrap(err, "fetching from storage") } @@ -215,10 +215,10 @@ func (s Service) GetSubmission(request model.GetSubmissionRequest) (*model.GetSu }, nil } -func (s Service) ListSubmissions(request model.ListSubmissionRequest) (*model.ListSubmissionResponse, error) { +func (s Service) ListSubmissions(ctx context.Context, request model.ListSubmissionRequest) (*model.ListSubmissionResponse, error) { logrus.Debug("listing presentation submissions") - subs, err := s.storage.ListSubmissions(request.Filter) + subs, err := s.storage.ListSubmissions(ctx, request.Filter) if err != nil { return nil, errors.Wrap(err, "fetching submissions from storage") } @@ -232,12 +232,12 @@ func (s Service) ListSubmissions(request model.ListSubmissionRequest) (*model.Li return resp, nil } -func (s Service) ReviewSubmission(request model.ReviewSubmissionRequest) (*model.Submission, error) { +func (s Service) ReviewSubmission(ctx context.Context, request model.ReviewSubmissionRequest) (*model.Submission, error) { if err := request.Validate(); err != nil { return nil, errors.Wrap(err, "invalid request") } - updatedSubmission, _, err := s.storage.UpdateSubmission(request.ID, request.Approved, request.Reason, submission.IDFromSubmissionID(request.ID)) + updatedSubmission, _, err := s.storage.UpdateSubmission(ctx, request.ID, request.Approved, request.Reason, submission.IDFromSubmissionID(request.ID)) if err != nil { return nil, errors.Wrap(err, "updating submission") } diff --git a/pkg/service/presentation/storage.go b/pkg/service/presentation/storage.go index 1a42d7e46..0ea7e1bfb 100644 --- a/pkg/service/presentation/storage.go +++ b/pkg/service/presentation/storage.go @@ -30,7 +30,7 @@ type Storage struct { db storage.ServiceStorage } -func (ps Storage) UpdateSubmission(id string, approved bool, reason string, opID string) (prestorage.StoredSubmission, opstorage.StoredOperation, error) { +func (ps Storage) UpdateSubmission(ctx context.Context, id string, approved bool, reason string, opID string) (prestorage.StoredSubmission, opstorage.StoredOperation, error) { m := map[string]any{ "status": opsubmission.StatusDenied, "reason": reason, @@ -39,6 +39,7 @@ func (ps Storage) UpdateSubmission(id string, approved bool, reason string, opID m["status"] = opsubmission.StatusApproved } submissionData, operationData, err := ps.db.UpdateValueAndOperation( + ctx, opsubmission.Namespace, id, storage.NewUpdater(m), @@ -64,8 +65,8 @@ func (ps Storage) UpdateSubmission(id string, approved bool, reason string, opID return s, op, nil } -func (ps *Storage) ListSubmissions(filter filtering.Filter) ([]prestorage.StoredSubmission, error) { - allData, err := ps.db.ReadAll(opsubmission.Namespace) +func (ps *Storage) ListSubmissions(ctx context.Context, filter filtering.Filter) ([]prestorage.StoredSubmission, error) { + allData, err := ps.db.ReadAll(ctx, opsubmission.Namespace) if err != nil { return nil, errors.Wrap(err, "reading all data") } @@ -116,8 +117,8 @@ func (ps *Storage) StorePresentation(ctx context.Context, presentation StoredPre return ps.db.Write(ctx, presentationDefinitionNamespace, id, jsonBytes) } -func (ps *Storage) GetPresentation(id string) (*StoredPresentation, error) { - jsonBytes, err := ps.db.Read(presentationDefinitionNamespace, id) +func (ps *Storage) GetPresentation(ctx context.Context, id string) (*StoredPresentation, error) { + jsonBytes, err := ps.db.Read(ctx, presentationDefinitionNamespace, id) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get presentation definition: %s", id) } @@ -131,8 +132,8 @@ func (ps *Storage) GetPresentation(id string) (*StoredPresentation, error) { return &stored, nil } -func (ps *Storage) DeletePresentation(id string) error { - if err := ps.db.Delete(presentationDefinitionNamespace, id); err != nil { +func (ps *Storage) DeletePresentation(ctx context.Context, id string) error { + if err := ps.db.Delete(ctx, presentationDefinitionNamespace, id); err != nil { return util.LoggingNewErrorf("could not delete presentation definition: %s", id) } return nil @@ -152,8 +153,8 @@ func (ps Storage) StoreSubmission(ctx context.Context, s prestorage.StoredSubmis return ps.db.Write(ctx, opsubmission.Namespace, id, jsonBytes) } -func (ps *Storage) GetSubmission(id string) (*prestorage.StoredSubmission, error) { - jsonBytes, err := ps.db.Read(opsubmission.Namespace, id) +func (ps *Storage) GetSubmission(ctx context.Context, id string) (*prestorage.StoredSubmission, error) { + jsonBytes, err := ps.db.Read(ctx, opsubmission.Namespace, id) if err != nil { return nil, util.LoggingNewErrorf("could not get submission definition: %s", id) } diff --git a/pkg/service/schema/service.go b/pkg/service/schema/service.go index aeb0a145e..474ff6d47 100644 --- a/pkg/service/schema/service.go +++ b/pkg/service/schema/service.go @@ -114,7 +114,7 @@ func (s Service) CreateSchema(ctx context.Context, request CreateSchemaRequest) // sign the schema if request.Sign { - signedSchema, err := s.signSchemaJWT(request.Author, schemaValue) + signedSchema, err := s.signSchemaJWT(ctx, request.Author, schemaValue) if err != nil { return nil, util.LoggingError(err) } @@ -143,8 +143,8 @@ func prepareJSONSchema(id, name string, s schema.JSONSchema) schema.JSONSchema { } // signSchemaJWT signs a schema after the key associated with the provided author for the schema as a JWT -func (s Service) signSchemaJWT(author string, schema schema.VCJSONSchema) (*keyaccess.JWT, error) { - gotKey, err := s.keyStore.GetKey(keystore.GetKeyRequest{ID: author}) +func (s Service) signSchemaJWT(ctx context.Context, author string, schema schema.VCJSONSchema) (*keyaccess.JWT, error) { + gotKey, err := s.keyStore.GetKey(ctx, keystore.GetKeyRequest{ID: author}) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get key for signing schema for author<%s>", author) } @@ -216,11 +216,11 @@ func (s Service) verifySchemaJWT(token keyaccess.JWT) (*schema.VCJSONSchema, err return &parsedSchema, nil } -func (s Service) GetSchemas() (*GetSchemasResponse, error) { +func (s Service) GetSchemas(ctx context.Context) (*GetSchemasResponse, error) { logrus.Debug("getting all schema") - storedSchemas, err := s.storage.GetSchemas() + storedSchemas, err := s.storage.GetSchemas(ctx) if err != nil { return nil, util.LoggingErrorMsg(err, "error getting schemas") } @@ -236,12 +236,12 @@ func (s Service) GetSchemas() (*GetSchemasResponse, error) { return &GetSchemasResponse{Schemas: schemas}, nil } -func (s Service) GetSchema(request GetSchemaRequest) (*GetSchemaResponse, error) { +func (s Service) GetSchema(ctx context.Context, request GetSchemaRequest) (*GetSchemaResponse, error) { logrus.Debugf("getting schema: %s", request.ID) // TODO(gabe) support external schema resolution https://github.com/TBD54566975/ssi-service/issues/125 - gotSchema, err := s.storage.GetSchema(request.ID) + gotSchema, err := s.storage.GetSchema(ctx, request.ID) if err != nil { return nil, util.LoggingErrorMsgf(err, "error getting schema: %s", request.ID) } @@ -251,19 +251,19 @@ func (s Service) GetSchema(request GetSchemaRequest) (*GetSchemaResponse, error) return &GetSchemaResponse{Schema: gotSchema.Schema, SchemaJWT: gotSchema.SchemaJWT}, nil } -func (s Service) Resolve(id string) (*schema.VCJSONSchema, error) { - schemaResponse, err := s.GetSchema(GetSchemaRequest{ID: id}) +func (s Service) Resolve(ctx context.Context, id string) (*schema.VCJSONSchema, error) { + schemaResponse, err := s.GetSchema(ctx, GetSchemaRequest{ID: id}) if err != nil { return nil, util.LoggingErrorMsgf(err, "could not get schema for id<%s>", id) } return &schemaResponse.Schema, nil } -func (s Service) DeleteSchema(request DeleteSchemaRequest) error { +func (s Service) DeleteSchema(ctx context.Context, request DeleteSchemaRequest) error { logrus.Debugf("deleting schema: %s", request.ID) - if err := s.storage.DeleteSchema(request.ID); err != nil { + if err := s.storage.DeleteSchema(ctx, request.ID); err != nil { return util.LoggingErrorMsgf(err, "could not delete schema with id: %s", request.ID) } diff --git a/pkg/service/schema/storage.go b/pkg/service/schema/storage.go index 8314c362a..65eaf6c4d 100644 --- a/pkg/service/schema/storage.go +++ b/pkg/service/schema/storage.go @@ -51,8 +51,8 @@ func (ss *Storage) StoreSchema(ctx context.Context, schema StoredSchema) error { return ss.db.Write(ctx, namespace, id, schemaBytes) } -func (ss *Storage) GetSchema(id string) (*StoredSchema, error) { - schemaBytes, err := ss.db.Read(namespace, id) +func (ss *Storage) GetSchema(ctx context.Context, id string) (*StoredSchema, error) { + schemaBytes, err := ss.db.Read(ctx, namespace, id) if err != nil { errMsg := fmt.Sprintf("could not get schema: %s", id) logrus.WithError(err).Error(errMsg) @@ -73,8 +73,8 @@ func (ss *Storage) GetSchema(id string) (*StoredSchema, error) { } // GetSchemas attempts to get all stored schemas. It will return those it can even if it has trouble with some. -func (ss *Storage) GetSchemas() ([]StoredSchema, error) { - gotSchemas, err := ss.db.ReadAll(namespace) +func (ss *Storage) GetSchemas(ctx context.Context) ([]StoredSchema, error) { + gotSchemas, err := ss.db.ReadAll(ctx, namespace) if err != nil { errMsg := "could not get all schemas" logrus.WithError(err).Error(errMsg) @@ -94,8 +94,8 @@ func (ss *Storage) GetSchemas() ([]StoredSchema, error) { return stored, nil } -func (ss *Storage) DeleteSchema(id string) error { - if err := ss.db.Delete(namespace, id); err != nil { +func (ss *Storage) DeleteSchema(ctx context.Context, id string) error { + if err := ss.db.Delete(ctx, namespace, id); err != nil { errMsg := fmt.Sprintf("could not delete schema: %s", id) logrus.WithError(err).Error(errMsg) return errors.Wrapf(err, errMsg) diff --git a/pkg/storage/bolt.go b/pkg/storage/bolt.go index f3415c1fd..e6d8863de 100644 --- a/pkg/storage/bolt.go +++ b/pkg/storage/bolt.go @@ -86,7 +86,7 @@ func (b *BoltDB) Write(ctx context.Context, namespace string, key string, value }) } -func (b *BoltDB) Read(namespace, key string) ([]byte, error) { +func (b *BoltDB) Read(ctx context.Context, namespace, key string) ([]byte, error) { var result []byte err := b.db.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(namespace)) @@ -101,7 +101,7 @@ func (b *BoltDB) Read(namespace, key string) ([]byte, error) { } // ReadPrefix does a prefix query within a namespace. -func (b *BoltDB) ReadPrefix(namespace, prefix string) (map[string][]byte, error) { +func (b *BoltDB) ReadPrefix(ctx context.Context, namespace, prefix string) (map[string][]byte, error) { result := make(map[string][]byte) err := b.db.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(namespace)) @@ -120,7 +120,7 @@ func (b *BoltDB) ReadPrefix(namespace, prefix string) (map[string][]byte, error) return result, err } -func (b *BoltDB) ReadAll(namespace string) (map[string][]byte, error) { +func (b *BoltDB) ReadAll(ctx context.Context, namespace string) (map[string][]byte, error) { result := make(map[string][]byte) err := b.db.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(namespace)) @@ -137,7 +137,7 @@ func (b *BoltDB) ReadAll(namespace string) (map[string][]byte, error) { return result, err } -func (b *BoltDB) ReadAllKeys(namespace string) ([]string, error) { +func (b *BoltDB) ReadAllKeys(ctx context.Context, namespace string) ([]string, error) { var result []string err := b.db.View(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(namespace)) @@ -153,7 +153,7 @@ func (b *BoltDB) ReadAllKeys(namespace string) ([]string, error) { return result, err } -func (b *BoltDB) Delete(namespace, key string) error { +func (b *BoltDB) Delete(ctx context.Context, namespace, key string) error { return b.db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(namespace)) if bucket == nil { @@ -163,7 +163,7 @@ func (b *BoltDB) Delete(namespace, key string) error { }) } -func (b *BoltDB) DeleteNamespace(namespace string) error { +func (b *BoltDB) DeleteNamespace(ctx context.Context, namespace string) error { return b.db.Update(func(tx *bolt.Tx) error { if err := tx.DeleteBucket([]byte(namespace)); err != nil { return util.LoggingErrorMsgf(err, "could not delete namespace<%s>", namespace) @@ -221,7 +221,7 @@ type ResponseSettingUpdater interface { // UpdateValueAndOperation updates the value stored in (namespace,key) with the new values specified in the map. // The updated value is then stored inside the (opNamespace, opKey), and the "done" value is set to true. -func (b *BoltDB) UpdateValueAndOperation(namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) { +func (b *BoltDB) UpdateValueAndOperation(ctx context.Context, namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) { err = b.db.Update(func(tx *bolt.Tx) error { if err := updateTxFn(namespace, key, updater, &first)(tx); err != nil { return err @@ -235,7 +235,7 @@ func (b *BoltDB) UpdateValueAndOperation(namespace, key string, updater Updater, return first, op, err } -func (b *BoltDB) Update(namespace string, key string, values map[string]any) ([]byte, error) { +func (b *BoltDB) Update(ctx context.Context, namespace string, key string, values map[string]any) ([]byte, error) { var updatedData []byte err := b.db.Update(updateTxFn(namespace, key, NewUpdater(values), &updatedData)) return updatedData, err diff --git a/pkg/storage/db_test.go b/pkg/storage/db_test.go index 855b54f47..75546af41 100644 --- a/pkg/storage/db_test.go +++ b/pkg/storage/db_test.go @@ -1,6 +1,7 @@ package storage import ( + "context" "fmt" "os" "testing" @@ -61,11 +62,11 @@ func TestDB(t *testing.T) { p1Bytes, err := json.Marshal(players1) assert.NoError(t, err) - err = db.Write(namespace, team1, p1Bytes) + err = db.Write(context.Background(), namespace, team1, p1Bytes) assert.NoError(t, err) // get it back - gotPlayers1, err := db.Read(namespace, team1) + gotPlayers1, err := db.Read(context.Background(), namespace, team1) assert.NoError(t, err) var players1Result []string @@ -74,12 +75,12 @@ func TestDB(t *testing.T) { assert.EqualValues(t, players1, players1Result) // get a value from a namespace that doesn't exist - res, err := db.Read("bad", "worse") + res, err := db.Read(context.Background(), "bad", "worse") assert.NoError(t, err) assert.Empty(t, res) // get a value that doesn't exist in the namespace - noValue, err := db.Read(namespace, "Porsche") + noValue, err := db.Read(context.Background(), namespace, "Porsche") assert.NoError(t, err) assert.Empty(t, noValue) @@ -89,11 +90,11 @@ func TestDB(t *testing.T) { p2Bytes, err := json.Marshal(players2) assert.NoError(t, err) - err = db.Write(namespace, team2, p2Bytes) + err = db.Write(context.Background(), namespace, team2, p2Bytes) assert.NoError(t, err) // get all values from the namespace - gotAll, err := db.ReadAll(namespace) + gotAll, err := db.ReadAll(context.Background(), namespace) assert.NoError(t, err) assert.True(t, len(gotAll) == 2) @@ -104,27 +105,27 @@ func TestDB(t *testing.T) { assert.True(t, gotMcLaren) // delete value in the namespace - err = db.Delete(namespace, team2) + err = db.Delete(context.Background(), namespace, team2) assert.NoError(t, err) - gotPlayers2, err := db.Read(namespace, team2) + gotPlayers2, err := db.Read(context.Background(), namespace, team2) assert.NoError(t, err) assert.Empty(t, gotPlayers2) // delete value in a namespace that doesn't exist - err = db.Delete("bad", team2) + err = db.Delete(context.Background(), "bad", team2) assert.Error(t, err) assert.Contains(t, err.Error(), "namespace does not exist") // delete a namespace that doesn't exist - err = db.DeleteNamespace("bad") + err = db.DeleteNamespace(context.Background(), "bad") assert.Contains(t, err.Error(), "could not delete namespace") // delete namespace - err = db.DeleteNamespace(namespace) + err = db.DeleteNamespace(context.Background(), namespace) assert.NoError(t, err) - res, err = db.Read(namespace, team1) + res, err = db.Read(context.Background(), namespace, team1) assert.NoError(t, err) assert.Empty(t, res) } @@ -139,19 +140,19 @@ func TestDBPrefixAndKeys(t *testing.T) { // set up prefix read test dummyData := []byte("dummy") - err := db.Write(namespace, "bitcoin-testnet", dummyData) + err := db.Write(context.Background(), namespace, "bitcoin-testnet", dummyData) assert.NoError(t, err) - err = db.Write(namespace, "bitcoin-mainnet", dummyData) + err = db.Write(context.Background(), namespace, "bitcoin-mainnet", dummyData) assert.NoError(t, err) - err = db.Write(namespace, "tezos-testnet", dummyData) + err = db.Write(context.Background(), namespace, "tezos-testnet", dummyData) assert.NoError(t, err) - err = db.Write(namespace, "tezos-mainnet", dummyData) + err = db.Write(context.Background(), namespace, "tezos-mainnet", dummyData) assert.NoError(t, err) - prefixValues, err := db.ReadPrefix(namespace, "bitcoin") + prefixValues, err := db.ReadPrefix(context.Background(), namespace, "bitcoin") assert.NoError(t, err) assert.Len(t, prefixValues, 2) @@ -163,7 +164,7 @@ func TestDBPrefixAndKeys(t *testing.T) { assert.Contains(t, keys, "bitcoin-mainnet") // read all keys - allKeys, err := db.ReadAllKeys(namespace) + allKeys, err := db.ReadAllKeys(context.Background(), namespace) assert.NoError(t, err) assert.NotEmpty(t, allKeys) @@ -193,7 +194,7 @@ func TestDB_Update(t *testing.T) { Reason: "", }) require.NoError(t, err) - require.NoError(t, db.Write(namespace, "123", data)) + require.NoError(t, db.Write(context.Background(), namespace, "123", data)) type args struct { key string @@ -235,7 +236,7 @@ func TestDB_Update(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - data, err = db.Update(namespace, tt.args.key, tt.args.values) + data, err = db.Update(context.Background(), namespace, tt.args.key, tt.args.values) if !tt.expectedError(t, err) { return } @@ -268,14 +269,14 @@ func TestDB_UpdatedSubmissionAndOperationTxFn(t *testing.T) { Reason: "", }) require.NoError(t, err) - require.NoError(t, db.Write(namespace, "123", data)) + require.NoError(t, db.Write(context.Background(), namespace, "123", data)) data, err = json.Marshal(operation{ Done: false, Response: nil, }) require.NoError(t, err) - require.NoError(t, db.Write(opNamespace, "op123", data)) + require.NoError(t, db.Write(context.Background(), opNamespace, "op123", data)) type args struct { namespace string @@ -346,7 +347,7 @@ func TestDB_UpdatedSubmissionAndOperationTxFn(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - gotFirstData, gotOpData, err := db.UpdateValueAndOperation(tt.args.namespace, tt.args.key, tt.args.updater, tt.args.opNamespace, tt.args.opKey, testOpUpdater{ + gotFirstData, gotOpData, err := db.UpdateValueAndOperation(context.Background(), tt.args.namespace, tt.args.key, tt.args.updater, tt.args.opNamespace, tt.args.opKey, testOpUpdater{ NewUpdater(map[string]any{ "done": true, }), diff --git a/pkg/storage/redis.go b/pkg/storage/redis.go index a4a7a182f..b0dd9efbf 100644 --- a/pkg/storage/redis.go +++ b/pkg/storage/redis.go @@ -24,8 +24,7 @@ func init() { } type RedisDB struct { - db *goredislib.Client - ctx context.Context + db *goredislib.Client } func (b *RedisDB) Init(i interface{}) error { @@ -37,7 +36,6 @@ func (b *RedisDB) Init(i interface{}) error { }) b.db = client - b.ctx = context.Background() return nil } @@ -47,7 +45,7 @@ func (b *RedisDB) URI() string { } func (b *RedisDB) IsOpen() bool { - pong, err := b.db.Ping(b.ctx).Result() + pong, err := b.db.Ping(context.Background()).Result() if err != nil { logrus.Error(err) return false @@ -70,7 +68,7 @@ func (b *RedisDB) Write(ctx context.Context, namespace, key string, value []byte return b.db.Set(ctx, nameSpaceKey, value, 0).Err() } -func (b *RedisDB) WriteMany(namespaces, keys []string, values [][]byte) error { +func (b *RedisDB) WriteMany(ctx context.Context, namespaces, keys []string, values [][]byte) error { if len(namespaces) != len(keys) && len(namespaces) != len(values) { return errors.New("namespaces, keys, and values, are not of equal length") } @@ -80,12 +78,12 @@ func (b *RedisDB) WriteMany(namespaces, keys []string, values [][]byte) error { nameSpaceKeys = append(nameSpaceKeys, getRedisKey(namespaces[i], keys[i])) } - return b.db.MSet(b.ctx, nameSpaceKeys, values, 0).Err() + return b.db.MSet(ctx, nameSpaceKeys, values, 0).Err() } -func (b *RedisDB) Read(namespace, key string) ([]byte, error) { +func (b *RedisDB) Read(ctx context.Context, namespace, key string) ([]byte, error) { nameSpaceKey := getRedisKey(namespace, key) - res, err := b.db.Get(b.ctx, nameSpaceKey).Bytes() + res, err := b.db.Get(ctx, nameSpaceKey).Bytes() // Nil reply returned by Redis when key does not exist. if errors.Is(err, goredislib.Nil) { @@ -95,35 +93,35 @@ func (b *RedisDB) Read(namespace, key string) ([]byte, error) { return res, err } -func (b *RedisDB) ReadPrefix(namespace, prefix string) (map[string][]byte, error) { +func (b *RedisDB) ReadPrefix(ctx context.Context, namespace, prefix string) (map[string][]byte, error) { namespacePrefix := getRedisKey(namespace, prefix) - keys, err := readAllKeys(namespacePrefix, b) + keys, err := readAllKeys(ctx, namespacePrefix, b) if err != nil { return nil, errors.Wrap(err, "read all keys") } - return readAll(keys, b) + return readAll(ctx, keys, b) } -func (b *RedisDB) ReadAll(namespace string) (map[string][]byte, error) { - keys, err := readAllKeys(namespace, b) +func (b *RedisDB) ReadAll(ctx context.Context, namespace string) (map[string][]byte, error) { + keys, err := readAllKeys(ctx, namespace, b) if err != nil { return nil, errors.Wrap(err, "read all keys") } - return readAll(keys, b) + return readAll(ctx, keys, b) } // TODO: This potentially could dangerous as it might run out of memory as we populate result -func readAll(keys []string, b *RedisDB) (map[string][]byte, error) { +func readAll(ctx context.Context, keys []string, b *RedisDB) (map[string][]byte, error) { result := make(map[string][]byte, len(keys)) if len(keys) == 0 { return nil, nil } - values, err := b.db.MGet(b.ctx, keys...).Result() + values, err := b.db.MGet(ctx, keys...).Result() if err != nil { return nil, errors.Wrap(err, "getting multiple keys") } @@ -143,8 +141,8 @@ func readAll(keys []string, b *RedisDB) (map[string][]byte, error) { return result, nil } -func (b *RedisDB) ReadAllKeys(namespace string) ([]string, error) { - keys, err := readAllKeys(namespace, b) +func (b *RedisDB) ReadAllKeys(ctx context.Context, namespace string) ([]string, error) { + keys, err := readAllKeys(ctx, namespace, b) if err != nil { return nil, err } @@ -163,13 +161,13 @@ func (b *RedisDB) ReadAllKeys(namespace string) ([]string, error) { } // TODO: This potentially could dangerous as it might run out of memory as we populate allKeys -func readAllKeys(namespace string, b *RedisDB) ([]string, error) { +func readAllKeys(ctx context.Context, namespace string, b *RedisDB) ([]string, error) { var cursor uint64 var allKeys []string for { - keys, nextCursor, err := b.db.Scan(b.ctx, cursor, namespace+"*", RedisScanBatchSize).Result() + keys, nextCursor, err := b.db.Scan(ctx, cursor, namespace+"*", RedisScanBatchSize).Result() if err != nil { return nil, errors.Wrap(err, "scan error") } @@ -186,14 +184,14 @@ func readAllKeys(namespace string, b *RedisDB) ([]string, error) { return allKeys, nil } -func (b *RedisDB) Delete(namespace, key string) error { +func (b *RedisDB) Delete(ctx context.Context, namespace, key string) error { nameSpaceKey := getRedisKey(namespace, key) - if !namespaceExists(namespace, b) { + if !namespaceExists(ctx, namespace, b) { return errors.Errorf("namespace<%s> does not exist", namespace) } - res, err := b.db.GetDel(b.ctx, nameSpaceKey).Result() + res, err := b.db.GetDel(ctx, nameSpaceKey).Result() if res == "" { return errors.Wrapf(err, "key<%s> and namespace<%s> does not exist", key, namespace) } @@ -202,8 +200,8 @@ func (b *RedisDB) Delete(namespace, key string) error { } -func (b *RedisDB) DeleteNamespace(namespace string) error { - keys, err := readAllKeys(namespace, b) +func (b *RedisDB) DeleteNamespace(ctx context.Context, namespace string) error { + keys, err := readAllKeys(ctx, namespace, b) if err != nil { return errors.Wrap(err, "read all keys") } @@ -212,25 +210,25 @@ func (b *RedisDB) DeleteNamespace(namespace string) error { return errors.Errorf("could not delete namespace<%s>, namespace does not exist", namespace) } - return b.db.Del(b.ctx, keys...).Err() + return b.db.Del(ctx, keys...).Err() } -func (b *RedisDB) Update(namespace string, key string, values map[string]any) ([]byte, error) { - updatedData, err := txWithUpdater(namespace, key, NewUpdater(values), b) +func (b *RedisDB) Update(ctx context.Context, namespace string, key string, values map[string]any) ([]byte, error) { + updatedData, err := txWithUpdater(ctx, namespace, key, NewUpdater(values), b) return updatedData, err } -func (b *RedisDB) UpdateValueAndOperation(namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) { +func (b *RedisDB) UpdateValueAndOperation(ctx context.Context, namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) { // The Pipeliner interface provided by the go-redis library guarantees that all the commands queued in the pipeline will either succeed or fail together. - _, err = b.db.TxPipelined(b.ctx, func(pipe goredislib.Pipeliner) error { + _, err = b.db.TxPipelined(ctx, func(pipe goredislib.Pipeliner) error { - firstTx, err := txWithUpdater(namespace, key, updater, b) + firstTx, err := txWithUpdater(ctx, namespace, key, updater, b) if err != nil { return err } opUpdater.SetUpdatedResponse(firstTx) - secondTx, err := txWithUpdater(opNamespace, opKey, opUpdater, b) + secondTx, err := txWithUpdater(ctx, opNamespace, opKey, opUpdater, b) if err != nil { return err } @@ -248,9 +246,9 @@ func (b *RedisDB) UpdateValueAndOperation(namespace, key string, updater Updater return first, op, err } -func txWithUpdater(namespace, key string, updater Updater, b *RedisDB) ([]byte, error) { +func txWithUpdater(ctx context.Context, namespace, key string, updater Updater, b *RedisDB) ([]byte, error) { nameSpaceKey := getRedisKey(namespace, key) - v, err := b.db.Get(b.ctx, nameSpaceKey).Bytes() + v, err := b.db.Get(ctx, nameSpaceKey).Bytes() if err != nil { return nil, errors.Wrapf(err, "get error with namespace: %s key: %s", namespace, key) } @@ -266,7 +264,7 @@ func txWithUpdater(namespace, key string, updater Updater, b *RedisDB) ([]byte, return nil, err } - if err = b.db.Set(b.ctx, nameSpaceKey, data, 0).Err(); err != nil { + if err = b.db.Set(ctx, nameSpaceKey, data, 0).Err(); err != nil { return nil, errors.Wrap(err, "writing to db") } @@ -277,8 +275,8 @@ func getRedisKey(namespace, key string) string { return namespace + NamespaceKeySeparator + key } -func namespaceExists(namespace string, b *RedisDB) bool { - keys, _ := b.db.Scan(b.ctx, 0, namespace+"*", RedisScanBatchSize).Val() +func namespaceExists(ctx context.Context, namespace string, b *RedisDB) bool { + keys, _ := b.db.Scan(ctx, 0, namespace+"*", RedisScanBatchSize).Val() if len(keys) == 0 { return false diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 9b45a3ffa..58bbe0696 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -25,14 +25,14 @@ type ServiceStorage interface { IsOpen() bool Close() error Write(ctx context.Context, namespace, key string, value []byte) error - Read(namespace, key string) ([]byte, error) - ReadAll(namespace string) (map[string][]byte, error) - ReadPrefix(namespace, prefix string) (map[string][]byte, error) - ReadAllKeys(namespace string) ([]string, error) - Delete(namespace, key string) error - DeleteNamespace(namespace string) error - Update(namespace string, key string, values map[string]any) ([]byte, error) - UpdateValueAndOperation(namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) + Read(ctx context.Context, namespace, key string) ([]byte, error) + ReadAll(ctx context.Context, namespace string) (map[string][]byte, error) + ReadPrefix(ctx context.Context, namespace, prefix string) (map[string][]byte, error) + ReadAllKeys(ctx context.Context, namespace string) ([]string, error) + Delete(ctx context.Context, namespace, key string) error + DeleteNamespace(ctx context.Context, namespace string) error + Update(ctx context.Context, namespace string, key string, values map[string]any) ([]byte, error) + UpdateValueAndOperation(ctx context.Context, namespace, key string, updater Updater, opNamespace, opKey string, opUpdater ResponseSettingUpdater) (first, op []byte, err error) } // NewStorage returns the instance of the given storageProvider. If it doesn't exist, then a default implementation From 1762502e1cc67d2e4df7c38f68939e7d65a5eba3 Mon Sep 17 00:00:00 2001 From: Neal Date: Mon, 9 Jan 2023 17:17:17 -0600 Subject: [PATCH 3/5] fixed build and tests --- pkg/storage/db_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/storage/db_test.go b/pkg/storage/db_test.go index 7d25549f3..ae7375d04 100644 --- a/pkg/storage/db_test.go +++ b/pkg/storage/db_test.go @@ -181,19 +181,19 @@ func TestDBEmptyNamespace(t *testing.T) { namespace := "dne" key := "doesnotexist" - prefixValues, err := db.ReadPrefix(namespace, key) + prefixValues, err := db.ReadPrefix(context.Background(), namespace, key) assert.NoError(t, err) assert.Len(t, prefixValues, 0) - allKeys, err := db.ReadAllKeys(namespace) + allKeys, err := db.ReadAllKeys(context.Background(), namespace) assert.NoError(t, err) assert.Len(t, allKeys, 0) - allValues, err := db.ReadAll(namespace) + allValues, err := db.ReadAll(context.Background(), namespace) assert.NoError(t, err) assert.Len(t, allValues, 0) - value, err := db.Read(namespace, key) + value, err := db.Read(context.Background(), namespace, key) assert.NoError(t, err) assert.Nil(t, value) } From 9a47e92be9b71ff5af8e07d2f730c4b1fc83aa35 Mon Sep 17 00:00:00 2001 From: Neal Date: Thu, 12 Jan 2023 15:11:48 -0600 Subject: [PATCH 4/5] adding batch writes to create credential --- pkg/service/credential/service.go | 62 ++++++++++++--------- pkg/service/credential/storage.go | 91 ++++++++++++++++++++++++++++--- pkg/storage/bolt.go | 18 ++++++ pkg/storage/storage.go | 1 + 4 files changed, 137 insertions(+), 35 deletions(-) diff --git a/pkg/service/credential/service.go b/pkg/service/credential/service.go index 12b9a3080..b19efa08b 100644 --- a/pkg/service/credential/service.go +++ b/pkg/service/credential/service.go @@ -93,6 +93,7 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR logrus.Debugf("creating credential: %+v", request) + writeContexts := make([]WriteContext, 0) builder := credential.NewVerifiableCredentialBuilder() if err := builder.SetIssuer(request.Issuer); err != nil { @@ -176,6 +177,34 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR if err := builder.SetCredentialStatus(status); err != nil { return nil, util.LoggingErrorMsg(err, "could not set credential status") } + + statusListCredJWT, err := s.signCredentialJWT(ctx, request.Issuer, *statusListCredential) + if err != nil { + return nil, util.LoggingErrorMsg(err, "could not sign status list credential") + } + + statusListContainer := credint.Container{ + ID: statusListCredential.ID, + Credential: statusListCredential, + CredentialJWT: statusListCredJWT, + } + + statusListStorageRequest := StoreCredentialRequest{ + Container: statusListContainer, + } + + statusListIndexWriteContext, err := s.storage.GetIncrementStatusListIndexWriteContext(ctx) + if err != nil { + return nil, util.LoggingErrorMsg(err, "could not get status list index write context") + } + + statusListCredWriteContext, err := s.storage.GetStoreStatusListCredentialWriteContext(statusListStorageRequest) + if err != nil { + return nil, util.LoggingErrorMsg(err, "could not get status list credential write context") + } + + writeContexts = append(writeContexts, *statusListIndexWriteContext) + writeContexts = append(writeContexts, *statusListCredWriteContext) } cred, err := builder.Build() @@ -191,13 +220,11 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR } // TODO(gabe) support Data Integrity creds too https://github.com/TBD54566975/ssi-service/issues/105 - // sign the credential credJWT, err := s.signCredentialJWT(ctx, request.Issuer, *cred) if err != nil { return nil, util.LoggingErrorMsg(err, "could not sign credential") } - // store the credential container := credint.Container{ ID: cred.ID, Credential: cred, @@ -205,15 +232,18 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR Revoked: false, } - storageRequest := StoreCredentialRequest{ + credentialStorageRequest := StoreCredentialRequest{ Container: container, } - if err = s.storage.StoreCredential(ctx, storageRequest); err != nil { - return nil, util.LoggingErrorMsg(err, "could not store credential") + credWriteContext, err := s.storage.GetStoreCredentialWriteContext(credentialStorageRequest) + if err != nil { + return nil, util.LoggingErrorMsg(err, "could not get credential write context") } + writeContexts = append(writeContexts, *credWriteContext) + + s.storage.WriteMany(ctx, writeContexts) - // return the result response := CreateCredentialResponse{Container: container} return &response, nil } @@ -239,26 +269,6 @@ func getStatusListCredential(ctx context.Context, s Service, issuerID string, sc return nil, util.LoggingErrorMsg(err, "could not generate status list") } - statusListCredJWT, err := s.signCredentialJWT(ctx, issuerID, *generatedStatusListCredential) - if err != nil { - return nil, util.LoggingErrorMsg(err, "could not sign status list credential") - } - - // store the credential - statusListContainer := credint.Container{ - ID: generatedStatusListCredential.ID, - Credential: generatedStatusListCredential, - CredentialJWT: statusListCredJWT, - } - - storageRequest := StoreCredentialRequest{ - Container: statusListContainer, - } - - if err = s.storage.StoreStatusListCredential(ctx, storageRequest); err != nil { - return nil, util.LoggingErrorMsg(err, "could not store credential") - } - statusListCredential = generatedStatusListCredential } else { diff --git a/pkg/service/credential/storage.go b/pkg/service/credential/storage.go index 2a76b8a51..3f7ddc7e1 100644 --- a/pkg/service/credential/storage.go +++ b/pkg/service/credential/storage.go @@ -39,6 +39,12 @@ type StoredCredential struct { Revoked bool `json:"revoked"` } +type WriteContext struct { + namespace string + key string + value []byte +} + func (sc StoredCredential) IsValid() bool { return sc.ID != "" && (sc.HasDataIntegrityCredential() || sc.HasJWTCredential()) } @@ -127,16 +133,59 @@ func (cs *Storage) GetNextStatusListRandomIndex(ctx context.Context) (int, error return -1, util.LoggingErrorMsgf(err, "could not unmarshal unique numbers") } + return uniqueNums[statusListIndex.Index], nil +} + +func (cs *Storage) WriteMany(ctx context.Context, writeContexts []WriteContext) error { + namespaces := make([]string, 0) + keys := make([]string, 0) + values := make([][]byte, 0) + + for i := range writeContexts { + namespaces = append(namespaces, writeContexts[i].namespace) + keys = append(keys, writeContexts[i].key) + values = append(values, writeContexts[i].value) + } + + return cs.db.WriteMany(ctx, namespaces, keys, values) +} + +func (cs *Storage) IncrementStatusListIndex(ctx context.Context) error { + wc, err := cs.GetIncrementStatusListIndexWriteContext(ctx) + if err != nil { + return util.LoggingErrorMsg(err, "problem getting increment status listIndex writeContext") + } + + if err := cs.db.Write(ctx, wc.namespace, wc.key, wc.value); err != nil { + return util.LoggingErrorMsg(err, "problem writing current list index to db") + } + + return nil +} + +func (cs *Storage) GetIncrementStatusListIndexWriteContext(ctx context.Context) (*WriteContext, error) { + gotCurrentListIndexBytes, err := cs.db.Read(ctx, statusListIndexNamespace, currentListIndexKey) + if err != nil { + return nil, util.LoggingErrorMsgf(err, "could not get list index") + } + + var statusListIndex StatusListIndex + if err = json.Unmarshal(gotCurrentListIndexBytes, &statusListIndex); err != nil { + return nil, util.LoggingErrorMsgf(err, "could not unmarshal unique numbers") + } + statusListIndexBytes, err := json.Marshal(StatusListIndex{Index: statusListIndex.Index + 1}) if err != nil { - return -1, util.LoggingErrorMsg(err, "could not marshal status list index bytes") + return nil, util.LoggingErrorMsg(err, "could not marshal status list index bytes") } - if err := cs.db.Write(ctx, statusListIndexNamespace, currentListIndexKey, statusListIndexBytes); err != nil { - return -1, util.LoggingErrorMsg(err, "problem writing current list index to db") + wc := WriteContext{ + namespace: statusListIndexNamespace, + key: currentListIndexKey, + value: statusListIndexBytes, } - return uniqueNums[statusListIndex.Index], nil + return &wc, nil } func (cs *Storage) StoreCredential(ctx context.Context, request StoreCredentialRequest) error { @@ -148,22 +197,46 @@ func (cs *Storage) StoreStatusListCredential(ctx context.Context, request StoreC } func (cs *Storage) storeCredential(ctx context.Context, request StoreCredentialRequest, namespace string) error { + + wc, err := cs.getStoreCredentialWriteContext(request, namespace) + if err != nil { + return errors.Wrap(err, "could not get stored credential write context") + } + // TODO(gabe) conflict checking? + return cs.db.Write(ctx, wc.namespace, wc.key, wc.value) +} + +func (cs *Storage) GetStoreCredentialWriteContext(request StoreCredentialRequest) (*WriteContext, error) { + return cs.getStoreCredentialWriteContext(request, credentialNamespace) +} + +func (cs *Storage) GetStoreStatusListCredentialWriteContext(request StoreCredentialRequest) (*WriteContext, error) { + return cs.getStoreCredentialWriteContext(request, statusListCredentialNamespace) +} + +func (cs *Storage) getStoreCredentialWriteContext(request StoreCredentialRequest, namespace string) (*WriteContext, error) { if !request.IsValid() { - return util.LoggingNewError("store request request is not valid") + return nil, util.LoggingNewError("store request request is not valid") } // transform the credential into its denormalized form for storage storedCredential, err := buildStoredCredential(request) if err != nil { - return errors.Wrap(err, "could not build stored credential") + return nil, errors.Wrap(err, "could not build stored credential") } storedCredBytes, err := json.Marshal(storedCredential) if err != nil { - return util.LoggingErrorMsgf(err, "could not store request: %s", storedCredential.CredentialID) + return nil, util.LoggingErrorMsgf(err, "could not store request: %s", storedCredential.CredentialID) } - // TODO(gabe) conflict checking? - return cs.db.Write(ctx, namespace, storedCredential.ID, storedCredBytes) + + wc := WriteContext{ + namespace: namespace, + key: storedCredential.ID, + value: storedCredBytes, + } + + return &wc, nil } // buildStoredCredential generically parses a store credential request and returns the object to be stored diff --git a/pkg/storage/bolt.go b/pkg/storage/bolt.go index bdf3437af..b46147ac4 100644 --- a/pkg/storage/bolt.go +++ b/pkg/storage/bolt.go @@ -85,6 +85,24 @@ func (b *BoltDB) Write(ctx context.Context, namespace string, key string, value return nil }) } +func (b *BoltDB) WriteMany(ctx context.Context, namespaces, keys []string, values [][]byte) error { + if len(namespaces) != len(keys) && len(namespaces) != len(values) { + return errors.New("namespaces, keys, and values, are not of equal length") + } + + return b.db.Update(func(tx *bolt.Tx) error { + for i := range namespaces { + bucket, err := tx.CreateBucketIfNotExists([]byte(namespaces[i])) + if err != nil { + return err + } + if err = bucket.Put([]byte(keys[i]), values[i]); err != nil { + return err + } + } + return nil + }) +} func (b *BoltDB) Read(ctx context.Context, namespace, key string) ([]byte, error) { var result []byte diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 58bbe0696..90b3874f3 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -25,6 +25,7 @@ type ServiceStorage interface { IsOpen() bool Close() error Write(ctx context.Context, namespace, key string, value []byte) error + WriteMany(ctx context.Context, namespace, key []string, value [][]byte) error Read(ctx context.Context, namespace, key string) ([]byte, error) ReadAll(ctx context.Context, namespace string) (map[string][]byte, error) ReadPrefix(ctx context.Context, namespace, prefix string) (map[string][]byte, error) From c03d99b323a5a5734f434be2b160acf300e11fba Mon Sep 17 00:00:00 2001 From: Neal Date: Fri, 13 Jan 2023 12:00:09 -0600 Subject: [PATCH 5/5] fix linter --- pkg/service/credential/service.go | 6 ++++-- pkg/service/manifest/storage/storage.go | 2 -- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/service/credential/service.go b/pkg/service/credential/service.go index 9133b9ea0..d27e3926d 100644 --- a/pkg/service/credential/service.go +++ b/pkg/service/credential/service.go @@ -243,7 +243,9 @@ func (s Service) CreateCredential(ctx context.Context, request CreateCredentialR } writeContexts = append(writeContexts, *credWriteContext) - s.storage.WriteMany(ctx, writeContexts) + if err = s.storage.WriteMany(ctx, writeContexts); err != nil { + return nil, util.LoggingErrorMsg(err, "failed to save vc") + } response := CreateCredentialResponse{Container: container} return &response, nil @@ -289,7 +291,7 @@ func getStatusListCredential(ctx context.Context, s Service, issuerID string, sc if err = s.storage.StoreStatusListCredential(ctx, storageRequest); err != nil { return nil, util.LoggingErrorMsg(err, "could not store credential") } - + statusListCredential = generatedStatusListCredential } else { diff --git a/pkg/service/manifest/storage/storage.go b/pkg/service/manifest/storage/storage.go index 0727729d1..34bbde43f 100644 --- a/pkg/service/manifest/storage/storage.go +++ b/pkg/service/manifest/storage/storage.go @@ -247,7 +247,6 @@ func (ms *Storage) DeleteResponse(ctx context.Context, id string) error { // creates in step 2. // // The operation and it's response (from 3) are returned. - func (ms *Storage) ReviewApplication(ctx context.Context, applicationID string, approved bool, reason string, opID string, response StoredResponse) (*StoredResponse, *opstorage.StoredOperation, error) { // TODO: everything should be in a single Tx. m := map[string]any{ @@ -257,7 +256,6 @@ func (ms *Storage) ReviewApplication(ctx context.Context, applicationID string, if approved { m["status"] = opsubmission.StatusApproved } - if _, err := ms.db.Update(ctx, credential.ApplicationNamespace, applicationID, m); err != nil { return nil, nil, errors.Wrap(err, "updating application") }