Skip to content

Commit

Permalink
Revert "Policy REST API (#3302)"
Browse files Browse the repository at this point in the history
This reverts commit 75114d0.
  • Loading branch information
furkansenharputlu committed Mar 15, 2022
1 parent 2b8044e commit aaeba77
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 236 deletions.
3 changes: 0 additions & 3 deletions cli/linter/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -779,9 +779,6 @@
"service",
"rpc"
]
},
"policy_path": {
"type": "string"
}
}
},
Expand Down
3 changes: 0 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,6 @@ type PoliciesConfig struct {
//
// This option should only be used when moving an installation to a new database.
AllowExplicitPolicyID bool `json:"allow_explicit_policy_id"`
// This option is used for storing a policies if `policies.policy_source` is set to `file`.
// it should be some existing file path on hard drive
PolicyPath string `json:"policy_path"`
}

type DBAppConfOptionsConfig struct {
Expand Down
135 changes: 1 addition & 134 deletions gateway/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,102 +775,6 @@ func (gw *Gateway) handleRemoveSortedSetRange(keyName, scoreFrom, scoreTo string
return gw.GlobalSessionManager.Store().RemoveSortedSetRange(keyName, scoreFrom, scoreTo)
}

func (gw *Gateway) handleGetPolicy(polID string) (interface{}, int) {
if pol := gw.getPolicy(polID); pol.ID != "" {
return pol, http.StatusOK
}

log.WithFields(logrus.Fields{
"prefix": "policy",
"polID": polID,
}).Error("Policy doesn't exist.")
return apiError("Policy not found"), http.StatusNotFound
}

func (gw *Gateway) handleGetPolicyList() (interface{}, int) {
gw.policiesMu.RLock()
defer gw.policiesMu.RUnlock()
polIDList := make([]user.Policy, len(gw.policiesByID))
c := 0
for _, pol := range gw.policiesByID {
polIDList[c] = pol
c++
}
return polIDList, http.StatusOK
}

func (gw *Gateway) handleAddOrUpdatePolicy(polID string, r *http.Request) (interface{}, int) {
if gw.GetConfig().Policies.PolicySource == "service" {
log.Error("Rejected new policy due to PolicySource = service")
return apiError("Due to enabled service policy source, please use the Dashboard API"), http.StatusInternalServerError
}

newPol := &user.Policy{}
if err := json.NewDecoder(r.Body).Decode(newPol); err != nil {
log.Error("Couldn't decode new policy object: ", err)
return apiError("Request malformed"), http.StatusBadRequest
}

if polID != "" && newPol.ID != polID && r.Method == http.MethodPut {
log.Error("PUT operation on different IDs")
return apiError("Request ID does not match that in policy! For Update operations these must match."), http.StatusBadRequest
}

// Create a filename
polFilePath := filepath.Join(gw.GetConfig().Policies.PolicyPath, newPol.ID+".json")

asByte, err := json.MarshalIndent(newPol, "", " ")
if err != nil {
log.Error("Marshalling of policy failed: ", err)
return apiError("Marshalling failed"), http.StatusInternalServerError
}

if err := ioutil.WriteFile(polFilePath, asByte, 0644); err != nil {
log.Error("Failed to create file! - ", err)
return apiError("Failed to create file!"), http.StatusInternalServerError
}

action := "modified"
if r.Method == http.MethodPost {
action = "added"
gw.policiesMu.Lock()
gw.policiesByID[polID] = *newPol
gw.policiesMu.Unlock()
}

response := apiModifyKeySuccess{
Key: newPol.ID,
Status: "ok",
Action: action,
}

return response, http.StatusOK
}

func (gw *Gateway) handleDeletePolicy(polID string) (interface{}, int) {
// Generate a filename
defFilePath := filepath.Join(gw.GetConfig().Policies.PolicyPath, polID+".json")

// If it exists, delete it
if _, err := os.Stat(defFilePath); err != nil {
log.Warningf("Error describing named file: %v ", err)
return apiError("Delete failed"), http.StatusInternalServerError
}

if err := os.Remove(defFilePath); err != nil {
log.Warningf("Delete failed: %v", err)
return apiError("Delete failed"), http.StatusInternalServerError
}

response := apiModifyKeySuccess{
Key: polID,
Status: "ok",
Action: "deleted",
}

return response, http.StatusOK
}

func (gw *Gateway) handleGetAPIList() (interface{}, int) {
gw.apisMu.RLock()
defer gw.apisMu.RUnlock()
Expand Down Expand Up @@ -980,43 +884,6 @@ func (gw *Gateway) handleDeleteAPI(apiID string) (interface{}, int) {
return response, http.StatusOK
}

func (gw *Gateway) polHandler(w http.ResponseWriter, r *http.Request) {
polID := mux.Vars(r)["polID"]

var obj interface{}
var code int

switch r.Method {
case http.MethodGet:
if polID != "" {
log.Debug("Requesting policy for", polID)
obj, code = gw.handleGetPolicy(polID)
} else {
log.Debug("Requesting Policy list")
obj, code = gw.handleGetPolicyList()
}
case http.MethodPost:
log.Debug("Creating new definition file")
obj, code = gw.handleAddOrUpdatePolicy(polID, r)
case http.MethodPut:
if polID != "" {
log.Debug("Updating existing Policy: ", polID)
obj, code = gw.handleAddOrUpdatePolicy(polID, r)
} else {
obj, code = apiError("Must specify an apiID to update"), http.StatusBadRequest
}
case http.MethodDelete:
if polID != "" {
log.Debug("Deleting policy for: ", polID)
obj, code = gw.handleDeletePolicy(polID)
} else {
obj, code = apiError("Must specify an apiID to delete"), http.StatusBadRequest
}
}

doJSONWrite(w, code, obj)
}

func (gw *Gateway) apiHandler(w http.ResponseWriter, r *http.Request) {
apiID := mux.Vars(r)["apiID"]

Expand Down Expand Up @@ -1282,7 +1149,7 @@ func (gw *Gateway) handleOrgAddOrUpdate(orgID string, r *http.Request) (interfac
}).Info("New organization key added or updated.")

action := "modified"
if r.Method == http.MethodPost {
if r.Method == "POST" {
action = "added"
}

Expand Down
81 changes: 18 additions & 63 deletions gateway/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,51 +47,6 @@ const apiTestDef = `{
}
}`

const defaultTestPol = `{
"ID": "default-test",
"rate": 1000,
"per": 1,
"quota_max": 100,
"quota_renewal_rate": 60,
"access_rights": {
"41433797848f41a558c1573d3e55a410": {
"api_name": "My API",
"api_id": "41433797848f41a558c1573d3e55a410",
"versions": [
"Default"
]
}
},
"org_id": "54de205930c55e15bd000001",
"hmac_enabled": false
}`

func TestPolicyAPI(t *testing.T) {
ts := StartTest(nil)
globalConf := ts.Gw.GetConfig()
globalConf.Policies.PolicyPath = "."
globalConf.Policies.PolicySource = "file"
ts.Gw.SetConfig(globalConf)

defer ts.Close()
ts.Gw.BuildAndLoadAPI()

_, _ = ts.Run(t, []test.TestCase{
// get non existent policy
{Path: "/tyk/policies/not-here", AdminAuth: true, Method: "GET", BodyMatch: `{"status":"error","message":"Policy not found"}`},
// create Policy
{Path: "/tyk/policies/default-test", AdminAuth: true, Method: "POST", Data: defaultTestPol, BodyMatch: `{"key":"default-test","status":"ok","action":"added"}`},
//update policy with new values
{Path: "/tyk/policies/default-test", AdminAuth: true, Method: "PUT", Data: defaultTestPol, BodyMatch: `{"key":"default-test","status":"ok","action":"modified"}`},
//get by ID
{Path: "/tyk/policies/default-test", AdminAuth: true, Method: "GET", Code: 200},
//delete to clean up
{Path: "/tyk/policies/default-test", AdminAuth: true, Method: "DELETE", BodyMatch: `{"key":"default-test","status":"ok","action":"deleted"}`},
}...)

}

func TestHealthCheckEndpoint(t *testing.T) {
ts := StartTest(nil)
defer ts.Close()
Expand All @@ -102,7 +57,7 @@ func TestHealthCheckEndpoint(t *testing.T) {

ts.Gw.BuildAndLoadAPI()

_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{Path: "/tyk/health/?api_id=test", AdminAuth: true, Code: 200},
{Path: "/tyk/health/?api_id=unknown", AdminAuth: true, Code: 404, BodyMatch: `"message":"API ID not found"`},
}...)
Expand Down Expand Up @@ -224,15 +179,15 @@ func TestKeyHandler(t *testing.T) {
withBadPolicyJSON, _ := json.Marshal(withBadPolicy)

t.Run("Create key", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
// Master keys should be disabled by default
{Method: "POST", Path: "/tyk/keys/create", Data: string(masterKeyJSON), AdminAuth: true, Code: 400, BodyMatch: "Failed to create key, keys must have at least one Access Rights record set."},
{Method: "POST", Path: "/tyk/keys/create", Data: string(withAccessJSON), AdminAuth: true, Code: 200},
}...)
})

t.Run("Create key with policy", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{
Method: "POST",
Path: "/tyk/keys/create",
Expand Down Expand Up @@ -304,7 +259,7 @@ func TestKeyHandler(t *testing.T) {
})

t.Run("Get key", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{Method: "GET", Path: "/tyk/keys/unknown", AdminAuth: true, Code: 404},
{Method: "GET", Path: "/tyk/keys/" + knownKey, AdminAuth: true, Code: 200},
{Method: "GET", Path: "/tyk/keys/" + knownKey + "?api_id=test", AdminAuth: true, Code: 200},
Expand All @@ -313,7 +268,7 @@ func TestKeyHandler(t *testing.T) {
})

t.Run("List keys", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{Method: "GET", Path: "/tyk/keys/", AdminAuth: true, Code: 200, BodyMatch: knownKey},
{Method: "GET", Path: "/tyk/keys/?api_id=test", AdminAuth: true, Code: 200, BodyMatch: knownKey},
{Method: "GET", Path: "/tyk/keys/?api_id=unknown", AdminAuth: true, Code: 200, BodyMatch: knownKey},
Expand Down Expand Up @@ -355,7 +310,7 @@ func TestKeyHandler(t *testing.T) {
})

t.Run("Update key", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
// Without data
{Method: "PUT", Path: "/tyk/keys/" + knownKey, AdminAuth: true, Code: 400},
{Method: "PUT", Path: "/tyk/keys/" + knownKey, Data: string(withAccessJSON), AdminAuth: true, Code: 200},
Expand All @@ -365,7 +320,7 @@ func TestKeyHandler(t *testing.T) {
})

t.Run("Delete key", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{Method: "DELETE", Path: "/tyk/keys/" + knownKey, AdminAuth: true, Code: 200, BodyMatch: `"action":"deleted"`},
{Method: "GET", Path: "/tyk/keys/" + knownKey, AdminAuth: true, Code: 404},
}...)
Expand Down Expand Up @@ -764,7 +719,7 @@ func TestHashKeyHandlerLegacyWithHashFunc(t *testing.T) {
// create session with legacy key format
session := ts.testPrepareBasicAuth(false)

_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{
Method: "POST",
Path: "/tyk/keys/defaultuser",
Expand All @@ -784,7 +739,7 @@ func TestHashKeyHandlerLegacyWithHashFunc(t *testing.T) {
globalConf.HashKeyFunction = storage.HashMurmur64
ts.Gw.SetConfig(globalConf)

_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{
Method: "GET",
Path: "/tyk/keys/defaultuser?username=true&org_id=default",
Expand Down Expand Up @@ -819,7 +774,7 @@ func (ts *Test) testHashKeyHandlerHelper(t *testing.T, expectedHashSize int) {
}

t.Run("Create, get and delete key with key hashing", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
// create key
{
Method: "POST",
Expand Down Expand Up @@ -929,7 +884,7 @@ func (ts *Test) testHashFuncAndBAHelper(t *testing.T) {

session := ts.testPrepareBasicAuth(false)

_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{
Method: "POST",
Path: "/tyk/keys/defaultuser",
Expand Down Expand Up @@ -977,7 +932,7 @@ func TestHashKeyListingDisabled(t *testing.T) {
myKeyHash := storage.HashKey(ts.Gw.generateToken("default", myKey), ts.Gw.GetConfig().HashKeys)

t.Run("Create, get and delete key with key hashing", func(t *testing.T) {
_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
// create key
{
Method: "POST",
Expand Down Expand Up @@ -1160,7 +1115,7 @@ func TestInvalidateCache(t *testing.T) {

ts.Gw.BuildAndLoadAPI()

_, _ = ts.Run(t, []test.TestCase{
ts.Run(t, []test.TestCase{
{Method: "DELETE", Path: "/tyk/cache/test", AdminAuth: true, Code: 200},
{Method: "DELETE", Path: "/tyk/cache/test/", AdminAuth: true, Code: 200},
}...)
Expand Down Expand Up @@ -1286,7 +1241,7 @@ func TestCreateOAuthClient(t *testing.T) {
for testName, testData := range tests {
t.Run(testName, func(t *testing.T) {
requestData, _ := json.Marshal(testData.req)
_, _ = ts.Run(
ts.Run(
t,
test.TestCase{
Method: http.MethodPost,
Expand Down Expand Up @@ -1354,7 +1309,7 @@ func TestUpdateOauthClientHandler(t *testing.T) {
Description: "MyOriginalDescription",
})

_, _ = ts.Run(
ts.Run(
t,
test.TestCase{
Method: http.MethodPost,
Expand Down Expand Up @@ -1427,7 +1382,7 @@ func TestUpdateOauthClientHandler(t *testing.T) {
testCase.BodyNotMatch = testData.bodyNotMatch
}

_, _ = ts.Run(t, testCase)
ts.Run(t, testCase)
})
}
}
Expand Down Expand Up @@ -1627,7 +1582,7 @@ func TestApiLoaderLongestPathFirst(t *testing.T) {
})
}

_, _ = ts.Run(t, testCases...)
ts.Run(t, testCases...)
}

func TestRotateClientSecretHandler(t *testing.T) {
Expand Down Expand Up @@ -1732,7 +1687,7 @@ func TestRotateClientSecretHandler(t *testing.T) {
testCase.BodyNotMatch = testData.bodyNotMatch
}

_, _ = ts.Run(t, testCase)
ts.Run(t, testCase)
})
}
}
Expand Down
Loading

0 comments on commit aaeba77

Please sign in to comment.