Skip to content

Commit

Permalink
fix 647:
Browse files Browse the repository at this point in the history
  • Loading branch information
Thykof committed Oct 18, 2023
1 parent 147daed commit b98dc39
Show file tree
Hide file tree
Showing 25 changed files with 85 additions and 195 deletions.
69 changes: 17 additions & 52 deletions internal/handler/wallet/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package wallet
import (
"fmt"
"io"
"net/http"
"os"

"github.com/awnumar/memguard"
"github.com/go-openapi/runtime/middleware"
"github.com/massalabs/station-massa-wallet/api/server/models"
"github.com/massalabs/station-massa-wallet/api/server/restapi/operations"
walletapp "github.com/massalabs/station-massa-wallet/pkg/app"
"github.com/massalabs/station-massa-wallet/pkg/prompt"
Expand All @@ -34,10 +34,7 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd
if err == walletmanager.AccountNotFoundError {
return operations.NewGetAccountNotFound()
} else if err != nil {
return operations.NewGetAccountInternalServerError().WithPayload(&models.Error{
Code: errorGetWallets,
Message: err.Error(),
})
return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError)

Check warning on line 37 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L37

Added line #L37 was not covered by tests
}

promptRequest := prompt.PromptRequest{
Expand All @@ -47,11 +44,7 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd

promptOutput, err := prompt.WakeUpPrompt(w.prompterApp, promptRequest, acc)
if err != nil {
return operations.NewBackupAccountUnauthorized().WithPayload(
&models.Error{
Code: errorCanceledAction,
Message: "Unable to backup account",
})
return newErrorResponse("Unable to backup account", errorCanceledAction, http.StatusUnauthorized)
}

// If the user choose to backup the wallet using the yaml file, promptOutput will be a BackupMethod
Expand All @@ -62,35 +55,25 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd
var publicKey string = ""

if isYmlBackup {
walletErr := w.saveAccountFile(params.Nickname)
if walletErr != nil {
err = w.saveAccountFile(params.Nickname)
if err != nil {
w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: false, CodeMessage: walletErr.CodeErr})
walletapp.EventData{Success: false, CodeMessage: utils.WailsErrorCode(err)})

Check warning on line 61 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L61

Added line #L61 was not covered by tests

return operations.NewBackupAccountBadRequest().WithPayload(
&models.Error{
Code: errorSaveAccount,
Message: walletErr.CodeErr,
})
return newErrorResponse(utils.ErrAccountFile, errorSaveAccount, http.StatusBadRequest)

Check warning on line 63 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L63

Added line #L63 was not covered by tests
}
} else {
guardedPassword, _ := promptOutput.(*memguard.LockedBuffer)
guardedPrivateKey, err := acc.PrivateKeyTextInClear(guardedPassword)
if err != nil {
return operations.NewBackupAccountInternalServerError().WithPayload(&models.Error{
Code: errorGetWallets,
Message: err.Error(),
})
return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError)
}

Check warning on line 70 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L69-L70

Added lines #L69 - L70 were not covered by tests
defer guardedPrivateKey.Destroy()
privateKey = string(guardedPrivateKey.Bytes())

publicKeyBytes, err := acc.PublicKey.MarshalText()
if err != nil {
return operations.NewBackupAccountInternalServerError().WithPayload(&models.Error{
Code: errorGetWallets,
Message: err.Error(),
})
return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError)
}

Check warning on line 77 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L76-L77

Added lines #L76 - L77 were not covered by tests

publicKey = string(publicKeyBytes)
Expand All @@ -102,60 +85,42 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd
}

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgBackupSuccess, Data: data})
walletapp.EventData{Success: true, Data: data})

return operations.NewBackupAccountNoContent()
}

func (w *walletBackupAccount) saveAccountFile(nickname string) *walletmanager.WalletError {
func (w *walletBackupAccount) saveAccountFile(nickname string) error {
dstFile, err := w.prompterApp.SelectBackupFilepath(nickname)
if err != nil {
return &walletmanager.WalletError{
Err: err,
CodeErr: utils.ErrAccountFile,
}
return err

Check warning on line 96 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L96

Added line #L96 was not covered by tests
}

if dstFile == "" {
return &walletmanager.WalletError{
Err: fmt.Errorf("no file selected"),
CodeErr: utils.ActionCanceled,
}
return fmt.Errorf("no file selected: %w", utils.ErrActionCanceled)

Check warning on line 100 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L100

Added line #L100 was not covered by tests
}

// Create the destination file
destination, err := os.Create(dstFile)
if err != nil {
return &walletmanager.WalletError{
Err: err,
CodeErr: utils.ErrAccountFile,
}
return err

Check warning on line 106 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L106

Added line #L106 was not covered by tests
}
defer destination.Close()

srcFile, err := w.prompterApp.App().WalletManager.AccountPath(nickname)
if err != nil {
return &walletmanager.WalletError{
Err: err,
CodeErr: utils.ErrAccountFile,
}
return err

Check warning on line 112 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L112

Added line #L112 was not covered by tests
}

source, err := os.Open(srcFile)
if err != nil {
return &walletmanager.WalletError{
Err: err,
CodeErr: utils.ErrAccountFile,
}
return err

Check warning on line 117 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L117

Added line #L117 was not covered by tests
}
defer source.Close()

_, err = io.Copy(destination, source)
if err != nil {
return &walletmanager.WalletError{
Err: err,
CodeErr: utils.ErrAccountFile,
}
return err

Check warning on line 123 in internal/handler/wallet/backup.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/backup.go#L123

Added line #L123 was not covered by tests
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions internal/handler/wallet/backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func Test_walletBackupAccount_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, "Backup Success")
checkResultChannel(t, result, true, "")
})

