2024-10-27 06:10:27 +01:00
|
|
|
package pkg
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
Copyright 2024 Jonas Kaninda
|
|
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
|
limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
import (
|
|
|
|
|
"github.com/gorilla/mux"
|
2024-11-17 03:56:47 +01:00
|
|
|
"github.com/jkaninda/goma-gateway/internal/metrics"
|
2024-11-15 14:24:35 +01:00
|
|
|
"github.com/jkaninda/goma-gateway/internal/middlewares"
|
2024-11-04 08:48:38 +01:00
|
|
|
"github.com/jkaninda/goma-gateway/pkg/logger"
|
2024-10-27 06:10:27 +01:00
|
|
|
"github.com/jkaninda/goma-gateway/util"
|
2024-11-10 17:06:58 +01:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2024-10-27 06:10:27 +01:00
|
|
|
"time"
|
|
|
|
|
)
|
|
|
|
|
|
2024-11-10 17:06:58 +01:00
|
|
|
func init() {
|
2024-11-17 03:56:47 +01:00
|
|
|
_ = prometheus.Register(metrics.TotalRequests)
|
|
|
|
|
_ = prometheus.Register(metrics.ResponseStatus)
|
|
|
|
|
_ = prometheus.Register(metrics.HttpDuration)
|
2024-11-10 17:06:58 +01:00
|
|
|
}
|
|
|
|
|
|
2024-11-17 05:28:27 +01:00
|
|
|
// Initialize initializes the routes
|
2024-10-27 06:10:27 +01:00
|
|
|
func (gatewayServer GatewayServer) Initialize() *mux.Router {
|
|
|
|
|
gateway := gatewayServer.gateway
|
2024-11-15 14:24:35 +01:00
|
|
|
m := gatewayServer.middlewares
|
2024-11-14 11:38:36 +01:00
|
|
|
redisBased := false
|
|
|
|
|
if len(gateway.Redis.Addr) != 0 {
|
|
|
|
|
redisBased = true
|
|
|
|
|
}
|
2024-11-17 05:28:27 +01:00
|
|
|
// Routes background healthcheck
|
2024-11-12 12:38:34 +01:00
|
|
|
routesHealthCheck(gateway.Routes)
|
2024-11-17 05:28:27 +01:00
|
|
|
|
2024-10-27 06:10:27 +01:00
|
|
|
r := mux.NewRouter()
|
|
|
|
|
heath := HealthCheckRoute{
|
|
|
|
|
DisableRouteHealthCheckError: gateway.DisableRouteHealthCheckError,
|
|
|
|
|
Routes: gateway.Routes,
|
|
|
|
|
}
|
2024-11-10 17:06:58 +01:00
|
|
|
if gateway.EnableMetrics {
|
|
|
|
|
// Prometheus endpoint
|
|
|
|
|
r.Path("/metrics").Handler(promhttp.Handler())
|
|
|
|
|
}
|
2024-11-04 06:52:41 +01:00
|
|
|
// Routes health check
|
|
|
|
|
if !gateway.DisableHealthCheckStatus {
|
|
|
|
|
r.HandleFunc("/healthz", heath.HealthCheckHandler).Methods("GET")
|
2024-11-05 20:11:24 +01:00
|
|
|
r.HandleFunc("/health/routes", heath.HealthCheckHandler).Methods("GET")
|
2024-11-04 06:52:41 +01:00
|
|
|
}
|
2024-11-10 17:06:58 +01:00
|
|
|
|
2024-11-05 20:11:24 +01:00
|
|
|
// Health check
|
|
|
|
|
r.HandleFunc("/health/live", heath.HealthReadyHandler).Methods("GET")
|
2024-10-27 07:24:50 +01:00
|
|
|
r.HandleFunc("/readyz", heath.HealthReadyHandler).Methods("GET")
|
2024-11-06 09:17:21 +01:00
|
|
|
// Enable common exploits
|
|
|
|
|
if gateway.BlockCommonExploits {
|
|
|
|
|
logger.Info("Block common exploits enabled")
|
2024-11-15 14:24:35 +01:00
|
|
|
r.Use(middlewares.BlockExploitsMiddleware)
|
2024-11-06 09:17:21 +01:00
|
|
|
}
|
2024-11-16 10:10:35 +01:00
|
|
|
if gateway.RateLimit != 0 {
|
2024-11-15 14:24:35 +01:00
|
|
|
// Add rate limit middlewares to all routes, if defined
|
|
|
|
|
rateLimit := middlewares.RateLimit{
|
2024-11-17 05:28:27 +01:00
|
|
|
Id: "global_rate", // Generate a unique ID for routes
|
2024-11-14 13:17:28 +01:00
|
|
|
Requests: gateway.RateLimit,
|
|
|
|
|
Window: time.Minute, // requests per minute
|
|
|
|
|
Origins: gateway.Cors.Origins,
|
|
|
|
|
Hosts: []string{},
|
|
|
|
|
RedisBased: redisBased,
|
|
|
|
|
}
|
|
|
|
|
limiter := rateLimit.NewRateLimiterWindow()
|
2024-11-15 14:24:35 +01:00
|
|
|
// Add rate limit middlewares
|
2024-10-27 06:10:27 +01:00
|
|
|
r.Use(limiter.RateLimitMiddleware())
|
|
|
|
|
}
|
2024-11-14 13:17:28 +01:00
|
|
|
for rIndex, route := range gateway.Routes {
|
2024-11-17 05:28:27 +01:00
|
|
|
if len(route.Path) != 0 {
|
|
|
|
|
// Checks if route destination and backend are empty
|
|
|
|
|
if len(route.Destination) == 0 && len(route.Backends) == 0 {
|
2024-11-09 10:59:17 +01:00
|
|
|
logger.Fatal("Route %s : destination or backends should not be empty", route.Name)
|
2024-10-30 16:38:09 +01:00
|
|
|
|
2024-11-09 10:59:17 +01:00
|
|
|
}
|
2024-11-17 05:28:27 +01:00
|
|
|
// Apply middlewares to the route
|
|
|
|
|
for _, middleware := range route.Middlewares {
|
|
|
|
|
if middleware != "" {
|
2024-11-15 14:24:35 +01:00
|
|
|
// Get Access middlewares if it does exist
|
2024-11-17 05:28:27 +01:00
|
|
|
accessMiddleware, err := getMiddleware([]string{middleware}, m)
|
2024-10-30 16:38:09 +01:00
|
|
|
if err != nil {
|
|
|
|
|
logger.Error("Error: %v", err.Error())
|
|
|
|
|
} else {
|
2024-11-15 14:24:35 +01:00
|
|
|
// Apply access middlewares
|
2024-10-30 16:38:09 +01:00
|
|
|
if accessMiddleware.Type == AccessMiddleware {
|
2024-11-15 14:24:35 +01:00
|
|
|
blM := middlewares.AccessListMiddleware{
|
2024-10-30 16:38:09 +01:00
|
|
|
Path: route.Path,
|
|
|
|
|
List: accessMiddleware.Paths,
|
|
|
|
|
}
|
2024-10-30 16:45:13 +01:00
|
|
|
r.Use(blM.AccessMiddleware)
|
2024-10-30 16:38:09 +01:00
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-27 06:10:27 +01:00
|
|
|
}
|
2024-11-15 14:24:35 +01:00
|
|
|
// Get route authentication middlewares if it does exist
|
2024-11-17 05:28:27 +01:00
|
|
|
routeMiddleware, err := getMiddleware([]string{middleware}, m)
|
2024-10-27 06:10:27 +01:00
|
|
|
if err != nil {
|
2024-11-17 05:28:27 +01:00
|
|
|
// Error: middlewares not found
|
2024-10-28 03:41:29 +01:00
|
|
|
logger.Error("Error: %v", err.Error())
|
2024-10-27 06:10:27 +01:00
|
|
|
} else {
|
2024-11-17 05:28:27 +01:00
|
|
|
attachAuthMiddlewares(route, routeMiddleware, gateway, r)
|
2024-10-27 06:10:27 +01:00
|
|
|
}
|
2024-10-27 07:24:50 +01:00
|
|
|
} else {
|
2024-11-15 14:24:35 +01:00
|
|
|
logger.Error("Error, middlewares path is empty")
|
2024-10-27 07:24:50 +01:00
|
|
|
logger.Error("Middleware ignored")
|
2024-10-27 06:10:27 +01:00
|
|
|
}
|
|
|
|
|
}
|
2024-10-27 07:24:50 +01:00
|
|
|
proxyRoute := ProxyRoute{
|
2024-11-12 17:38:55 +01:00
|
|
|
path: route.Path,
|
|
|
|
|
rewrite: route.Rewrite,
|
|
|
|
|
destination: route.Destination,
|
|
|
|
|
backends: route.Backends,
|
|
|
|
|
methods: route.Methods,
|
|
|
|
|
disableHostFording: route.DisableHostFording,
|
|
|
|
|
cors: route.Cors,
|
2024-11-14 22:30:36 +01:00
|
|
|
insecureSkipVerify: route.InsecureSkipVerify,
|
2024-10-27 07:24:50 +01:00
|
|
|
}
|
2024-11-10 14:52:31 +01:00
|
|
|
// create route
|
2024-10-27 07:24:50 +01:00
|
|
|
router := r.PathPrefix(route.Path).Subrouter()
|
2024-11-10 14:52:31 +01:00
|
|
|
// Apply common exploits to the route
|
|
|
|
|
// Enable common exploits
|
|
|
|
|
if route.BlockCommonExploits {
|
|
|
|
|
logger.Info("Block common exploits enabled")
|
2024-11-15 14:24:35 +01:00
|
|
|
router.Use(middlewares.BlockExploitsMiddleware)
|
2024-11-10 14:52:31 +01:00
|
|
|
}
|
2024-11-15 08:19:22 +01:00
|
|
|
id := string(rune(rIndex))
|
|
|
|
|
if len(route.Name) != 0 {
|
|
|
|
|
// Use route name as ID
|
|
|
|
|
id = util.Slug(route.Name)
|
|
|
|
|
}
|
2024-11-10 14:52:31 +01:00
|
|
|
// Apply route rate limit
|
2024-11-16 10:10:35 +01:00
|
|
|
if route.RateLimit != 0 {
|
2024-11-15 14:24:35 +01:00
|
|
|
rateLimit := middlewares.RateLimit{
|
2024-11-15 08:19:22 +01:00
|
|
|
Id: id, // Use route index as ID
|
2024-11-14 13:17:28 +01:00
|
|
|
Requests: route.RateLimit,
|
|
|
|
|
Window: time.Minute, // requests per minute
|
|
|
|
|
Origins: route.Cors.Origins,
|
|
|
|
|
Hosts: route.Hosts,
|
|
|
|
|
RedisBased: redisBased,
|
|
|
|
|
}
|
|
|
|
|
limiter := rateLimit.NewRateLimiterWindow()
|
2024-11-15 14:24:35 +01:00
|
|
|
// Add rate limit middlewares
|
2024-11-10 14:52:31 +01:00
|
|
|
router.Use(limiter.RateLimitMiddleware())
|
|
|
|
|
}
|
2024-10-28 10:10:53 +01:00
|
|
|
// Apply route Cors
|
2024-10-27 07:24:50 +01:00
|
|
|
router.Use(CORSHandler(route.Cors))
|
2024-11-10 07:56:46 +01:00
|
|
|
if len(route.Hosts) > 0 {
|
|
|
|
|
for _, host := range route.Hosts {
|
|
|
|
|
router.Host(host).PathPrefix("").Handler(proxyRoute.ProxyHandler())
|
|
|
|
|
}
|
2024-10-28 04:10:24 +01:00
|
|
|
} else {
|
|
|
|
|
router.PathPrefix("").Handler(proxyRoute.ProxyHandler())
|
|
|
|
|
}
|
2024-11-11 08:50:34 +01:00
|
|
|
if gateway.EnableMetrics {
|
2024-11-17 03:56:47 +01:00
|
|
|
pr := metrics.PrometheusRoute{
|
|
|
|
|
Name: route.Name,
|
|
|
|
|
Path: route.Path,
|
2024-11-11 08:50:34 +01:00
|
|
|
}
|
|
|
|
|
// Prometheus endpoint
|
2024-11-17 03:56:47 +01:00
|
|
|
router.Use(pr.PrometheusMiddleware)
|
2024-11-11 08:50:34 +01:00
|
|
|
}
|
2024-11-15 14:24:35 +01:00
|
|
|
// Apply route Error interceptor middlewares
|
2024-11-14 21:18:07 +01:00
|
|
|
if len(route.InterceptErrors) != 0 {
|
2024-11-15 14:24:35 +01:00
|
|
|
interceptErrors := middlewares.InterceptErrors{
|
2024-11-14 21:18:07 +01:00
|
|
|
Origins: route.Cors.Origins,
|
|
|
|
|
Errors: route.InterceptErrors,
|
|
|
|
|
}
|
|
|
|
|
router.Use(interceptErrors.ErrorInterceptor)
|
2024-11-14 00:26:21 +01:00
|
|
|
}
|
2024-10-27 07:24:50 +01:00
|
|
|
} else {
|
|
|
|
|
logger.Error("Error, path is empty in route %s", route.Name)
|
2024-11-10 07:56:46 +01:00
|
|
|
logger.Error("Route path ignored: %s", route.Path)
|
2024-10-27 07:24:50 +01:00
|
|
|
}
|
2024-10-27 06:10:27 +01:00
|
|
|
}
|
2024-10-28 10:10:53 +01:00
|
|
|
// Apply global Cors middlewares
|
2024-11-15 14:24:35 +01:00
|
|
|
r.Use(CORSHandler(gateway.Cors)) // Apply CORS middlewares
|
|
|
|
|
// Apply errorInterceptor middlewares
|
2024-11-14 21:18:07 +01:00
|
|
|
if len(gateway.InterceptErrors) != 0 {
|
2024-11-15 14:24:35 +01:00
|
|
|
interceptErrors := middlewares.InterceptErrors{
|
2024-11-14 21:18:07 +01:00
|
|
|
Errors: gateway.InterceptErrors,
|
|
|
|
|
Origins: gateway.Cors.Origins,
|
|
|
|
|
}
|
|
|
|
|
r.Use(interceptErrors.ErrorInterceptor)
|
2024-10-29 09:39:31 +01:00
|
|
|
}
|
2024-11-14 21:18:07 +01:00
|
|
|
|
2024-10-27 06:10:27 +01:00
|
|
|
return r
|
|
|
|
|
|
|
|
|
|
}
|
2024-11-17 05:28:27 +01:00
|
|
|
|
|
|
|
|
func attachAuthMiddlewares(route Route, routeMiddleware Middleware, gateway Gateway, r *mux.Router) {
|
|
|
|
|
for _, middlewarePath := range routeMiddleware.Paths {
|
|
|
|
|
proxyRoute := ProxyRoute{
|
|
|
|
|
path: route.Path,
|
|
|
|
|
rewrite: route.Rewrite,
|
|
|
|
|
destination: route.Destination,
|
|
|
|
|
backends: route.Backends,
|
|
|
|
|
disableHostFording: route.DisableHostFording,
|
|
|
|
|
methods: route.Methods,
|
|
|
|
|
cors: route.Cors,
|
|
|
|
|
insecureSkipVerify: route.InsecureSkipVerify,
|
|
|
|
|
}
|
|
|
|
|
secureRouter := r.PathPrefix(util.ParseRoutePath(route.Path, middlewarePath)).Subrouter()
|
|
|
|
|
// Check Authentication middleware types
|
|
|
|
|
switch routeMiddleware.Type {
|
|
|
|
|
case BasicAuth:
|
|
|
|
|
basicAuth, err := getBasicAuthMiddleware(routeMiddleware.Rule)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Error("Error: %s", err.Error())
|
|
|
|
|
} else {
|
|
|
|
|
authBasic := middlewares.AuthBasic{
|
|
|
|
|
Username: basicAuth.Username,
|
|
|
|
|
Password: basicAuth.Password,
|
|
|
|
|
Headers: nil,
|
|
|
|
|
Params: nil,
|
|
|
|
|
}
|
|
|
|
|
// Apply JWT authentication middlewares
|
|
|
|
|
secureRouter.Use(authBasic.AuthMiddleware)
|
|
|
|
|
secureRouter.Use(CORSHandler(route.Cors))
|
|
|
|
|
secureRouter.PathPrefix("/").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
secureRouter.PathPrefix("").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
}
|
|
|
|
|
case JWTAuth:
|
|
|
|
|
jwt, err := getJWTMiddleware(routeMiddleware.Rule)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Error("Error: %s", err.Error())
|
|
|
|
|
} else {
|
|
|
|
|
jwtAuth := middlewares.JwtAuth{
|
|
|
|
|
AuthURL: jwt.URL,
|
|
|
|
|
RequiredHeaders: jwt.RequiredHeaders,
|
|
|
|
|
Headers: jwt.Headers,
|
|
|
|
|
Params: jwt.Params,
|
|
|
|
|
Origins: gateway.Cors.Origins,
|
|
|
|
|
}
|
|
|
|
|
// Apply JWT authentication middlewares
|
|
|
|
|
secureRouter.Use(jwtAuth.AuthMiddleware)
|
|
|
|
|
secureRouter.Use(CORSHandler(route.Cors))
|
|
|
|
|
secureRouter.PathPrefix("/").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
secureRouter.PathPrefix("").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
case OAuth:
|
|
|
|
|
oauth, err := oAuthMiddleware(routeMiddleware.Rule)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Error("Error: %s", err.Error())
|
|
|
|
|
} else {
|
|
|
|
|
redirectURL := "/callback" + route.Path
|
|
|
|
|
if oauth.RedirectURL != "" {
|
|
|
|
|
redirectURL = oauth.RedirectURL
|
|
|
|
|
}
|
|
|
|
|
amw := middlewares.Oauth{
|
|
|
|
|
ClientID: oauth.ClientID,
|
|
|
|
|
ClientSecret: oauth.ClientSecret,
|
|
|
|
|
RedirectURL: redirectURL,
|
|
|
|
|
Scopes: oauth.Scopes,
|
|
|
|
|
Endpoint: middlewares.OauthEndpoint{
|
|
|
|
|
AuthURL: oauth.Endpoint.AuthURL,
|
|
|
|
|
TokenURL: oauth.Endpoint.TokenURL,
|
|
|
|
|
UserInfoURL: oauth.Endpoint.UserInfoURL,
|
|
|
|
|
},
|
|
|
|
|
State: oauth.State,
|
|
|
|
|
Origins: gateway.Cors.Origins,
|
|
|
|
|
JWTSecret: oauth.JWTSecret,
|
|
|
|
|
Provider: oauth.Provider,
|
|
|
|
|
}
|
|
|
|
|
oauthRuler := oauthRulerMiddleware(amw)
|
|
|
|
|
// Check if a cookie path is defined
|
|
|
|
|
if oauthRuler.CookiePath == "" {
|
|
|
|
|
oauthRuler.CookiePath = route.Path
|
|
|
|
|
}
|
|
|
|
|
// Check if a RedirectPath is defined
|
|
|
|
|
if oauthRuler.RedirectPath == "" {
|
|
|
|
|
oauthRuler.RedirectPath = util.ParseRoutePath(route.Path, middlewarePath)
|
|
|
|
|
}
|
|
|
|
|
if oauthRuler.Provider == "" {
|
|
|
|
|
oauthRuler.Provider = "custom"
|
|
|
|
|
}
|
|
|
|
|
secureRouter.Use(amw.AuthMiddleware)
|
|
|
|
|
secureRouter.Use(CORSHandler(route.Cors))
|
|
|
|
|
secureRouter.PathPrefix("/").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
secureRouter.PathPrefix("").Handler(proxyRoute.ProxyHandler()) // Proxy handler
|
|
|
|
|
// Callback route
|
|
|
|
|
r.HandleFunc(util.UrlParsePath(redirectURL), oauthRuler.callbackHandler).Methods("GET")
|
|
|
|
|
}
|
|
|
|
|
default:
|
|
|
|
|
if !doesExist(routeMiddleware.Type) {
|
|
|
|
|
logger.Error("Unknown middlewares type %s", routeMiddleware.Type)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|