Skip to content

Commit

Permalink
Refactoring so error causality is easier to follow (#672)
Browse files Browse the repository at this point in the history
Co-authored-by: Gabe <[email protected]>
  • Loading branch information
andresuribe87 and decentralgabe authored Oct 3, 2023
1 parent c47449d commit 79cfb8b
Show file tree
Hide file tree
Showing 37 changed files with 85 additions and 101 deletions.
8 changes: 4 additions & 4 deletions integration/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func CreateVerifiableCredential(credentialInput credInputParams) (string, error)
}, expBackoff)

if err != nil {
return "", errors.Wrap(err, "error after retrying")
return "", errors.Wrap(err, "after retrying")
}

return output, nil
Expand Down Expand Up @@ -230,7 +230,7 @@ func BatchCreateVerifiableCredentials(credentialInput batchCredInputParams) (str

output, err := put(endpoint+version+"credentials/batch", credentialJSON)
if err != nil {
return "", errors.Wrap(err, "error writing batch credentials")
return "", errors.Wrap(err, "writing batch credentials")
}

return output, nil
Expand All @@ -253,7 +253,7 @@ func BatchUpdateVerifiableCredentialStatuses(updateStatusInput batchUpdateStatus

output, err := put(endpoint+version+"credentials/status/batch", updateStatusesJSON)
if err != nil {
return "", errors.Wrap(err, "error writing batch update status")
return "", errors.Wrap(err, "writing batch update status")
}

return output, nil
Expand Down Expand Up @@ -292,7 +292,7 @@ func BatchCreate100VerifiableCredentials(credentialInput credInputParams) (strin

output, err := put(endpoint+version+"credentials/batch", string(batchCreateData))
if err != nil {
return "", errors.Wrap(err, "error writing batch credentials")
return "", errors.Wrap(err, "writing batch credentials")
}

return output, nil
Expand Down
8 changes: 4 additions & 4 deletions internal/credential/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (c Container) HasJWTCredential() bool {
func NewCredentialContainerFromJWT(credentialJWT string) (*Container, error) {
_, _, cred, err := parsing.ToCredential(credentialJWT)
if err != nil {
return nil, errors.Wrap(err, "could not parse credential from JWT")
return nil, errors.Wrap(err, "parsing credential from JWT")
}
return &Container{
Credential: cred,
Expand All @@ -76,7 +76,7 @@ func NewCredentialContainerFromJWT(credentialJWT string) (*Container, error) {
func NewCredentialContainerFromMap(credMap map[string]any) (*Container, error) {
_, _, cred, err := parsing.ToCredential(credMap)
if err != nil {
return nil, errors.Wrap(err, "could not parse credential from map")
return nil, errors.Wrap(err, "parsing credential from map")
}
container := Container{
Credential: cred,
Expand Down Expand Up @@ -109,14 +109,14 @@ func NewCredentialContainerFromArray(creds []any) ([]Container, error) {
// JWT
container, err := NewCredentialContainerFromJWT(v)
if err != nil {
return nil, errors.Wrap(err, "could not parse credential from JWT")
return nil, errors.Wrap(err, "parsing credential from JWT")
}
containers = append(containers, *container)
case map[string]any:
// JSON
container, err := NewCredentialContainerFromMap(v)
if err != nil {
return nil, errors.Wrap(err, "could not parse credential from JSON")
return nil, errors.Wrap(err, "parsing credential from JSON")
}
containers = append(containers, *container)
default:
Expand Down
6 changes: 3 additions & 3 deletions internal/keyaccess/dataintegrity.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ func (ka DataIntegrityKeyAccess) Sign(payload cryptosuite.WithEmbeddedProof) (*D
return nil, errors.New("payload cannot be nil")
}
if err := ka.CryptoSuite.Sign(&ka.Signer, payload); err != nil {
return nil, errors.Wrap(err, "could not sign payload")
return nil, errors.Wrap(err, "signing payload")
}
signedJSONBytes, err := json.Marshal(payload)
if err != nil {
return nil, errors.Wrap(err, "could not marshal signed payload")
return nil, errors.Wrap(err, "marshaling signed payload")
}
return &DataIntegrityJSON{Data: signedJSONBytes}, nil
}
Expand All @@ -74,7 +74,7 @@ func (ka DataIntegrityKeyAccess) Verify(payload cryptosuite.WithEmbeddedProof) e
return errors.New("payload cannot be nil")
}
if err := ka.CryptoSuite.Verify(&ka.Verifier, payload); err != nil {
return errors.Wrap(err, "could not verify payload")
return errors.Wrap(err, "verifying payload")
}
return nil
}
Expand Down
6 changes: 3 additions & 3 deletions internal/keyaccess/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (ka JWKKeyAccess) Sign(payload map[string]any) (*JWT, error) {
}
tokenBytes, err := ka.SignWithDefaults(payload)
if err != nil {
return nil, errors.Wrap(err, "could not sign payload")
return nil, errors.Wrap(err, "signing payload")
}
return JWT(tokenBytes).Ptr(), nil
}
Expand All @@ -125,7 +125,7 @@ func (ka JWKKeyAccess) SignVerifiableCredential(cred credential.VerifiableCreden

tokenBytes, err := integrity.SignVerifiableCredentialJWT(*ka.Signer, cred)
if err != nil {
return nil, errors.Wrap(err, "could not sign cred")
return nil, errors.Wrap(err, "signing cred")
}
return JWT(tokenBytes).Ptr(), nil
}
Expand All @@ -147,7 +147,7 @@ func (ka JWKKeyAccess) SignVerifiablePresentation(audience string, presentation
}
tokenBytes, err := integrity.SignVerifiablePresentationJWT(*ka.Signer, &integrity.JWTVVPParameters{Audience: []string{audience}}, presentation)
if err != nil {
return nil, errors.Wrap(err, "could not sign presentation")
return nil, errors.Wrap(err, "signing presentation")
}
return JWT(tokenBytes).Ptr(), nil
}
Expand Down
8 changes: 4 additions & 4 deletions internal/util/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ const (
func XChaCha20Poly1305Encrypt(key, data []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, errors.Wrap(err, "could not create aead with provided key")
return nil, errors.Wrap(err, "creating aead with provided key")
}

// generate a random nonce, leaving room for the ciphertext
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(data)+aead.Overhead())
if _, err = rand.Read(nonce); err != nil {
return nil, errors.Wrap(err, "could not generate nonce for encryption")
return nil, errors.Wrap(err, "generating nonce for encryption")
}

encrypted := aead.Seal(nonce, nonce, data, nil)
Expand All @@ -46,7 +46,7 @@ func XChaCha20Poly1305Encrypt(key, data []byte) ([]byte, error) {
func XChaCha20Poly1305Decrypt(key, data []byte) ([]byte, error) {
aead, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, errors.Wrap(err, "could not create aead with provided key")
return nil, errors.Wrap(err, "creating aead with provided key")
}

if len(data) < aead.NonceSize() {
Expand All @@ -59,7 +59,7 @@ func XChaCha20Poly1305Decrypt(key, data []byte) ([]byte, error) {
// Decrypt the message and check it wasn't tampered with.
decrypted, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, errors.Wrap(err, "could not decrypt data")
return nil, errors.Wrap(err, "decrypting data")
}
return decrypted, nil
}
Expand Down
2 changes: 1 addition & 1 deletion internal/verification/verification.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func NewVerifiableDataVerifier(didResolver resolution.Resolver, schemaResolver s
validators := validation.GetKnownVerifiers()
validator, err := validation.NewCredentialValidator(validators)
if err != nil {
return nil, errors.Wrap(err, "failed to create static validator")
return nil, errors.Wrap(err, "creating static validator")
}
return &Verifier{
validator: validator,
Expand Down
16 changes: 0 additions & 16 deletions pkg/server/framework/util.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
package framework

import (
"bytes"
"io"
"net/http"

"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)

// GetParam is a utility to get a path parameter from context, nil if not found
Expand All @@ -30,14 +25,3 @@ func GetQueryValue(c *gin.Context, param string) *string {
}
return &got
}

// PeekRequestBody reads a request's body without emptying the buffer
func PeekRequestBody(r *http.Request) (string, error) {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
return "", errors.Wrap(err, "could not ready request body")
}
result := string(bodyBytes)
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
return result, nil
}
2 changes: 1 addition & 1 deletion pkg/server/router/credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,7 @@ func (cr CredentialRouter) DeleteCredential(c *gin.Context) {
}

if err := cr.service.DeleteCredential(c, credential.DeleteCredentialRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete credential with id: %s", *id)
errMsg := fmt.Sprintf("deleting credential with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/router/did_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func TestDIDRouter(t *testing.T) {
// bad key type
_, 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")
assert.Contains(tt, err.Error(), "unsupported did:key type: bad")

// good key type
createDIDResponse, err := didService.CreateDIDByMethod(context.Background(), did.CreateDIDRequest{Method: didsdk.KeyMethod, KeyType: crypto.Ed25519})
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/router/issuance.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func (ir IssuanceRouter) DeleteIssuanceTemplate(c *gin.Context) {
}

if err := ir.service.DeleteIssuanceTemplate(c, &issuance.DeleteIssuanceTemplateRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete issuance template with id: %s", *id)
errMsg := fmt.Sprintf("deleting issuance template with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/server/router/keystore.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ func (sk StoreKeyRequest) ToServiceRequest() (*keystore.StoreKeyRequest, error)
// make sure we can decode and re-encode the key before storing it
privateKeyBytes, err := base58.Decode(sk.PrivateKeyBase58)
if err != nil {
return nil, errors.Wrap(err, "could not decode base58 private key")
return nil, errors.Wrap(err, "decoding base58 private key")
}
if _, err = crypto.BytesToPrivKey(privateKeyBytes, sk.Type); err != nil {
return nil, errors.Wrap(err, "could not convert bytes to private key")
return nil, errors.Wrap(err, "converting bytes to private key")
}
return &keystore.StoreKeyRequest{
ID: sk.ID,
Expand Down
16 changes: 8 additions & 8 deletions pkg/server/router/manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func (mr ManifestRouter) DeleteManifest(c *gin.Context) {
}

if err := mr.service.DeleteManifest(c, model.DeleteManifestRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete manifest with id: %s", *id)
errMsg := fmt.Sprintf("deleting manifest with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand All @@ -258,7 +258,7 @@ const (
func (sar SubmitApplicationRequest) toServiceRequest() (*model.SubmitApplicationRequest, error) {
_, token, err := util.ParseJWT(sar.ApplicationJWT)
if err != nil {
return nil, errors.Wrap(err, "could not parse application JWT")
return nil, errors.Wrap(err, "parsing application JWT")
}
iss := token.Issuer()
if iss == "" {
Expand Down Expand Up @@ -287,16 +287,16 @@ func (sar SubmitApplicationRequest) toServiceRequest() (*model.SubmitApplication
}
applicationTokenBytes, err := json.Marshal(credAppJSON)
if err != nil {
return nil, errors.Wrap(err, "could not marshal Credential Application credAppJSON")
return nil, errors.Wrap(err, "marshalling Credential Application credAppJSON")
}
var application manifestsdk.CredentialApplication
if err = json.Unmarshal(applicationTokenBytes, &application); err != nil {
return nil, errors.Wrap(err, "could not reconstruct Credential Application")
return nil, errors.Wrap(err, "reconstructing Credential Application")
}

credContainer, err := credential.NewCredentialContainerFromArray(creds)
if err != nil {
return nil, errors.Wrap(err, "could not parse submitted credentials")
return nil, errors.Wrap(err, "parsing submitted credentials")
}
return &model.SubmitApplicationRequest{
ApplicantDID: iss,
Expand Down Expand Up @@ -438,7 +438,7 @@ func (mr ManifestRouter) DeleteApplication(c *gin.Context) {
}

if err := mr.service.DeleteApplication(c, model.DeleteApplicationRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete application with id: %s", *id)
errMsg := fmt.Sprintf("deleting application with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -535,7 +535,7 @@ func (mr ManifestRouter) DeleteResponse(c *gin.Context) {
}

if err := mr.service.DeleteResponse(c, model.DeleteResponseRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete response with id: %s", *id)
errMsg := fmt.Sprintf("deleting response with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -744,7 +744,7 @@ func (mr ManifestRouter) DeleteRequest(c *gin.Context) {
}

if err := mr.service.DeleteRequest(c, model.DeleteRequestRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete manifest request with id: %s", *id)
errMsg := fmt.Sprintf("deleting manifest request with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/server/router/presentation.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ func (pr PresentationRouter) DeleteDefinition(c *gin.Context) {
}

if err := pr.service.DeletePresentationDefinition(c, model.DeletePresentationDefinitionRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete presentation with id: %s", *id)
errMsg := fmt.Sprintf("deleting presentation with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down Expand Up @@ -681,7 +681,7 @@ func (pr PresentationRouter) DeleteRequest(c *gin.Context) {
}

if err := pr.service.DeleteRequest(c, model.DeleteRequestRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete presentation request with id: %s", *id)
errMsg := fmt.Sprintf("deleting presentation request with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/router/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ func (sr SchemaRouter) DeleteSchema(c *gin.Context) {
}

if err := sr.service.DeleteSchema(c, schema.DeleteSchemaRequest{ID: *id}); err != nil {
errMsg := fmt.Sprintf("could not delete schema with id: %s", *id)
errMsg := fmt.Sprintf("deleting schema with id: %s", *id)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/router/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func (wr WebhookRouter) DeleteWebhook(c *gin.Context) {
}

if err := wr.service.DeleteWebhook(c, req); err != nil {
errMsg := fmt.Sprintf("could not delete webhook with id: %s-%s-%s", request.Noun, request.Verb, request.URL)
errMsg := fmt.Sprintf("deleting webhook with id: %s-%s-%s", request.Noun, request.Verb, request.URL)
framework.LoggingRespondErrWithMsg(c, err, errMsg, http.StatusInternalServerError)
return
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/server_presentation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ func TestPresentationAPI(t *testing.T) {
w := httptest.NewRecorder()
c := newRequestContextWithParams(w, req, map[string]string{"id": pd.ID})
pRouter.DeleteDefinition(c)
assert.Contains(ttt, w.Body.String(), fmt.Sprintf("could not delete presentation definition with id: %s", pd.ID))
assert.Contains(ttt, w.Body.String(), fmt.Sprintf("deleting presentation definition with id: %s", pd.ID))
})

tt.Run("Submission endpoints", func(ttt *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/server/server_schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ func TestSchemaAPI(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, "https://ssi-service.com/v1/schemas/bad", nil)
c := newRequestContextWithParams(w, req, map[string]string{"id": "bad"})
schemaService.DeleteSchema(c)
assert.Contains(tt, w.Body.String(), "could not delete schema with id: bad")
assert.Contains(tt, w.Body.String(), "deleting schema with id: bad")

// create a schema
simpleSchema := getTestSchema()
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/common/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func (s *requestStorage) GetRequest(ctx context.Context, id string) (*StoredRequ

func (s *requestStorage) DeleteRequest(ctx context.Context, id string) error {
if err := s.db.Delete(ctx, s.namespace, id); err != nil {
return util.LoggingNewErrorf("could not delete request: %s", id)
return util.LoggingNewErrorf("deleting request: %s", id)
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/credential/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ func (s Service) DeleteCredential(ctx context.Context, request DeleteCredentialR
logrus.Debugf("deleting credential: %s", request.ID)

if err := s.storage.DeleteCredential(ctx, request.ID); err != nil {
return sdkutil.LoggingErrorMsgf(err, "could not delete credential with id: %s", request.ID)
return sdkutil.LoggingErrorMsgf(err, "deleting credential with id: %s", request.ID)
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions pkg/service/credential/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ func buildStoredCredential(request StoreCredentialRequest) (*StoredCredential, e
if request.HasJWTCredential() {
_, _, parsedCred, err := integrity.ParseVerifiableCredentialFromJWT(request.CredentialJWT.String())
if err != nil {
return nil, errors.Wrap(err, "could not parse credential from jwt")
return nil, errors.Wrap(err, "parsing credential from jwt")
}

// if we have a JWT credential, update the reference
Expand Down Expand Up @@ -524,7 +524,7 @@ func (cs *Storage) deleteCredential(ctx context.Context, id string, namespace st
// re-create the prefix key to delete
prefix := createPrefixKey(id, gotCred.Issuer, gotCred.Subject, gotCred.Schema)
if err = cs.db.Delete(ctx, namespace, prefix); err != nil {
return sdkutil.LoggingErrorMsgf(err, "could not delete credential: %s", id)
return sdkutil.LoggingErrorMsgf(err, "deleting credential: %s", id)
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/did/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type BatchService struct {
func NewBatchDIDService(config config.DIDServiceConfig, s storage.ServiceStorage, factory keystore.ServiceFactory) (*BatchService, error) {
didStorage, err := NewDIDStorage(s)
if err != nil {
return nil, errors.Wrap(err, "could not instantiate DID storage for the DID service")
return nil, errors.Wrap(err, "instantiating DID storage for the DID service")
}

service := BatchService{
Expand Down
Loading

0 comments on commit 79cfb8b

Please sign in to comment.