github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/appsec/custom_rule_test.go (about)

     1  package appsec
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"errors"
     7  	"net/http"
     8  	"net/http/httptest"
     9  	"testing"
    10  
    11  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v2/pkg/session"
    12  	"github.com/stretchr/testify/assert"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestAppSec_ListCustomRules(t *testing.T) {
    17  
    18  	result := GetCustomRulesResponse{}
    19  
    20  	respData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRules.json"))
    21  	json.Unmarshal([]byte(respData), &result)
    22  
    23  	tests := map[string]struct {
    24  		params           GetCustomRulesRequest
    25  		responseStatus   int
    26  		responseBody     string
    27  		expectedPath     string
    28  		expectedResponse *GetCustomRulesResponse
    29  		withError        error
    30  		headers          http.Header
    31  	}{
    32  		"200 OK": {
    33  			params: GetCustomRulesRequest{
    34  				ConfigID: 43253,
    35  			},
    36  			headers: http.Header{
    37  				"Content-Type": []string{"application/json"},
    38  			},
    39  			responseStatus:   http.StatusOK,
    40  			responseBody:     string(respData),
    41  			expectedPath:     "/appsec/v1/configs/43253/custom-rules",
    42  			expectedResponse: &result,
    43  		},
    44  		"500 internal server error": {
    45  			params: GetCustomRulesRequest{
    46  				ConfigID: 43253,
    47  			},
    48  			headers:        http.Header{},
    49  			responseStatus: http.StatusInternalServerError,
    50  			responseBody: `
    51  {
    52      "type": "internal_error",
    53      "title": "Internal Server Error",
    54      "detail": "Error fetching propertys",
    55      "status": 500
    56  }`,
    57  			expectedPath: "/appsec/v1/configs/43253/custom-rules",
    58  			withError: &Error{
    59  				Type:       "internal_error",
    60  				Title:      "Internal Server Error",
    61  				Detail:     "Error fetching propertys",
    62  				StatusCode: http.StatusInternalServerError,
    63  			},
    64  		},
    65  	}
    66  
    67  	for name, test := range tests {
    68  		t.Run(name, func(t *testing.T) {
    69  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    70  				assert.Equal(t, test.expectedPath, r.URL.String())
    71  				assert.Equal(t, http.MethodGet, r.Method)
    72  				w.WriteHeader(test.responseStatus)
    73  				_, err := w.Write([]byte(test.responseBody))
    74  				assert.NoError(t, err)
    75  			}))
    76  			client := mockAPIClient(t, mockServer)
    77  			result, err := client.GetCustomRules(
    78  				session.ContextWithOptions(
    79  					context.Background(),
    80  					session.WithContextHeaders(test.headers),
    81  				),
    82  				test.params)
    83  			if test.withError != nil {
    84  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
    85  				return
    86  			}
    87  			require.NoError(t, err)
    88  			assert.Equal(t, test.expectedResponse, result)
    89  		})
    90  	}
    91  }
    92  
    93  // Test CustomRule
    94  func TestAppSec_GetCustomRule(t *testing.T) {
    95  
    96  	result := GetCustomRuleResponse{}
    97  
    98  	respData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRule.json"))
    99  	json.Unmarshal([]byte(respData), &result)
   100  
   101  	tests := map[string]struct {
   102  		params           GetCustomRuleRequest
   103  		responseStatus   int
   104  		responseBody     string
   105  		expectedPath     string
   106  		expectedResponse *GetCustomRuleResponse
   107  		withError        error
   108  	}{
   109  		"200 OK": {
   110  			params: GetCustomRuleRequest{
   111  				ConfigID: 43253,
   112  				ID:       60039625,
   113  			},
   114  			responseStatus:   http.StatusOK,
   115  			responseBody:     respData,
   116  			expectedPath:     "/appsec/v1/configs/43253/custom-rules/60039625",
   117  			expectedResponse: &result,
   118  		},
   119  		"500 internal server error": {
   120  			params: GetCustomRuleRequest{
   121  				ConfigID: 43253,
   122  				ID:       60039625,
   123  			},
   124  			responseStatus: http.StatusInternalServerError,
   125  			responseBody: (`
   126  {
   127      "type": "internal_error",
   128      "title": "Internal Server Error",
   129      "detail": "Error fetching match target"
   130  }`),
   131  			expectedPath: "/appsec/v1/configs/43253/custom-rules/60039625",
   132  			withError: &Error{
   133  				Type:       "internal_error",
   134  				Title:      "Internal Server Error",
   135  				Detail:     "Error fetching match target",
   136  				StatusCode: http.StatusInternalServerError,
   137  			},
   138  		},
   139  	}
   140  
   141  	for name, test := range tests {
   142  		t.Run(name, func(t *testing.T) {
   143  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   144  				assert.Equal(t, test.expectedPath, r.URL.String())
   145  				assert.Equal(t, http.MethodGet, r.Method)
   146  				w.WriteHeader(test.responseStatus)
   147  				_, err := w.Write([]byte(test.responseBody))
   148  				assert.NoError(t, err)
   149  			}))
   150  			client := mockAPIClient(t, mockServer)
   151  			result, err := client.GetCustomRule(context.Background(), test.params)
   152  			if test.withError != nil {
   153  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
   154  				return
   155  			}
   156  			require.NoError(t, err)
   157  			assert.Equal(t, test.expectedResponse, result)
   158  		})
   159  	}
   160  }
   161  
   162  // Test Create CustomRule
   163  func TestAppSec_CreateCustomRule(t *testing.T) {
   164  
   165  	result := CreateCustomRuleResponse{}
   166  
   167  	respData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRule.json"))
   168  	json.Unmarshal([]byte(respData), &result)
   169  
   170  	req := CreateCustomRuleRequest{}
   171  
   172  	reqData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRule.json"))
   173  	json.Unmarshal([]byte(reqData), &req)
   174  
   175  	tests := map[string]struct {
   176  		params           CreateCustomRuleRequest
   177  		prop             *CreateCustomRuleRequest
   178  		responseStatus   int
   179  		responseBody     string
   180  		expectedPath     string
   181  		expectedResponse *CreateCustomRuleResponse
   182  		withError        error
   183  		headers          http.Header
   184  	}{
   185  		"201 Created": {
   186  			params: CreateCustomRuleRequest{
   187  				ConfigID: 43253,
   188  			},
   189  			headers: http.Header{
   190  				"Content-Type": []string{"application/json;charset=UTF-8"},
   191  			},
   192  			responseStatus:   http.StatusCreated,
   193  			responseBody:     respData,
   194  			expectedResponse: &result,
   195  			expectedPath:     "/appsec/v1/configs/43253/custom-rules",
   196  		},
   197  		"500 internal server error": {
   198  			params: CreateCustomRuleRequest{
   199  				ConfigID: 43253,
   200  			},
   201  			responseStatus: http.StatusInternalServerError,
   202  			responseBody: (`
   203  {
   204      "type": "internal_error",
   205      "title": "Internal Server Error",
   206      "detail": "Error creating domain"
   207  }`),
   208  			expectedPath: "/appsec/v1/configs/43253/custom-rules",
   209  			withError: &Error{
   210  				Type:       "internal_error",
   211  				Title:      "Internal Server Error",
   212  				Detail:     "Error creating domain",
   213  				StatusCode: http.StatusInternalServerError,
   214  			},
   215  		},
   216  	}
   217  
   218  	for name, test := range tests {
   219  		t.Run(name, func(t *testing.T) {
   220  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   221  				assert.Equal(t, http.MethodPost, r.Method)
   222  				w.WriteHeader(test.responseStatus)
   223  				if len(test.responseBody) > 0 {
   224  					_, err := w.Write([]byte(test.responseBody))
   225  					assert.NoError(t, err)
   226  				}
   227  			}))
   228  			client := mockAPIClient(t, mockServer)
   229  			result, err := client.CreateCustomRule(
   230  				session.ContextWithOptions(
   231  					context.Background(),
   232  					session.WithContextHeaders(test.headers)), test.params)
   233  			if test.withError != nil {
   234  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
   235  				return
   236  			}
   237  			require.NoError(t, err)
   238  			assert.Equal(t, test.expectedResponse, result)
   239  		})
   240  	}
   241  }
   242  
   243  // Test Update CustomRule
   244  func TestAppSec_UpdateCustomRule(t *testing.T) {
   245  	result := UpdateCustomRuleResponse{}
   246  
   247  	respData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRule.json"))
   248  	json.Unmarshal([]byte(respData), &result)
   249  
   250  	req := UpdateCustomRuleRequest{}
   251  
   252  	reqData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRule.json"))
   253  	json.Unmarshal([]byte(reqData), &req)
   254  
   255  	tests := map[string]struct {
   256  		params           UpdateCustomRuleRequest
   257  		responseStatus   int
   258  		responseBody     string
   259  		expectedPath     string
   260  		expectedResponse *UpdateCustomRuleResponse
   261  		withError        error
   262  		headers          http.Header
   263  	}{
   264  		"200 Success": {
   265  			params: UpdateCustomRuleRequest{
   266  				ConfigID: 43253,
   267  				ID:       60039625,
   268  			},
   269  			headers: http.Header{
   270  				"Content-Type": []string{"application/json;charset=UTF-8"},
   271  			},
   272  			responseStatus:   http.StatusCreated,
   273  			responseBody:     respData,
   274  			expectedResponse: &result,
   275  			expectedPath:     "/appsec/v1/configs/43253/custom-rules/%d",
   276  		},
   277  		"500 internal server error": {
   278  			params: UpdateCustomRuleRequest{
   279  				ConfigID: 43253,
   280  				ID:       60039625,
   281  			},
   282  			responseStatus: http.StatusInternalServerError,
   283  			responseBody: (`
   284  {
   285      "type": "internal_error",
   286      "title": "Internal Server Error",
   287      "detail": "Error creating zone"
   288  }`),
   289  			expectedPath: "/appsec/v1/configs/43253/custom-rules/%d",
   290  			withError: &Error{
   291  				Type:       "internal_error",
   292  				Title:      "Internal Server Error",
   293  				Detail:     "Error creating zone",
   294  				StatusCode: http.StatusInternalServerError,
   295  			},
   296  		},
   297  	}
   298  
   299  	for name, test := range tests {
   300  		t.Run(name, func(t *testing.T) {
   301  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   302  				assert.Equal(t, http.MethodPut, r.Method)
   303  				w.WriteHeader(test.responseStatus)
   304  				if len(test.responseBody) > 0 {
   305  					_, err := w.Write([]byte(test.responseBody))
   306  					assert.NoError(t, err)
   307  				}
   308  			}))
   309  			client := mockAPIClient(t, mockServer)
   310  			result, err := client.UpdateCustomRule(
   311  				session.ContextWithOptions(
   312  					context.Background(),
   313  					session.WithContextHeaders(test.headers)), test.params)
   314  			if test.withError != nil {
   315  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
   316  				return
   317  			}
   318  			require.NoError(t, err)
   319  			assert.Equal(t, test.expectedResponse, result)
   320  		})
   321  	}
   322  }
   323  
   324  // Test Remove CustomRule
   325  func TestAppSec_RemoveCustomRule(t *testing.T) {
   326  
   327  	result := RemoveCustomRuleResponse{}
   328  
   329  	respData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRulesEmpty.json"))
   330  	json.Unmarshal([]byte(respData), &result)
   331  
   332  	req := RemoveCustomRuleRequest{}
   333  
   334  	reqData := compactJSON(loadFixtureBytes("testdata/TestCustomRules/CustomRulesEmpty.json"))
   335  	json.Unmarshal([]byte(reqData), &req)
   336  
   337  	tests := map[string]struct {
   338  		params           RemoveCustomRuleRequest
   339  		responseStatus   int
   340  		responseBody     string
   341  		expectedPath     string
   342  		expectedResponse *RemoveCustomRuleResponse
   343  		withError        error
   344  		headers          http.Header
   345  	}{
   346  		"200 Success": {
   347  			params: RemoveCustomRuleRequest{
   348  				ConfigID: 43253,
   349  				ID:       60039625,
   350  			},
   351  			headers: http.Header{
   352  				"Content-Type": []string{"application/json"},
   353  			},
   354  			responseStatus:   http.StatusOK,
   355  			responseBody:     respData,
   356  			expectedResponse: &result,
   357  			expectedPath:     "/appsec/v1/configs/43253/custom-rules/%d",
   358  		},
   359  		"500 internal server error": {
   360  			params: RemoveCustomRuleRequest{
   361  				ConfigID: 43253,
   362  				ID:       60039625,
   363  			},
   364  			responseStatus: http.StatusInternalServerError,
   365  			responseBody: (`
   366  {
   367      "type": "internal_error",
   368      "title": "Internal Server Error",
   369      "detail": "Error deleting match target"
   370  }`),
   371  			expectedPath: "/appsec/v1/configs/43253/custom-rules/%d",
   372  			withError: &Error{
   373  				Type:       "internal_error",
   374  				Title:      "Internal Server Error",
   375  				Detail:     "Error deleting match target",
   376  				StatusCode: http.StatusInternalServerError,
   377  			},
   378  		},
   379  	}
   380  
   381  	for name, test := range tests {
   382  		t.Run(name, func(t *testing.T) {
   383  			mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   384  				assert.Equal(t, http.MethodDelete, r.Method)
   385  				w.WriteHeader(test.responseStatus)
   386  				if len(test.responseBody) > 0 {
   387  					_, err := w.Write([]byte(test.responseBody))
   388  					assert.NoError(t, err)
   389  				}
   390  			}))
   391  			client := mockAPIClient(t, mockServer)
   392  			result, err := client.RemoveCustomRule(
   393  				session.ContextWithOptions(
   394  					context.Background(),
   395  					session.WithContextHeaders(test.headers)), test.params)
   396  			if test.withError != nil {
   397  				assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err)
   398  				return
   399  			}
   400  			require.NoError(t, err)
   401  			assert.Equal(t, test.expectedResponse, result)
   402  		})
   403  	}
   404  }