t.Run("chose private backup then cancel", func(t *testing.T) {
Expand Down Expand Up @@ -133,7 +133,7 @@ func Test_walletBackupAccount_Handle(t *testing.T) {
assert.Equal(t, "S", string(data.PrivateKey[0]))
assert.Equal(t, string(publicKeyBytes), data.PublicKey)

checkResultChannel(t, result, true, "Backup Success")
checkResultChannel(t, result, true, "")
})

err = os.Remove(WalletBackupFilepath)
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/wallet/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (w *walletCreate) Handle(params operations.CreateAccountParams) middleware.
}

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountCreated})
walletapp.EventData{Success: true})

infos, err := w.massaClient.GetAccountsInfos([]account.Account{*acc})
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/wallet/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func Test_walletCreate_Handle(t *testing.T) {
if len(test.password) > 0 && test.statusCode == http.StatusOK {
result := <-testResult

checkResultChannel(t, result, true, "New password created")
checkResultChannel(t, result, true, "")

assertWallet(t, prompterApp.App().WalletManager, nickname)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/wallet/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (w *walletDelete) Handle(params operations.DeleteAccountParams) middleware.
}

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountDeleted})
walletapp.EventData{Success: true})

return operations.NewDeleteAccountNoContent()
}
2 changes: 1 addition & 1 deletion internal/handler/wallet/delete_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func Test_walletDelete_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, utils.MsgAccountDeleted)
checkResultChannel(t, result, true, "")

_, err = prompterApp.App().WalletManager.GetAccount(nickname)
assert.Error(t, err, "Wallet should have been deleted")
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/wallet/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (w *walletGet) Handle(params operations.GetAccountParams) middleware.Respon
defer guardedPrivateKey.Destroy()

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected})
walletapp.EventData{Success: true})

modelWallet.KeyPair, resp = newKeyPairModel(*acc, guardedPrivateKey)
if resp != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/wallet/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func Test_getWallet_handler(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, "Unprotect Success")
checkResultChannel(t, result, true, "")
})
}

Expand Down
3 changes: 1 addition & 2 deletions internal/handler/wallet/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
walletapp "github.com/massalabs/station-massa-wallet/pkg/app"
"github.com/massalabs/station-massa-wallet/pkg/network"
"github.com/massalabs/station-massa-wallet/pkg/prompt"
"github.com/massalabs/station-massa-wallet/pkg/utils"
"github.com/massalabs/station-massa-wallet/pkg/wallet/account"
)

Expand Down Expand Up @@ -43,7 +42,7 @@ func (w *walletImport) Handle(_ operations.ImportAccountParams) middleware.Respo
acc, _ := promptOutput.(*account.Account)

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountImported})
walletapp.EventData{Success: true})

infos, err := w.massaClient.GetAccountsInfos([]account.Account{*acc})
if err != nil {
Expand Down
31 changes: 2 additions & 29 deletions internal/handler/wallet/import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,39 +69,13 @@ PublicKey: [0, 164, 243, 44, 155, 204, 6, 20, 131, 218, 97, 32, 58, 224, 189, 41

verifyStatusCode(t, resp, http.StatusOK)

checkResultChannel(t, result, true, "Import Success")
checkResultChannel(t, result, true, "")

assertWallet(t, prompterApp.App().WalletManager, nickname)

os.Remove(filePath)
})

t.Run("import invalid path file", func(t *testing.T) {
walletFile := "InvalidWallet"

filePath := "importMe.yaml"
// Write wallet file
data := []byte(walletFile)
err = os.WriteFile(filePath, data, 0o644)
assert.NoError(t, err)
defer os.Remove(filePath)

testResult := make(chan walletapp.EventData)

// Send filepath to prompter app and wait for result
go func(res chan walletapp.EventData) {
// Send invalid filename to prompter app and wait for result
prompterApp.App().PromptInput <- "invalidFilename"
failRes := <-resChan

checkResultChannel(t, failRes, false, utils.ErrInvalidFileExtension)
}(testResult)

resp := importWallet(t, api)

verifyStatusCode(t, resp, http.StatusUnauthorized)
})

