Skip to content

Commit

Permalink
fix: Handle case when NAP metadata directory doesn't exist (#179)
Browse files Browse the repository at this point in the history
When writing NAP metadata, create the metadata directory if it doesn't exist.
  • Loading branch information
edarzins authored Jan 23, 2023
1 parent bdeec5f commit a0f380f
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
13 changes: 12 additions & 1 deletion src/extensions/nginx-app-protect/nap/nap_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"encoding/json"
"errors"
"os"
"path/filepath"

"github.com/nginx/agent/sdk/v2"
"github.com/nginx/agent/sdk/v2/proto"
Expand Down Expand Up @@ -88,8 +89,18 @@ func UpdateMetadata(
if err != nil {
return err
}
log.Debugf("Writing NAP Metadata %s", m)

// Make dir if not exists
directory := filepath.Dir(wafLocation)
_, err = os.Stat(directory)
if os.IsNotExist(err) {
err = os.MkdirAll(directory, 0755)
if err != nil {
return err
}
}

log.Debugf("Writing NAP Metadata %s", m)
return os.WriteFile(wafLocation, m, 0644)
}

Expand Down
19 changes: 17 additions & 2 deletions src/extensions/nginx-app-protect/nap/nap_metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ import (

const (
configFile = "/tmp/testdata/nginx.conf"
metadataFile = "/tmp/testdata/app_protect_metadata.json"
basePath = "/tmp/testdata"
metadataPath = "/tmp/testdata/nms"
metadataFile = "/tmp/testdata/nms/app_protect_metadata.json"

nginxID = "1"
systemID = "2"
Expand Down Expand Up @@ -105,6 +107,12 @@ func TestUpdateNapMetadata(t *testing.T) {
precompPub bool
expected string
}{
{
testName: "NoMetadataDir",
meta: "",
precompPub: false,
expected: expectedFalse,
},
{
testName: "NoMetadataFile",
meta: "",
Expand Down Expand Up @@ -135,7 +143,14 @@ func TestUpdateNapMetadata(t *testing.T) {
t.Run(tc.testName, func(t *testing.T) {
defer tearDownTestDirectory()

if tc.testName != "NoMetadataFile" {
switch tc.testName {
case "NoMetadataDir":
err := os.MkdirAll(basePath, 0755)
assert.NoError(t, err)
case "NoMetadataFile":
err := os.MkdirAll(metadataPath, 0755)
assert.NoError(t, err)
default:
err := setUpFile(metadataFile, []byte(tc.meta))
assert.NoError(t, err)
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a0f380f

Please sign in to comment.