From c228c605ef015111dafe89ca7506b4764b0f38a5 Mon Sep 17 00:00:00 2001 From: Jonas Kaninda Date: Wed, 30 Oct 2024 18:01:53 +0100 Subject: [PATCH] refactor: refatcoring code --- README.md | 71 +++++++++++------------------ goma.yml | 68 +++++++++++---------------- internal/logger/logger.go | 4 +- pkg/config.go | 6 --- pkg/middleware/access-middleware.go | 2 +- pkg/middleware/middleware.go | 2 +- util/constants.go | 2 +- 7 files changed, 58 insertions(+), 97 deletions(-) diff --git a/README.md b/README.md index 413d603..43de580 100644 --- a/README.md +++ b/README.md @@ -145,46 +145,12 @@ gateway: Access-Control-Allow-Headers: 'Origin, Authorization, Accept, Content-Type, Access-Control-Allow-Headers, X-Client-Id, X-Session-Id' Access-Control-Allow-Credentials: 'true' Access-Control-Max-Age: 1728000 - #### Define route blocklist paths - blocklist: - - /swagger-ui/* - - /v2/swagger-ui/* - - /api-docs/* - - /internal/* - - /actuator/* ##### Define route middlewares from middlewares names ## The name must be unique ## List of middleware name middlewares: - # path to protect - - path: /user - # Rules defines which specific middleware applies to a route path - rules: - - basic-auth - # path to protect - - path: /path-example - # Rules defines which specific middleware applies to a route path - rules: - - jwt - # path to protect - - path: /admin - # Rules defines which specific middleware applies to a route path - rules: - - basic-auth - # path to protect - - path: /path-example - # Rules defines which specific middleware applies to a route path - rules: - - jwt - - path: /history - http: - url: http://security-service:8080/security/authUser - headers: - #Key from backend authentication header, and inject to the request with custom key name - userId: X-Auth-UserId - userCountryId: X-Auth-UserCountryId - params: - userCountryId: X-countryId + - api-forbidden-paths + - basic-auth # Example of a route | 2 - name: Authentication service path: /auth @@ -192,8 +158,8 @@ gateway: destination: 'http://security-service:8080' healthCheck: /internal/health/ready cors: {} - blocklist: [] - middlewares: [] + middlewares: + - api-forbidden-paths # Example of a route | 3 - name: Basic auth path: /protected @@ -201,7 +167,6 @@ gateway: destination: 'http://notification-service:8080' healthCheck: cors: {} - blocklist: [] middlewares: [] #Defines proxy middlewares @@ -210,6 +175,10 @@ middlewares: - name: basic-auth # Authentication types | jwt, basic, OAuth type: basic + paths: + - /user + - /admin + - /account rule: username: admin password: admin @@ -218,6 +187,10 @@ middlewares: # Authentication types | jwt, basic, OAuth # jwt authorization based on the result of backend's response and continue the request when the client is authorized type: jwt + # Paths to protect + paths: + - /protected-access + - /example-of-jwt rule: # This is an example URL url: https://www.googleapis.com/auth/userinfo.email @@ -234,12 +207,22 @@ middlewares: # Add header to the next request from AuthRequest header, depending on your requirements # Key is AuthRequest's response header Key, and value is Request's header Key # In case you want to get headers from the Authentication service and inject them into the next request's headers - headers: - userId: X-Auth-UserId - userCountryId: X-Auth-UserCountryId + headers: + userId: X-Auth-UserId + userCountryId: X-Auth-UserCountryId # In case you want to get headers from the Authentication service and inject them to the next request's params - params: - userCountryId: countryId + params: + userCountryId: countryId + # The server will return 404 + - name: api-forbidden-paths + type: access + ## Forbidden paths + paths: + - /swagger-ui/* + - /v2/swagger-ui/* + - /api-docs/* + - /internal/* + - /actuator/* ``` ## Requirement diff --git a/goma.yml b/goma.yml index 7abc163..e158515 100644 --- a/goma.yml +++ b/goma.yml @@ -66,46 +66,12 @@ gateway: Access-Control-Allow-Headers: 'Origin, Authorization, Accept, Content-Type, Access-Control-Allow-Headers, X-Client-Id, X-Session-Id' Access-Control-Allow-Credentials: 'true' Access-Control-Max-Age: 1728000 - #### Define route blocklist paths - blocklist: - - /swagger-ui/* - - /v2/swagger-ui/* - - /api-docs/* - - /internal/* - - /actuator/* ##### Define route middlewares from middlewares names ## The name must be unique ## List of middleware name middlewares: - # path to protect - - path: /user - # Rules defines which specific middleware applies to a route path - rules: - - basic-auth - # path to protect - - path: /path-example - # Rules defines which specific middleware applies to a route path - rules: - - jwt - # path to protect - - path: /admin - # Rules defines which specific middleware applies to a route path - rules: - - basic-auth - # path to protect - - path: /path-example - # Rules defines which specific middleware applies to a route path - rules: - - jwt - - path: /history - http: - url: http://security-service:8080/security/authUser - headers: - #Key from backend authentication header, and inject to the request with custom key name - userId: X-Auth-UserId - userCountryId: X-Auth-UserCountryId - params: - userCountryId: X-countryId + - api-forbidden-paths + - basic-auth # Example of a route | 2 - name: Authentication service path: /auth @@ -113,8 +79,8 @@ gateway: destination: 'http://security-service:8080' healthCheck: /internal/health/ready cors: {} - blocklist: [] - middlewares: [] + middlewares: + - api-forbidden-paths # Example of a route | 3 - name: Basic auth path: /protected @@ -122,15 +88,19 @@ gateway: destination: 'http://notification-service:8080' healthCheck: cors: {} - blocklist: [] middlewares: [] #Defines proxy middlewares +# middleware name must be unique middlewares: # Enable Basic auth authorization based - name: basic-auth # Authentication types | jwt, basic, OAuth type: basic + paths: + - /user + - /admin + - /account rule: username: admin password: admin @@ -139,6 +109,10 @@ middlewares: # Authentication types | jwt, basic, OAuth # jwt authorization based on the result of backend's response and continue the request when the client is authorized type: jwt + # Paths to protect + paths: + - /protected-access + - /example-of-jwt rule: # This is an example URL url: https://www.googleapis.com/auth/userinfo.email @@ -155,9 +129,19 @@ middlewares: # Add header to the next request from AuthRequest header, depending on your requirements # Key is AuthRequest's response header Key, and value is Request's header Key # In case you want to get headers from the Authentication service and inject them into the next request's headers - headers: + headers: userId: X-Auth-UserId userCountryId: X-Auth-UserCountryId # In case you want to get headers from the Authentication service and inject them to the next request's params - params: - userCountryId: countryId \ No newline at end of file + params: + userCountryId: countryId +# The server will return 404 + - name: api-forbidden-paths + type: access + ## Forbidden paths + paths: + - /swagger-ui/* + - /v2/swagger-ui/* + - /api-docs/* + - /internal/* + - /actuator/* \ No newline at end of file diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 26abe18..04d4426 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -77,9 +77,9 @@ func Debug(msg string, args ...interface{}) { log.SetOutput(getStd(util.GetStringEnv("GOMA_ACCESS_LOG", "/dev/stdout"))) formattedMessage := fmt.Sprintf(msg, args...) if len(args) == 0 { - log.Printf("DUBUG: %s\n", msg) + log.Printf("DEBUG: %s\n", msg) } else { - log.Printf("DUBUG: %s\n", formattedMessage) + log.Printf("DEBUG: %s\n", formattedMessage) } } func getStd(out string) *os.File { diff --git a/pkg/config.go b/pkg/config.go index 17e0cfa..6885149 100644 --- a/pkg/config.go +++ b/pkg/config.go @@ -103,12 +103,6 @@ type Middleware struct { type MiddlewareName struct { name string `yaml:"name"` } -type RouteMiddleware struct { - //Path contains the path to protect - Path string `yaml:"path"` - //Rules defines which specific middleware applies to a route path - Rules []string `yaml:"rules"` -} // Route defines gateway route type Route struct { diff --git a/pkg/middleware/access-middleware.go b/pkg/middleware/access-middleware.go index decd703..500f201 100644 --- a/pkg/middleware/access-middleware.go +++ b/pkg/middleware/access-middleware.go @@ -30,7 +30,7 @@ func (blockList AccessListMiddleware) AccessMiddleware(next http.Handler) http.H return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { for _, block := range blockList.List { if isPathBlocked(r.URL.Path, util.ParseURLPath(blockList.Path+block)) { - logger.Warn("%s: access to %s is forbidden", getRealIP(r), r.URL.Path) + logger.Debug("%s: access to %s is forbidden", getRealIP(r), r.URL.Path) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusNotFound) err := json.NewEncoder(w).Encode(ProxyResponseError{ diff --git a/pkg/middleware/middleware.go b/pkg/middleware/middleware.go index 04433fe..e30d6cc 100644 --- a/pkg/middleware/middleware.go +++ b/pkg/middleware/middleware.go @@ -162,7 +162,7 @@ func (jwtAuth JwtAuth) AuthMiddleware(next http.Handler) http.Handler { client := &http.Client{} authResp, err := client.Do(authReq) if err != nil || authResp.StatusCode != http.StatusOK { - logger.Info("%s %s %s %s", r.Method, r.RemoteAddr, r.URL, r.UserAgent()) + logger.Info("%s %s %s %s", r.Method, getRealIP(r), r.URL, r.UserAgent()) logger.Warn("Proxy authentication error") w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusUnauthorized) diff --git a/util/constants.go b/util/constants.go index e003539..5a15dff 100644 --- a/util/constants.go +++ b/util/constants.go @@ -30,6 +30,6 @@ func FullVersion() string { return ver } -const MainExample = "Initialize config: init config --output config.yml\n" + +const MainExample = "Initialize config: config init --output config.yml\n" + "Start server: server \n" + "Start server with custom config file: server --config config.yml"