Skip to content

Commit

Permalink
Merge pull request #271 from grycap/micafer_dev
Browse files Browse the repository at this point in the history
Add tests
  • Loading branch information
micafer authored Nov 22, 2024
2 parents c389373 + eca1436 commit 75d862f
Show file tree
Hide file tree
Showing 9 changed files with 664 additions and 5 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ require (

require (
github.com/fatih/color v1.14.1 // indirect
github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/rs/xid v1.4.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ github.com/goccy/go-yaml v1.9.8/go.mod h1:JubOolP3gh0HpiBc4BLRD4YmjEjHAmIIB2aaXK
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down
2 changes: 1 addition & 1 deletion pkg/handlers/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func TestMakeUpdateHandler(t *testing.T) {
}
}
},
"allowed_users": ["user1", "user2"]
"allowed_users": ["[email protected]", "[email protected]"]
}
`)
req, _ := http.NewRequest("PUT", "/system/services", body)
Expand Down
140 changes: 140 additions & 0 deletions pkg/types/expose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
appsv1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
corev1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
testclient "k8s.io/client-go/kubernetes/fake"
Expand Down Expand Up @@ -229,3 +230,142 @@ func TestHortizontalAutoScaleSpec(t *testing.T) {
t.Errorf("Expected target cpu 40 but got %d", res.Spec.TargetCPUUtilizationPercentage)
}
}

func TestListIngress(t *testing.T) {

K8sObjects := []runtime.Object{
&netv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "service-ing",
Namespace: "namespace",
},
},
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

_, err := listIngress(kubeClientset, cfg)

if err != nil {
t.Errorf("Error listing ingresses: %v", err)
}
}

func TestUpdateIngress(t *testing.T) {

K8sObjects := []runtime.Object{
&netv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "service-ing",
Namespace: "namespace",
},
},
}

service := Service{
Name: "service",
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

err := updateIngress(service, kubeClientset, cfg)

if err != nil {
t.Errorf("Error updating ingress: %v", err)
}
}

func TestDeleteIngress(t *testing.T) {

K8sObjects := []runtime.Object{
&netv1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "service-ing",
Namespace: "namespace",
},
},
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

err := deleteIngress("service-ing", kubeClientset, cfg)

if err != nil {
t.Errorf("Error deleting ingress: %v", err)
}
}

func TestUpdateSecret(t *testing.T) {

K8sObjects := []runtime.Object{
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "service-auth-expose",
Namespace: "namespace",
},
},
}
service := Service{
Name: "service",
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

err := updateSecret(service, kubeClientset, cfg)

if err != nil {
t.Errorf("Error updating secret: %v", err)
}
}

func TestDeleteSecret(t *testing.T) {

K8sObjects := []runtime.Object{
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "service-auth-expose",
Namespace: "namespace",
},
},
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

err := deleteSecret("service", kubeClientset, cfg)

if err != nil {
t.Errorf("Error deleting secret: %v", err)
}
}

func TestExistsSecret(t *testing.T) {

K8sObjects := []runtime.Object{
&corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "service-auth-expose",
Namespace: "namespace",
},
},
}

kubeClientset := testclient.NewSimpleClientset(K8sObjects...)
cfg := &Config{ServicesNamespace: "namespace"}

exists := existsSecret("service", kubeClientset, cfg)

if exists != true {
t.Errorf("Expected secret to exist but got %v", exists)
}

notexists := existsSecret("service1", kubeClientset, cfg)

if notexists != false {
t.Errorf("Expected secret not to exist but got %v", notexists)
}
}
6 changes: 3 additions & 3 deletions pkg/utils/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
)

// GetAuthMiddleware returns the appropriate gin auth middleware
func GetAuthMiddleware(cfg *types.Config, kubeClientset *kubernetes.Clientset) gin.HandlerFunc {
func GetAuthMiddleware(cfg *types.Config, kubeClientset kubernetes.Interface) gin.HandlerFunc {
if !cfg.OIDCEnable {
return gin.BasicAuth(gin.Accounts{
// Use the config's username and password for basic auth
Expand All @@ -40,7 +40,7 @@ func GetAuthMiddleware(cfg *types.Config, kubeClientset *kubernetes.Clientset) g
}

// CustomAuth returns a custom auth handler (gin middleware)
func CustomAuth(cfg *types.Config, kubeClientset *kubernetes.Clientset) gin.HandlerFunc {
func CustomAuth(cfg *types.Config, kubeClientset kubernetes.Interface) gin.HandlerFunc {
basicAuthHandler := gin.BasicAuth(gin.Accounts{
// Use the config's username and password for basic auth
cfg.Username: cfg.Password,
Expand All @@ -53,7 +53,7 @@ func CustomAuth(cfg *types.Config, kubeClientset *kubernetes.Clientset) gin.Hand
minIOAdminClient.CreateAllUsersGroup()
minIOAdminClient.UpdateUsersInGroup(oscarUser, "all_users_group", false)

oidcHandler := getOIDCMiddleware(kubeClientset, minIOAdminClient, cfg.OIDCIssuer, cfg.OIDCSubject, cfg.OIDCGroups)
oidcHandler := getOIDCMiddleware(kubeClientset, minIOAdminClient, cfg.OIDCIssuer, cfg.OIDCSubject, cfg.OIDCGroups, nil)
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
Expand Down
145 changes: 145 additions & 0 deletions pkg/utils/auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
Copyright (C) GRyCAP - I3M - UPV
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.
*/
package auth

import (
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/gin-gonic/gin"
"github.com/grycap/oscar/v3/pkg/types"
"k8s.io/client-go/kubernetes/fake"
)

func TestGetAuthMiddleware(t *testing.T) {
cfg := &types.Config{
OIDCEnable: false,
Username: "testuser",
Password: "testpass",
}
kubeClientset := fake.NewSimpleClientset()

router := gin.New()
router.Use(GetAuthMiddleware(cfg, kubeClientset))
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.SetBasicAuth("testuser", "testpass")
router.ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Errorf("expected status %v, got %v", http.StatusOK, w.Code)
}

we := httptest.NewRecorder()
reqe, _ := http.NewRequest("GET", "/", nil)
reqe.SetBasicAuth("testuser", "otherpass")
router.ServeHTTP(we, reqe)

if we.Code != http.StatusUnauthorized {
t.Errorf("expected status %v, got %v", http.StatusUnauthorized, we.Code)
}
}

func TestGetLoggerMiddleware(t *testing.T) {
router := gin.New()
router.Use(GetLoggerMiddleware())
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
router.ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Errorf("expected status %v, got %v", http.StatusOK, w.Code)
}
}

func TestGetUIDFromContext(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Set("uidOrigin", "testuid")

uid, err := GetUIDFromContext(c)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if uid != "testuid" {
t.Errorf("expected uid %v, got %v", "testuid", uid)
}
}

func TestGetMultitenancyConfigFromContext(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
mc := &MultitenancyConfig{}
c.Set("multitenancyConfig", mc)

mcFromContext, err := GetMultitenancyConfigFromContext(c)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if mcFromContext != mc {
t.Errorf("expected multitenancyConfig %v, got %v", mc, mcFromContext)
}
}

func TestCustomAuth(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, hreq *http.Request) {
if !strings.HasPrefix(hreq.URL.Path, "/minio/admin/v3/") {
t.Errorf("Unexpected path in request, got: %s", hreq.URL.Path)
}
if hreq.URL.Path == "/minio/admin/v3/info" {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(`{"Mode": "local", "Region": "us-east-1"}`))
} else {
rw.WriteHeader(http.StatusOK)
rw.Write([]byte(`{"status": "success"}`))
}
}))

cfg := &types.Config{
OIDCEnable: false,
Username: "testuser",
Password: "testpass",
MinIOProvider: &types.MinIOProvider{
Endpoint: server.URL,
AccessKey: "minio",
SecretKey: "minio123",
},
}
kubeClientset := fake.NewSimpleClientset()

router := gin.New()
router.Use(CustomAuth(cfg, kubeClientset))
router.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "")
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
req.SetBasicAuth("testuser", "testpass")
router.ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Errorf("expected status %v, got %v", http.StatusOK, w.Code)
}
}
Loading

0 comments on commit 75d862f

Please sign in to comment.