From 5973d1789e2fad763157430bc43d09186a674e8c Mon Sep 17 00:00:00 2001 From: leszek-vechain Date: Fri, 7 Jun 2024 21:45:04 +0100 Subject: [PATCH] chore: add check if path to file is valid --- entrypoint/api/http_api_test.go | 12 ++++++++++-- preset/preset.go | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/entrypoint/api/http_api_test.go b/entrypoint/api/http_api_test.go index 91c78e2..8907ff6 100644 --- a/entrypoint/api/http_api_test.go +++ b/entrypoint/api/http_api_test.go @@ -63,13 +63,21 @@ func TestStartStopHandler(t *testing.T) { wantBody: "Unable to stop network - network no-exist is not configured\n", }, { - name: "Load existing preset network", + name: "Load existing preset network with valid artifact path", target: "/preset/noop-network", - payload: "{ \"artifactPath\": \"noop/dir\" }", + payload: "{ \"artifactPath\": \"http_api_test.go\" }", method: http.MethodPost, wantStatus: http.StatusOK, wantBody: "{\"networkId\": \"noop\"}", }, + { + name: "Load existing preset network with invalid artifact path", + target: "/preset/noop-network", + payload: "{ \"artifactPath\": \"blob\" }", + method: http.MethodPost, + wantStatus: http.StatusBadRequest, + wantBody: "file does not exist at location: blob", + }, { name: "Load existing preset network no config", target: "/preset/noop-network", diff --git a/preset/preset.go b/preset/preset.go index b0d14cf..85b712a 100644 --- a/preset/preset.go +++ b/preset/preset.go @@ -4,6 +4,7 @@ import ( "fmt" "log/slog" "math/big" + "os" "github.com/vechain/networkhub/network" "github.com/vechain/thor/v2/genesis" @@ -17,6 +18,14 @@ type Networks struct { presets map[string]*network.Network } +func fileExists(path string) bool { + _, err := os.Stat(path) + if os.IsNotExist(err) { + return false + } + return err == nil +} + func NewPresetNetworks() *Networks { return &Networks{ presets: map[string]*network.Network{}, @@ -37,6 +46,11 @@ func (p *Networks) Load(id string, configPayload *APIConfigPayload) (*network.Ne if configPayload == nil || configPayload.ArtifactPath == "" { return nil, fmt.Errorf("preset config must be set") } + + if !fileExists(configPayload.ArtifactPath) { + return nil, fmt.Errorf("file does not exist at location: %s", configPayload.ArtifactPath) + } + // override the default path for _, node := range preset.Nodes { node.ExecArtifact = configPayload.ArtifactPath