Closed buger closed 1 month ago
API Changes
--- prev.txt 2024-06-26 09:20:42.370330174 +0000
+++ current.txt 2024-06-26 09:20:39.414303248 +0000
@@ -8234,6 +8234,12 @@
func (gw *Gateway) NotifyCurrentServerStatus()
+func (gw *Gateway) PolicyByID(polID string) (user.Policy, bool)
+
+func (gw *Gateway) PolicyCount() int
+
+func (gw *Gateway) PolicyIDs() []string
+
func (gw *Gateway) ProcessOauthClientsOps(clients map[string]string)
ProcessOauthClientsOps performs the appropriate action for the received
clients it can be any of the Create,Update and Delete operations
@@ -9522,6 +9528,10 @@
TickOk triggers a reload and ensures a queue happened and a reload cycle
happens. This will block until all the cases are met.
+type Repository interface {
+ policy.Repository
+}
+
type RequestDefinition struct {
Method string `json:"method"`
Headers map[string]string `json:"headers"`
@@ -12032,10 +12042,6 @@
func (limit APILimit) IsEmpty() bool
-func (g *APILimit) Less(in APILimit) bool
- Less will return true if the receiver has a smaller duration between
- requests than `in`.
-
type AccessDefinition struct {
APIName string `json:"api_name" msg:"api_name"`
APIID string `json:"api_id" msg:"api_id"`
β±οΈ Estimated effort to review [1-5] | 4 |
π§ͺ Relevant tests | Yes |
π Security concerns | No |
β‘ Key issues to review |
Possible Bug: The refactoring of the ApplyPolicies function into the new policy package might introduce issues if not all edge cases are handled properly. The logic is complex and the changes are significant, so careful review of the new policy.Service implementation and its interaction with existing systems is crucial. |
Performance Concern: The new implementation locks and unlocks the mutex multiple times within loops in several functions such as PolicyIDs and PolicyByID . This could lead to performance degradation, especially under high load. Consider optimizing the locking strategy. |
Category | Suggestion | Score |
Possible bug |
Add nil checks to prevent potential runtime errors from nil pointer dereferences___ **To prevent potential nil pointer dereferences, add checks for nil before dereferencingpointers such as orgID and logger in the Service struct methods.**
[internal/policy/apply.go [112-116]](https://github.com/TykTechnologies/tyk/pull/6372/files#diff-59b92e9d31f142f1d99b746eb3ff7db4e26bf6c3044c9b87b58034a947ee04d1R112-R116)
```diff
-if t.orgID != nil && policy.OrgID != *t.orgID {
+if t.orgID == nil {
+ return errors.New("orgID is nil")
+}
+if policy.OrgID != *t.orgID {
err := errors.New("attempting to apply policy from different organisation to key, skipping")
t.Logger().Error(err)
return err
}
```
Suggestion importance[1-10]: 10Why: This suggestion addresses a potential bug by adding nil checks, which is crucial for preventing runtime errors and ensuring the robustness of the code. | 10 |
Add nil check for
___
**Consider checking if | 8 | |
Add nil checks for
___
**Consider handling the case where | 8 | |
Maintainability |
Refactor the
___
**Refactor the | 9 |
Encapsulate the logic for merging
___
**Consider implementing a method to handle the merging of | 8 | |
Improve error handling in the policy application process for better control and testing___ **Replace the direct error logging within theApply method with a more structured error handling approach that allows for better control and testing. Instead of logging and returning errors immediately, accumulate errors in a slice and handle them collectively after the policy application loop.** [internal/policy/apply.go [102-108]](https://github.com/TykTechnologies/tyk/pull/6372/files#diff-59b92e9d31f142f1d99b746eb3ff7db4e26bf6c3044c9b87b58034a947ee04d1R102-R108) ```diff -err := fmt.Errorf("policy not found: %q", polID) -t.Logger().Error(err) -if len(policyIDs) > 1 { - continue +var errs []error +errs = append(errs, fmt.Errorf("policy not found: %q", polID)) +if len(policyIDs) == 1 { + return fmt.Errorf("errors encountered: %v", errs) } -return err ``` Suggestion importance[1-10]: 7Why: The suggestion improves error handling by accumulating errors and handling them collectively, which enhances maintainability and testability. However, it introduces complexity that may not be necessary for all use cases. | 7 | |
Simplify policy ID check by handling it inside the
___
**Refactor the condition to check the policy ID directly in the | 5 | |
Best practice |
Add thread safety to the
___
**Implement concurrency protection for the | 9 |
Enhancement |
Use dependency injection for the policy store___ **Instead of creating a new policy store in each call toApplyPolicies , consider using a dependency injection to provide the policy store, which can improve testability and reduce coupling.** [gateway/middleware.go [357-358]](https://github.com/TykTechnologies/tyk/pull/6372/files#diff-703054910891a4db633eca0f42ed779d6b4fa75cd9b3aa4c503e681364201c1bR357-R358) ```diff -store := policy.New(orgID, t.Gw, log) -return store.Apply(session) +return t.policyStore.Apply(session) ``` Suggestion importance[1-10]: 7Why: Using dependency injection can improve testability and reduce coupling, which are good practices for maintainable code. However, this change is more of an enhancement rather than a critical fix. | 7 |
Enhance the test assertions to cover changes to both
___
**To ensure that the | 7 | |
Enhance error message clarity in rate limit handling___ **The error message inhandleRateLimitFailure should provide more context about the failure. Consider including the rateLimitKey in the error message.**
[gateway/middleware.go [525]](https://github.com/TykTechnologies/tyk/pull/6372/files#diff-703054910891a4db633eca0f42ed779d6b4fa75cd9b3aa4c503e681364201c1bR525-R525)
```diff
-return errors.New(message), http.StatusTooManyRequests
+return errors.New(fmt.Sprintf("%s - Key: %s", message, rateLimitKey)), http.StatusTooManyRequests
```
Suggestion importance[1-10]: 6Why: Providing more context in error messages can be helpful for debugging and understanding issues. This suggestion improves the clarity of the error message but is not crucial for functionality. | 6 | |
Performance |
Optimize the
___
**The | 6 |
Failed conditions
30.0% Coverage on New Code (required β₯ 80%)
C Reliability Rating on New Code (required β₯ A)
See analysis details on SonarCloud
Catch issues before they fail your Quality Gate with our IDE extension SonarLint
User description
TT-12454 Extract ApplyPolicies into internal/policy scope (#6367)
User description
This extracts a large problematic
ApplyPolicies
function into it's own package scope. It does this by:On top of that:
The duration was calculated as rate/per, however, the correct way was per/rate; This fixes it so duration is calculated correctly, fixing the Less function comparison.
PR Type
Enhancement, Bug fix
Description
handleGetPolicy
to use the newPolicyByID
method.Repository
interface and added methodsPolicyIDs
,PolicyByID
, andPolicyCount
to theGateway
struct.ApplyPolicies
inBaseMiddleware
to use the newpolicy
package.buildNodeInfo
to usePolicyCount
instead ofpoliciesByIDLen
.getPolicy
andpoliciesByIDLen
fromGateway
.Changes walkthrough π
api.go
Refactor policy retrieval in `handleGetPolicy`.
gateway/api.go - Replaced `getPolicy` with `PolicyByID` in `handleGetPolicy`.
gateway.go
Add policy-related methods and interface to Gateway.
gateway/gateway.go
Repository
interface.PolicyIDs
,PolicyByID
, andPolicyCount
.middleware.go
Refactor ApplyPolicies to use new policy store.
gateway/middleware.go
clearSession
method.ApplyPolicies
to usepolicy.New
andstore.Apply
.rpc_storage_handler.go
Update policy count retrieval in buildNodeInfo.
gateway/rpc_storage_handler.go - Replaced `policiesByIDLen` with `PolicyCount` in `buildNodeInfo`.
server.go
Remove redundant policy methods from Gateway.
gateway/server.go - Removed `getPolicy` and `policiesByIDLen` methods.
Co-authored-by: Tit Petric tit@tyk.io
PR Type
Enhancement, Bug fix, Tests
Description
handleGetPolicy
to use the newPolicyByID
method.Repository
interface and added methodsPolicyIDs
,PolicyByID
, andPolicyCount
to theGateway
struct.ApplyPolicies
inBaseMiddleware
to use the newpolicy
package.buildNodeInfo
to usePolicyCount
instead ofpoliciesByIDLen
.getPolicy
andpoliciesByIDLen
fromGateway
.Duration
method ofAPILimit
.ApplyRateLimits
andApply
methods in thepolicy
package.Changes walkthrough π
10 files
api.go
Refactor `handleGetPolicy` to use `PolicyByID` method
gateway/api.go - Refactored `handleGetPolicy` to use `PolicyByID` method.
gateway.go
Introduce `Repository` interface and methods in `Gateway`
gateway/gateway.go
Repository
interface.PolicyIDs
,PolicyByID
, andPolicyCount
toGateway
.middleware.go
Refactor `ApplyPolicies` to use new `policy` package
gateway/middleware.go
ApplyPolicies
to use the newpolicy
package.clearSession
method.mw_rate_limiting.go
Update error message in `handleRateLimitFailure`
gateway/mw_rate_limiting.go - Updated error message in `handleRateLimitFailure`.
rpc_storage_handler.go
Refactor `buildNodeInfo` to use `PolicyCount` method
gateway/rpc_storage_handler.go - Refactored `buildNodeInfo` to use `PolicyCount` method.
server.go
Remove redundant methods from `Gateway`
gateway/server.go - Removed `getPolicy` and `policiesByIDLen` methods.
event.go
Remove `RateLimitExceeded` event from `eventMap`
internal/event/event.go - Removed `RateLimitExceeded` event from `eventMap`.
apply.go
Extract `ApplyPolicies` logic into `policy` package
internal/policy/apply.go
ApplyPolicies
logic intopolicy
package.Service
struct and methodsClearSession
andApply
.store.go
Introduce `Store` struct implementing `Repository` interface
internal/policy/store.go - Introduced `Store` struct implementing `Repository` interface.
util.go
Add utility functions for policy handling
internal/policy/util.go - Added utility functions for policy handling.
5 files
policy_test.go
Update tests to use `PolicyByID` method
gateway/policy_test.go - Updated tests to use `PolicyByID` method.
server_test.go
Update tests to use `PolicyCount` method
gateway/server_test.go - Updated tests to use `PolicyCount` method.
event_test.go
Update test to use `RateLimitSmoothingUp` event
internal/event/event_test.go - Updated test to use `RateLimitSmoothingUp` event.
apply_test.go
Add tests for `ApplyRateLimits` and `Apply` methods
internal/policy/apply_test.go
ApplyRateLimits
andApply
methods inpolicy
package.session_test.go
Update tests for `Duration` method and remove `Less` method tests
user/session_test.go
Duration
method ofAPILimit
.Less
method.1 files
session.go
Fix bug in `Duration` method and remove `Less` method
user/session.go
Duration
method ofAPILimit
.Less
method fromAPILimit
.1 files
Taskfile.yml
Add Taskfile for running tests and coverage
internal/policy/Taskfile.yml - Added Taskfile for running tests and coverage.