From 2eee3781f316a84d9ac5208b49bd1af1a3033b28 Mon Sep 17 00:00:00 2001
From: Yordan Kinkov <yordan.kinkov@vereign.com>
Date: Tue, 15 Nov 2022 09:49:32 +0200
Subject: [PATCH] Apply Authentication middleware to policy service

---
 cmd/policy/main.go        | 10 ++++++++++
 internal/config/config.go |  7 +++++++
 2 files changed, 17 insertions(+)

diff --git a/cmd/policy/main.go b/cmd/policy/main.go
index 0b26b2f9..72d5b57a 100644
--- a/cmd/policy/main.go
+++ b/cmd/policy/main.go
@@ -22,6 +22,7 @@ import (
 	"golang.org/x/oauth2/clientcredentials"
 	"golang.org/x/sync/errgroup"
 
+	"gitlab.com/gaia-x/data-infrastructure-federation-services/tsa/golib/auth"
 	"gitlab.com/gaia-x/data-infrastructure-federation-services/tsa/golib/graceful"
 	goahealth "gitlab.com/gaia-x/data-infrastructure-federation-services/tsa/policy/gen/health"
 	goahealthsrv "gitlab.com/gaia-x/data-infrastructure-federation-services/tsa/policy/gen/http/health/server"
@@ -179,6 +180,15 @@ func main() {
 	// Apply middlewares on the servers
 	policyServer.Evaluate = header.Middleware()(policyServer.Evaluate)
 
+	// Apply Authentication middleware if enabled
+	if cfg.Auth.Enabled {
+		m, err := auth.NewMiddleware(cfg.Auth.JwkURL, cfg.Auth.RefreshInterval, httpClient)
+		if err != nil {
+			logger.Fatal("failed to create authentication middleware", zap.Error(err))
+		}
+		policyServer.Use(m.Handler())
+	}
+
 	// Configure the mux.
 	goapolicysrv.Mount(mux, policyServer)
 	goahealthsrv.Mount(mux, healthServer)
diff --git a/internal/config/config.go b/internal/config/config.go
index c092a9fa..f203bd46 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -13,6 +13,7 @@ type Config struct {
 	OCM         ocmConfig
 	OAuth       oauthConfig
 	Refresher   refresherConfig
+	Auth        authConfig
 
 	LogLevel string `envconfig:"LOG_LEVEL" default:"INFO"`
 }
@@ -66,3 +67,9 @@ type oauthConfig struct {
 type refresherConfig struct {
 	PollInterval time.Duration `envconfig:"REFRESHER_POLL_INTERVAL" default:"10s"`
 }
+
+type authConfig struct {
+	Enabled         bool          `envconfig:"AUTH_ENABLED" default:"true"`
+	JwkURL          string        `envconfig:"AUTH_JWK_URL"`
+	RefreshInterval time.Duration `envconfig:"AUTH_REFRESH_INTERVAL" default:"1h"`
+}
-- 
GitLab