t.Run("import invalid account file", func(t *testing.T) {
walletFile := "InvalidWallet"

Expand Down Expand Up @@ -184,8 +158,7 @@ PublicKey: [0, 164, 243, 44, 155, 204, 6, 20, 131, 218, 97, 32, 58, 224, 189, 41
password: memguard.NewBufferFromBytes([]byte("aGoodPassword")),
wantStatus: http.StatusOK,
wantResult: walletapp.EventData{
Success: true,
CodeMessage: utils.MsgAccountImported,
Success: true,
},
},
{
Expand Down
3 changes: 1 addition & 2 deletions internal/handler/wallet/rolls.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
walletapp "github.com/massalabs/station-massa-wallet/pkg/app"
"github.com/massalabs/station-massa-wallet/pkg/network"
"github.com/massalabs/station-massa-wallet/pkg/prompt"
"github.com/massalabs/station-massa-wallet/pkg/utils"
"github.com/massalabs/station-massa-wallet/pkg/wallet/account"
sendOperation "github.com/massalabs/station/pkg/node/sendoperation"
"github.com/massalabs/station/pkg/node/sendoperation/buyrolls"
Expand Down Expand Up @@ -81,7 +80,7 @@ func (t *tradeRolls) Handle(params operations.TradeRollsParams) middleware.Respo
}

t.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgRollTradeSuccess})
walletapp.EventData{Success: true})

return operations.NewTradeRollsOK().WithPayload(
&models.OperationResponse{
Expand Down
5 changes: 3 additions & 2 deletions internal/handler/wallet/sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,10 @@ func (w *walletSign) Handle(params operations.SignParams) middleware.Responder {
password, err := w.PromptPassword(acc, promptRequest)
if err != nil {
msg := fmt.Sprintf("Unable to unprotect wallet: %s", err.Error())
if errors.Is(err, prompt.ErrWrongPassword) || errors.Is(err, prompt.ErrActionCanceled) {
if errors.Is(err, utils.ErrWrongPassword) || errors.Is(err, utils.ErrActionCanceled) {
return newErrorResponse(msg, errorGetWallets, http.StatusUnauthorized)
}

return newErrorResponse(msg, errorGetWallets, http.StatusInternalServerError)

Check warning on line 110 in internal/handler/wallet/sign.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/sign.go#L110

Added line #L110 was not covered by tests
}

Expand Down Expand Up @@ -147,7 +148,7 @@ func (w *walletSign) PromptPassword(acc *account.Account, promptRequest *prompt.
password, _ := promptOutput.(*memguard.LockedBuffer)

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected})
walletapp.EventData{Success: true})

return password, nil
}
Expand Down
14 changes: 8 additions & 6 deletions internal/handler/wallet/sign_message.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package wallet

import (
"errors"
"fmt"
"net/http"

Expand Down Expand Up @@ -47,11 +48,12 @@ func (w *walletSignMessage) Handle(params operations.SignMessageParams) middlewa
// Use the prompt-based logic to sign the message
promptOutput, err := prompt.WakeUpPrompt(w.prompterApp, *promptRequest, acc)
if err != nil {
return operations.NewSignMessageUnauthorized().WithPayload(
&models.Error{
Code: errorCanceledAction,
Message: "Unable to unprotect wallet",
})
msg := fmt.Sprintf("Unable to unprotect wallet: %s", err.Error())
if errors.Is(err, utils.ErrWrongPassword) || errors.Is(err, utils.ErrActionCanceled) {
return newErrorResponse(msg, errorGetWallets, http.StatusUnauthorized)
}

Check warning on line 54 in internal/handler/wallet/sign_message.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/sign_message.go#L51-L54

Added lines #L51 - L54 were not covered by tests

return newErrorResponse(msg, errorGetWallets, http.StatusInternalServerError)

Check warning on line 56 in internal/handler/wallet/sign_message.go

View check run for this annotation

Codecov / codecov/patch

internal/handler/wallet/sign_message.go#L56

Added line #L56 was not covered by tests
}

guardedPassword, _ := promptOutput.(*memguard.LockedBuffer)
Expand All @@ -62,7 +64,7 @@ func (w *walletSignMessage) Handle(params operations.SignMessageParams) middlewa
}

w.prompterApp.EmitEvent(walletapp.PromptResultEvent,
walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected})
walletapp.EventData{Success: true})

publicKeyBytes, err := acc.PublicKey.MarshalText()
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions internal/handler/wallet/sign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func Test_walletSign_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, utils.MsgAccountUnprotected)
checkResultChannel(t, result, true, "")
})

t.Run("sign a plain text message", func(t *testing.T) {
Expand All @@ -87,7 +87,7 @@ func Test_walletSign_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, utils.MsgAccountUnprotected)
checkResultChannel(t, result, true, "")
})

// The handler will not return until a the good password is sent or the action is canceled
Expand Down Expand Up @@ -115,7 +115,7 @@ func Test_walletSign_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, utils.MsgAccountUnprotected)
checkResultChannel(t, result, true, "")
})

t.Run("invalid password try, then action canceled by user", func(t *testing.T) {
Expand Down Expand Up @@ -152,7 +152,7 @@ func Test_walletSign_Handle(t *testing.T) {

result := <-testResult

checkResultChannel(t, result, true, "Unprotect Success")
checkResultChannel(t, result, true, "")

var body models.SignResponse
err = json.Unmarshal(resp.Body.Bytes(), &body)
Expand Down
Loading

0 comments on commit b98dc39

Please sign in to comment.