Skip to content

Commit 0317bb9

Browse files
Add health endpoints on the order and stocks service
1 parent a580ff5 commit 0317bb9

File tree

9 files changed

+62
-21
lines changed

9 files changed

+62
-21
lines changed

deploy/alpha-stocks-dev/deploy.sh

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,5 @@ envsubst < ./deployments/gateway-deployment.yaml | kubectl apply -f -
1717

1818
if [ "$ENABLE_TRATS" = "true" ]; then
1919
kubectl apply -f tratteria/kubernetes
20-
fi
21-
22-
23-
if [ "$ENABLE_TRATS" = "true" ]; then
24-
sleep 20
2520
kubectl apply -f trats
2621
fi

order/cmd/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ func main() {
8686
}
8787

8888
func (a *App) initializeRoutes(handlers *handler.Handlers) {
89+
a.Router.HandleFunc("/health", handlers.HealthCheckHandler).Methods("GET")
8990
a.Router.HandleFunc("/api/order", handlers.OrderHandler).Methods("POST")
9091
a.Router.HandleFunc("/api/order/{id}", handlers.GetOrderDetailsHandler).Methods("GET")
9192
}

order/handler/handler.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ type OrderRequest struct {
3232
Quantity int `json:"quantity"`
3333
}
3434

35+
func (h *Handlers) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
36+
h.Logger.Info("Health check request received.")
37+
38+
w.WriteHeader(http.StatusOK)
39+
w.Header().Set("Content-Type", "application/json")
40+
w.Write([]byte(`{"status":"healthy"}`))
41+
}
42+
3543
func (h *Handlers) OrderHandler(w http.ResponseWriter, r *http.Request) {
3644
h.Logger.Info("Order request received.")
3745

order/pkg/authz/policies.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ import (
77
"github.com/spiffe/go-spiffe/v2/spiffeid"
88
)
99

10+
func GetPublicEndpoints() []string {
11+
return []string{
12+
"/health",
13+
}
14+
}
15+
1016
func GetSpiffeAccessControlPolicies(orderConfig *config.OrderConfig) map[spiffeid.ID]map[string][]string {
1117
return map[spiffeid.ID]map[string][]string{
1218
orderConfig.SpiffeIDs.Gateway: {

order/pkg/middleware/spiffemiddleware.go

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"net/http"
5+
"slices"
56
"strings"
67

78
"github.com/gorilla/mux"
@@ -14,10 +15,25 @@ import (
1415
)
1516

1617
func spiffeMiddleware(orderConfig *config.OrderConfig, spireJwtSource *workloadapi.JWTSource, logger *zap.Logger) func(http.Handler) http.Handler {
18+
publicEndpoints := authz.GetPublicEndpoints()
1719
policies := authz.GetSpiffeAccessControlPolicies(orderConfig)
1820

1921
return func(next http.Handler) http.Handler {
2022
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
routePath, err := mux.CurrentRoute(r).GetPathTemplate()
24+
if err != nil {
25+
logger.Error("Error retrieving the route path template:", zap.Error(err))
26+
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
27+
28+
return
29+
}
30+
31+
if slices.Contains(publicEndpoints, routePath) {
32+
next.ServeHTTP(w, r)
33+
34+
return
35+
}
36+
2137
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
2238
if token == "" {
2339
logger.Error("JWT-SVID token not provided.")
@@ -36,14 +52,6 @@ func spiffeMiddleware(orderConfig *config.OrderConfig, spireJwtSource *workloada
3652

3753
logger.Info("Successfully authenticated a request.", zap.String("spiffeID", svid.ID.String()))
3854

39-
routePath, err := mux.CurrentRoute(r).GetPathTemplate()
40-
if err != nil {
41-
logger.Error("Error retrieving the route path template:", zap.Error(err))
42-
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
43-
44-
return
45-
}
46-
4755
if !authz.IsSpiffeIDAuthorized(svid.ID, r.Method, routePath, policies) {
4856
logger.Error("Unauthorized access attempt.", zap.String("spiffeID", svid.ID.String()), zap.String("path", routePath), zap.String("method", r.Method))
4957
http.Error(w, "Forbidden: Access not permited to the resource", http.StatusForbidden)

stocks/cmd/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ func main() {
8484
}
8585

8686
func (a *App) initializeRoutes(handlers *handler.Handlers) {
87+
a.Router.HandleFunc("/health", handlers.HealthCheckHandler).Methods("GET")
8788
a.Router.HandleFunc("/api/stocks/search", handlers.SearchStocksHandler).Methods("GET")
8889
a.Router.HandleFunc("/api/stocks/holdings", handlers.GetUserHoldingsHandler).Methods("GET")
8990
a.Router.HandleFunc("/api/stocks/details/{id}", handlers.GetStockDetailsHandler).Methods("GET")

stocks/handler/handler.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ type UpdateRequest struct {
3838
Quantity int `json:"quantity"`
3939
}
4040

41+
func (h *Handlers) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
42+
h.Logger.Info("Health check request received.")
43+
44+
w.WriteHeader(http.StatusOK)
45+
w.Header().Set("Content-Type", "application/json")
46+
w.Write([]byte(`{"status":"healthy"}`))
47+
}
48+
4149
func (h *Handlers) SearchStocksHandler(w http.ResponseWriter, r *http.Request) {
4250
query := r.URL.Query().Get("query")
4351
if query == "" {

stocks/pkg/authz/policies.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ import (
77
"github.com/spiffe/go-spiffe/v2/spiffeid"
88
)
99

10+
func GetPublicEndpoints() []string {
11+
return []string{
12+
"/health",
13+
}
14+
}
15+
1016
func GetSpiffeAccessControlPolicies(stocksConfig *config.StocksConfig) map[spiffeid.ID]map[string][]string {
1117
return map[spiffeid.ID]map[string][]string{
1218
stocksConfig.SpiffeIDs.Gateway: {

stocks/pkg/middleware/spiffemiddleware.go

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"net/http"
5+
"slices"
56
"strings"
67

78
"github.com/gorilla/mux"
@@ -14,10 +15,25 @@ import (
1415
)
1516

1617
func getSpiffeMiddleware(stocksConfig *config.StocksConfig, spireJwtSource *workloadapi.JWTSource, logger *zap.Logger) func(http.Handler) http.Handler {
18+
publicEndpoints := authz.GetPublicEndpoints()
1719
policies := authz.GetSpiffeAccessControlPolicies(stocksConfig)
1820

1921
return func(next http.Handler) http.Handler {
2022
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
routePath, err := mux.CurrentRoute(r).GetPathTemplate()
24+
if err != nil {
25+
logger.Error("Error retrieving the route path template:", zap.Error(err))
26+
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
27+
28+
return
29+
}
30+
31+
if slices.Contains(publicEndpoints, routePath) {
32+
next.ServeHTTP(w, r)
33+
34+
return
35+
}
36+
2137
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
2238
if token == "" {
2339
logger.Error("JWT-SVID token not provided.")
@@ -36,14 +52,6 @@ func getSpiffeMiddleware(stocksConfig *config.StocksConfig, spireJwtSource *work
3652

3753
logger.Info("Successfully authenticated a request.", zap.String("spiffeID", svid.ID.String()))
3854

39-
routePath, err := mux.CurrentRoute(r).GetPathTemplate()
40-
if err != nil {
41-
logger.Error("Error retrieving the route path template:", zap.Error(err))
42-
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
43-
44-
return
45-
}
46-
4755
if !authz.IsSpiffeIDAuthorized(svid.ID, r.Method, routePath, policies) {
4856
logger.Error("Unauthorized access attempt", zap.String("spiffeID", svid.ID.String()), zap.String("path", routePath), zap.String("method", r.Method))
4957
http.Error(w, "Forbidden: Access not permited to the resource", http.StatusForbidden)

0 commit comments

Comments
 (0)