Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bearer token #27

Merged
merged 1 commit into from
Oct 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ KIND := $(TOOLS_BIN_DIR)/kind
KUBECTL := $(TOOLS_BIN_DIR)/kubectl

GOLANGCI_LINT_VERSION := "v1.59.0"
CLUSTERCTL_VERSION := "v1.8.3"
CLUSTERCTL_VERSION := "v1.8.4"

KUSTOMIZE_VER := v5.3.0
KUSTOMIZE_BIN := kustomize
Expand Down
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ Please refere to sveltos [documentation](https://projectsveltos.github.io/svelto
## What this repository is
This repo contains a service that exposes all APIs used by Sveltos frontend.

### Authorization Header

Using authorization header is the only way to contact backend as an user, when accessing it over HTTP.
To use authorization header you simply need to pass `Authorization: Bearer <token>` in every request.
To create sample user and to get its token, see [Creating sample user](#how-to-get-token) guide.

### Get ClusterAPI powered clusters

```/capiclusters```
Expand Down Expand Up @@ -260,6 +266,39 @@ returns
}
```

### How to get token

First, create a service account in the desired namespace:

```
kubectl create sa <user> -n <namespace>
```

Give the service account permissions to access the Calico Enterprise Manager UI, and a Calico Enterprise cluster role:

```
kubectl create clusterrolebinding <binding_name> --clusterrole <role_name> --serviceaccount <namespace>:<service_account>
```

where:

- **binding_name** is a descriptive name for the rolebinding.
- **role_name** is one of the default cluster roles (or a custom cluster role) specifying permissions.
- **namespace** is the service account's namespace.
- **service_account** is the service account that the permissions are being associated with.

Next, create a bearer token for the service account. Using the running example of a service account named, sveltos in the _default_ namespace:

```
kubectl create token sveltos --duration=24h
```

it should print somthing like

```
eyJhbGciOiJSUzI1NiIsImtpZCI6IkVsYW8zRU9BMWw3UTZ2QUpjNGFRLXljcTU4M1NhaXBZd1ZNWXJySkVtMTAifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjLmNsdXN0ZXIubG9jYWwiXSwiZXhwIjoxNzI4NzE3NjA0LCJpYXQiOjE3Mjg2MzEyMDQsImlzcyI6Imh0dHBzOi8va3ViZXJuZXRlcy5kZWZhdWx0LnN2Yy5jbHVzdGVyLmxvY2FsIiwianRpIjoiZmQ1OWU4OTctODZlNS00MDQ4LWEwZjAtMDMxYjM5MjVlYjQwIiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJwbGF0Zm9ybSIsInNlcnZpY2VhY2NvdW50Ijp7Im5hbWUiOiJtZ2lhbmx1YyIsInVpZCI6ImJjZWUwZDEwLWM2MTQtNDIzNi1iNmZmLTAyYWU2M2M1MjcxZiJ9fSwibmJmIjoxNzI4NjMxMjA0LCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6cGxhdGZvcm06bWdpYW5sdWMifQ.JlEN38Whyb4mlNsWkC4RAQ82dVUJmWvmdvar7VVxEw2SUgoQthQQPsV-l28bGYpuQspFlsdaO2JRdhm6MGctlMJziweHHm3PNv_RBnFMPRQ01y7ciaRZXE7HEB3sAndvBEQKNWyo4wmmyRnEE2tR79ICQRTLmuWO17MjRIZFChXMHsCsam5OsuE6mE1fj3RSUSbvfRbQwrsTcWOrnYxzquyNVyJyOKxQ97Nm175rez5x9EflHPwueYu5FmNgz3cxMsdkHwkrMnhMqMyNN8WBqKUrju-gPJ9GB-cOcrR_38JyeQBPXYTo9J0tueIWEyaiwKvmPqAsnyHKPT5p-7hFCQ
```

## Contributing

❤️ Your contributions are always welcome! If you want to contribute, have questions, noticed any bug or want to get the latest project news, you can connect with us in the following ways:
Expand Down
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func main() {
go startClusterController(ctx, mgr, setupLog)
go startClusterSummaryController(mgr)

server.InitializeManagerInstance(ctx, mgr.GetClient(), scheme,
server.InitializeManagerInstance(ctx, mgr.GetConfig(), mgr.GetClient(), scheme,
httpPort, ctrl.Log.WithName("gin"))

setupLog.Info("starting manager")
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ require (
k8s.io/client-go v0.31.1
k8s.io/component-base v0.31.1
k8s.io/klog/v2 v2.130.1
sigs.k8s.io/cluster-api v1.8.3
sigs.k8s.io/cluster-api v1.8.4
sigs.k8s.io/controller-runtime v0.19.0
)

Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,8 @@ k8s.io/utils v0.0.0-20240921022957-49e7df575cb6/go.mod h1:OLgZIPagt7ERELqWJFomSt
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.30.3 h1:2770sDpzrjjsAtVhSeUFseziht227YAWYHLGNM8QPwY=
sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.30.3/go.mod h1:Ve9uj1L+deCXFrPOk1LpFXqTg7LCFzFso6PA48q/XZw=
sigs.k8s.io/cluster-api v1.8.3 h1:N6i25rF5QMadwVg2UPfuO6CzmNXjqnF2r1MAO+kcsro=
sigs.k8s.io/cluster-api v1.8.3/go.mod h1:pXv5LqLxuIbhGIXykyNKiJh+KrLweSBajVHHitPLyoY=
sigs.k8s.io/cluster-api v1.8.4 h1:jBKQH1H/HUdUFk8T6qDzIxZJfWw1F5ZP0ZpYQJDmTHs=
sigs.k8s.io/cluster-api v1.8.4/go.mod h1:pXv5LqLxuIbhGIXykyNKiJh+KrLweSBajVHHitPLyoY=
sigs.k8s.io/controller-runtime v0.19.0 h1:nWVM7aq+Il2ABxwiCizrVDSlmDcshi9llbaFbC0ji/Q=
sigs.k8s.io/controller-runtime v0.19.0/go.mod h1:iRmWllt8IlaLjvTTDLhRBXIEtkCK6hwVBJJsYS9Ajf4=
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=
Expand Down
8 changes: 5 additions & 3 deletions internal/controller/sveltoscluster_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ var _ = Describe("SveltosClusterReconciler", func() {

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
server.InitializeManagerInstance(ctx, c, scheme, httpPort, logger)
server.InitializeManagerInstance(ctx, nil, c, scheme, httpPort, logger)

reconciler := getSveltosClusterReconciler(c)

Expand All @@ -89,7 +89,8 @@ var _ = Describe("SveltosClusterReconciler", func() {
}

manager := server.GetManagerInstance()
clusters := manager.GetManagedSveltosClusters()
clusters, err := manager.GetManagedSveltosClusters(context.TODO(), true, randomString())
Expect(err).To(BeNil())
_, ok := clusters[*cluster]
Expect(ok).To(BeTrue())

Expand All @@ -101,7 +102,8 @@ var _ = Describe("SveltosClusterReconciler", func() {
})
Expect(err).ToNot(HaveOccurred())

clusters = manager.GetManagedSveltosClusters()
clusters, err = manager.GetManagedSveltosClusters(context.TODO(), true, randomString())
Expect(err).To(BeNil())
_, ok = clusters[*cluster]
Expect(ok).To(BeFalse())

Expand Down
167 changes: 165 additions & 2 deletions internal/server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package server

import (
"context"
"errors"
"fmt"
"net/http"
"sort"
Expand All @@ -38,6 +39,10 @@ const (
maxItems = 6
)

type Token struct {
Value string `json:"token,omitempty"`
}

var (
ginLogger logr.Logger

Expand All @@ -50,19 +55,40 @@ var (
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("filters: namespace %q name %q labels %q",
filters.Namespace, filters.name, filters.labelSelector))

user, err := validateToken(c)
if err != nil {
return
}

manager := GetManagerInstance()
clusters := manager.GetManagedCAPIClusters()

canListAll, err := manager.canListCAPIClusters(user)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

clusters, err := manager.GetManagedCAPIClusters(c.Request.Context(), canListAll, user)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

managedClusterData := getManagedClusterData(clusters, filters)
sort.Sort(managedClusterData)

result, err := getClustersInRange(managedClusterData, limit, skip)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}

response := ClusterResult{
Expand All @@ -83,19 +109,40 @@ var (
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("filters: namespace %q name %q labels %q",
filters.Namespace, filters.name, filters.labelSelector))

user, err := validateToken(c)
if err != nil {
return
}

manager := GetManagerInstance()
clusters := manager.GetManagedSveltosClusters()

canListAll, err := manager.canListSveltosClusters(user)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

clusters, err := manager.GetManagedSveltosClusters(c.Request.Context(), canListAll, user)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

managedClusterData := getManagedClusterData(clusters, filters)
sort.Sort(managedClusterData)

result, err := getClustersInRange(managedClusterData, limit, skip)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}

response := ClusterResult{
Expand All @@ -116,12 +163,31 @@ var (
limit, skip := getLimitAndSkipFromQuery(c)
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("limit %d skip %d", limit, skip))

user, err := validateToken(c)
if err != nil {
return
}

manager := GetManagerInstance()

canGetCluster, err := manager.canGetCluster(namespace, name, user, clusterType)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

if !canGetCluster {
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("no permissions to access this cluster"))
return
}

helmCharts, err := manager.getHelmChartsForCluster(c.Request.Context(),
namespace, name, clusterType)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
sort.Slice(helmCharts, func(i, j int) bool {
return sortHelmCharts(helmCharts, i, j)
Expand All @@ -131,6 +197,7 @@ var (
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}

response := HelmReleaseResult{
Expand All @@ -150,12 +217,31 @@ var (
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("cluster %s:%s/%s", clusterType, namespace, name))
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("limit %d skip %d", limit, skip))

user, err := validateToken(c)
if err != nil {
return
}

manager := GetManagerInstance()

canGetCluster, err := manager.canGetCluster(namespace, name, user, clusterType)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

if !canGetCluster {
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("no permissions to access this cluster"))
return
}

resources, err := manager.getResourcesForCluster(c.Request.Context(),
namespace, name, clusterType)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}
sort.Slice(resources, func(i, j int) bool {
return sortResources(resources, i, j)
Expand All @@ -165,6 +251,7 @@ var (
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}

response := ResourceResult{
Expand All @@ -186,7 +273,25 @@ var (
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("limit %d skip %d", limit, skip))
ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("failed %t", failedOnly))

user, err := validateToken(c)
if err != nil {
return
}

manager := GetManagerInstance()

canGetCluster, err := manager.canGetCluster(namespace, name, user, clusterType)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to verify permissions %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, err)
return
}

if !canGetCluster {
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("no permissions to access this cluster"))
return
}

clusterProfileStatuses := manager.GetClusterProfileStatusesByCluster(&namespace, &name, clusterType)

flattenedProfileStatuses := flattenProfileStatuses(clusterProfileStatuses, failedOnly)
Expand All @@ -198,6 +303,7 @@ var (
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("bad request %s: %v", c.Request.URL, err))
_ = c.AbortWithError(http.StatusBadRequest, err)
return
}

c.JSON(http.StatusOK, gin.H{
Expand Down Expand Up @@ -357,3 +463,60 @@ func getClusterFromQuery(c *gin.Context) (namespace, name string, clusterType li
c.JSON(http.StatusBadRequest, gin.H{"error": "cluster type is incorrect"})
return
}

func getTokenFromAuthorizationHeader(c *gin.Context) (string, error) {
// Get the authorization header value
authorizationHeader := c.GetHeader("Authorization")

// Check if the authorization header is present
if authorizationHeader == "" {
errorMsg := "authorization header is missing"
c.JSON(http.StatusUnauthorized, gin.H{"error": errorMsg})
return "", errors.New(errorMsg)
}

// Extract the token from the authorization header
// Assuming the authorization header format is "Bearer <token>"
token := authorizationHeader[len("Bearer "):]
// Check if the token is present
if token == "" {
errorMsg := "token is missing"
c.JSON(http.StatusUnauthorized, gin.H{"error": errorMsg})
return "", errors.New(errorMsg)
}

return token, nil
}

// validateToken:
// - gets token from authorization request. Returns an error if missing
// - validate token. Returns an error if this check fails
// - get and return user info. Returns an error if getting user from token fails
func validateToken(c *gin.Context) (string, error) {
token, err := getTokenFromAuthorizationHeader(c)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get token from authorization request. Request %s, error %v",
c.Request.URL, err))
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("failed to get token from authorization request"))
return "", err
}

manager := GetManagerInstance()
err = manager.validateToken(token)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to validate token: %v", err))
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("failed to validate token"))
return "", err
}

user, err := manager.getUserFromToken(token)
if err != nil {
ginLogger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get user from token: %v", err))
_ = c.AbortWithError(http.StatusUnauthorized, errors.New("failed to get user from token"))
return "", err
}

ginLogger.V(logs.LogDebug).Info(fmt.Sprintf("user %s", user))

return user, nil
}
Loading
Loading