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

feat: add Public-Viewer support #443

Merged
merged 87 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
87 commits
Select commit Hold shift + click to select a range
1cfcd94
fix: use UTC time in tests
filariow Jul 12, 2024
2c897f6
add public-viewer support
filariow Mar 18, 2024
52156fe
enable public-viewer support in spacelister_get
filariow Jul 9, 2024
573aecc
add unit tests for pkg/configuration
filariow Jul 12, 2024
fc99e4e
add tests for log
filariow Jul 12, 2024
962c87c
add unit tests for proxy
filariow Jul 12, 2024
ec8b470
Apply suggestions from code review
filariow Jul 15, 2024
8193b55
Merge branch 'master' into pv-532
filariow Jul 15, 2024
91ff1aa
fix linter
filariow Jul 15, 2024
6c2a595
return empty slice instead of nil
filariow Jul 15, 2024
ca4b882
simplify getUserSpaceBinding
filariow Jul 15, 2024
7f015b5
cleanup tests
filariow Jul 15, 2024
941e052
refactor spacelister_get tests
filariow Jul 15, 2024
4981f91
refactor
filariow Jul 15, 2024
76e43eb
fix spacelister list
filariow Jul 15, 2024
a85b104
enhance spacelister get tests
filariow Jul 15, 2024
75fec5c
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Jul 16, 2024
0d3bfc5
remove unreachable check
filariow Jul 16, 2024
6941c15
Merge branch 'master' into pv-532
filariow Jul 22, 2024
9136bb0
add tests for cluster-service
filariow Jul 22, 2024
7ec2cb4
add user validation test
filariow Jul 22, 2024
f362ac5
add tests for validateSpace
filariow Jul 22, 2024
3b7d1c2
use ptr
filariow Jul 22, 2024
650a6a2
add test case for non-ready user
filariow Jul 22, 2024
e275514
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Jul 23, 2024
4e51460
fix configuration tests comments
filariow Jul 25, 2024
dfa1533
Update pkg/proxy/handlers/spacelister_get.go
filariow Jul 25, 2024
69be0bf
refactor proxy.go
filariow Jul 25, 2024
ef8e333
refactor comments and function names
filariow Jul 25, 2024
8cf0f7b
refactor
filariow Jul 25, 2024
29dd7fe
fix comments
filariow Jul 25, 2024
00dd2f4
improve code readability
filariow Jul 25, 2024
f9b9b5a
improve cluster_service code reuse
filariow Jul 25, 2024
c683c65
Add pkg/context tests for public-viewer
filariow Jul 25, 2024
f533353
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Jul 31, 2024
08cb567
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Jul 31, 2024
43f6c58
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Aug 5, 2024
3452b2b
improve tests
filariow Aug 12, 2024
ac24de1
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Aug 20, 2024
4d863bb
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Aug 26, 2024
2b62f6c
rollback changes to pkg/server/in_cluster_application.go
filariow Aug 26, 2024
3ccbee7
add PublicViewer's middleware
filariow Aug 1, 2024
276323b
remove ctx set in favor of middleware
filariow Aug 26, 2024
8d944fb
fix error message
filariow Aug 26, 2024
f74ee96
Update pkg/proxy/proxy.go
filariow Aug 27, 2024
d278ea7
remove not needed checks
filariow Aug 27, 2024
6f97b34
remove unused parameter
filariow Aug 27, 2024
7934119
Update pkg/proxy/proxy.go
filariow Aug 28, 2024
30b980b
fix tests
filariow Sep 3, 2024
51fe1a4
improve comments
filariow Sep 3, 2024
e27d558
remove redundant check
filariow Sep 3, 2024
96b1646
improve returned error and logging
filariow Sep 3, 2024
048f29b
improve comments
filariow Sep 3, 2024
d9299c5
improve comments
filariow Sep 3, 2024
6408242
check if public-viewer has access to space before forwarding
filariow Sep 3, 2024
76ca225
Merge branch 'master' into pv-532
filariow Sep 3, 2024
a2bc3f8
add test for not signed up user
filariow Sep 12, 2024
1995b76
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 12, 2024
47ab59e
fix typo in comment
filariow Sep 12, 2024
d4fee9b
refactor user names and cleanup test
filariow Sep 12, 2024
e614e38
rename notReadyUser to john
filariow Sep 12, 2024
bd91b58
rename notSignedUpUser to bob
filariow Sep 12, 2024
241fd5a
remove communityuser in favor of alice
filariow Sep 12, 2024
139809a
fix linter complaints
filariow Sep 12, 2024
a2a9837
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 12, 2024
b1e93fb
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 12, 2024
ea515a6
Add tests for banneduser in community tests
filariow Sep 12, 2024
3db6128
use ElementsMatch instead of Equal to reduce flakyness
filariow Sep 12, 2024
b18db56
remove unnecessary TODO comment
filariow Sep 13, 2024
d5c1503
refactor tests
filariow Sep 13, 2024
94e45a0
refactor tests
filariow Sep 13, 2024
306b6d6
revert unneeded changes to test/fake/proxy.go
filariow Sep 13, 2024
fd3e191
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 23, 2024
13d335a
check proxy has forwarded the call
filariow Sep 23, 2024
15fa0cd
add comments and fix typos
filariow Sep 23, 2024
83ea573
add more test cases
filariow Sep 23, 2024
5d0f604
remove dead code
filariow Sep 23, 2024
c071225
consolidate code
filariow Sep 23, 2024
a3eff03
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 23, 2024
e09cd75
fix linter complaints
filariow Sep 23, 2024
cf79085
Merge branch 'master' into pv-532
filariow Sep 24, 2024
599e2d2
add comment
filariow Sep 25, 2024
150dbd0
check proxy requires email in the JWT token
filariow Sep 25, 2024
c343167
remove publicViewer leftovers from test
filariow Sep 25, 2024
087b0dc
Merge remote-tracking branch 'upstream/master' into pv-532
filariow Sep 25, 2024
8ba3452
sort proxy middlewares
filariow Sep 25, 2024
0ffff03
remove unneeded comment
filariow Sep 26, 2024
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
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ go 1.20

require (
github.com/aws/aws-sdk-go v1.44.100
github.com/codeready-toolchain/api v0.0.0-20240607180719-368c7afbaebe
github.com/codeready-toolchain/toolchain-common v0.0.0-20240613121043-7e6ef858cdff
github.com/codeready-toolchain/api v0.0.0-20240708122235-0af5a9a178bb
github.com/codeready-toolchain/toolchain-common v0.0.0-20240711082950-c7f9f4442ae0
github.com/go-logr/logr v1.4.1
github.com/gofrs/uuid v4.2.0+incompatible
github.com/pkg/errors v0.9.1
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtM
github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU=
github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/codeready-toolchain/api v0.0.0-20240607180719-368c7afbaebe h1:l+KsEXkNe1mZ14Z/RaTgeUkEuX9r56mSZC6xlu5H6zY=
github.com/codeready-toolchain/api v0.0.0-20240607180719-368c7afbaebe/go.mod h1:ie9p4LenCCS0LsnbWp6/xwpFDdCWYE0KWzUO6Sk1g0E=
github.com/codeready-toolchain/toolchain-common v0.0.0-20240613121043-7e6ef858cdff h1:bVWL+2eayFKUnEzdEAwltPs+pzbGlGDSmrM3oOV2Ams=
github.com/codeready-toolchain/toolchain-common v0.0.0-20240613121043-7e6ef858cdff/go.mod h1:cyHrUfvBYEtsf+FbqQYmR9y0AQi9QAVtM3SUWLA5bd4=
github.com/codeready-toolchain/api v0.0.0-20240708122235-0af5a9a178bb h1:Wc9CMsv0ODZv9dM5qF3OI0mFDO95YNIXV/8oRvoz8aE=
github.com/codeready-toolchain/api v0.0.0-20240708122235-0af5a9a178bb/go.mod h1:ie9p4LenCCS0LsnbWp6/xwpFDdCWYE0KWzUO6Sk1g0E=
github.com/codeready-toolchain/toolchain-common v0.0.0-20240711082950-c7f9f4442ae0 h1:v7Z5i0JaF1H9SYxK/uEjWgH8Vpm4Eg3OJep/Pl/2iyM=
github.com/codeready-toolchain/toolchain-common v0.0.0-20240711082950-c7f9f4442ae0/go.mod h1:8M9k7w2VSyRKSK6P08Jo2ddW3uyGgxCcSitnYa3HK9o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down
2 changes: 1 addition & 1 deletion pkg/application/service/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type VerificationService interface {
}

type MemberClusterService interface {
GetClusterAccess(userID, username, workspace, proxyPluginName string) (*access.ClusterAccess, error)
GetClusterAccess(userID, username, workspace, proxyPluginName string, publicViewerEnabled bool) (*access.ClusterAccess, error)
}

type Services interface {
Expand Down
4 changes: 4 additions & 0 deletions pkg/configuration/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ func (r RegistrationServiceConfig) Print() {
logger.Info("Registration Service Configuration", "config", r.cfg.Host.RegistrationService)
}

func (r RegistrationServiceConfig) PublicViewerEnabled() bool {
return r.cfg.Host.PublicViewerConfig != nil && r.cfg.Host.PublicViewerConfig.Enabled
}

func (r RegistrationServiceConfig) Environment() string {
return commonconfig.GetString(r.cfg.Host.RegistrationService.Environment, prodEnvironment)
}
Expand Down
39 changes: 39 additions & 0 deletions pkg/configuration/configuration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package configuration_test
import (
"testing"

"github.com/codeready-toolchain/api/api/v1alpha1"
"github.com/codeready-toolchain/registration-service/pkg/configuration"
"github.com/codeready-toolchain/registration-service/test"
commonconfig "github.com/codeready-toolchain/toolchain-common/pkg/configuration"
Expand Down Expand Up @@ -68,6 +69,7 @@ func TestRegistrationService(t *testing.T) {
assert.InDelta(t, float32(0), regServiceCfg.Verification().CaptchaRequiredScore(), 0.01)
assert.True(t, regServiceCfg.Verification().CaptchaAllowLowScoreReactivation())
assert.Empty(t, regServiceCfg.Verification().CaptchaServiceAccountFileContents())
assert.False(t, regServiceCfg.PublicViewerEnabled())
})
t.Run("non-default", func(t *testing.T) {
// given
Expand Down Expand Up @@ -151,5 +153,42 @@ func TestRegistrationService(t *testing.T) {
assert.InDelta(t, float32(0.5), regServiceCfg.Verification().CaptchaRequiredScore(), 0.01)
assert.False(t, regServiceCfg.Verification().CaptchaAllowLowScoreReactivation())
assert.Equal(t, "example-content", regServiceCfg.Verification().CaptchaServiceAccountFileContents())
assert.False(t, regServiceCfg.PublicViewerEnabled())
})
}

func TestPublicViewer(t *testing.T) {
tt := map[string]struct {
name string
expectedValue bool
publicViewerConfig *v1alpha1.PublicViewerConfiguration
}{
"public-viewer is explicitly enabled": {
expectedValue: true,
publicViewerConfig: &v1alpha1.PublicViewerConfiguration{Enabled: true},
},
"public-viewer is explicitly disabled": {
expectedValue: false,
publicViewerConfig: &v1alpha1.PublicViewerConfiguration{Enabled: false},
},
"public-viewer config not set, assume disabled": {
expectedValue: false,
publicViewerConfig: nil,
},
}

for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
// given
cfg := commonconfig.NewToolchainConfigObjWithReset(t)
cfg.Spec.Host.PublicViewerConfig = tc.publicViewerConfig
secrets := make(map[string]map[string]string)
regServiceCfg := configuration.NewRegistrationServiceConfig(cfg, secrets)

// then

// when
assert.Equal(t, tc.expectedValue, regServiceCfg.PublicViewerEnabled())
})
}
}
4 changes: 4 additions & 0 deletions pkg/context/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,8 @@ const (
WorkspaceKey = "workspace"
// RequestReceivedTime is the context key for the starting time of a request made
RequestReceivedTime = "requestReceivedTime"
// PublicViewerEnabled is a boolean value indicating whether PublicViewer support is enabled
PublicViewerEnabled = "publicViewerEnabled"
// ImpersonateUser is the content key for the impersonated user in proxied call
filariow marked this conversation as resolved.
Show resolved Hide resolved
ImpersonateUser = "impersonateUser"
)
10 changes: 10 additions & 0 deletions pkg/context/public_viewer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package context

import "github.com/labstack/echo/v4"

// IsPublicViewerEnabled retrieves from the context the boolean value associated to the PublicViewerEnabled key.
// If the key is not set it returns false, otherwise it returns the boolean value stored in the context.
func IsPublicViewerEnabled(ctx echo.Context) bool {
publicViewerEnabled, _ := ctx.Get(PublicViewerEnabled).(bool)
return publicViewerEnabled
}
8 changes: 8 additions & 0 deletions pkg/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ func (l *Logger) InfoEchof(ctx echo.Context, msg string, args ...string) {
ctxFields = append(ctxFields, "url")
ctxFields = append(ctxFields, ctx.Request().URL)

if impersonateUser, ok := ctx.Get(context.ImpersonateUser).(string); ok {
ctxFields = append(ctxFields, "impersonate-user", impersonateUser)
}

if publicViewerEnabled, ok := ctx.Get(context.PublicViewerEnabled).(bool); ok {
ctxFields = append(ctxFields, "public-viewer-enabled", publicViewerEnabled)
}

l.infof(ctxFields, msg, args...)
}

Expand Down
79 changes: 61 additions & 18 deletions pkg/log/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,25 +60,68 @@ func TestLog(t *testing.T) {
})

t.Run("log infoEchof", func(t *testing.T) {
buf.Reset()
req := httptest.NewRequest(http.MethodGet, "https://api-server.com/api/workspaces/path", strings.NewReader("{}"))
rec := httptest.NewRecorder()
ctx := echo.New().NewContext(req, rec)
ctx.Set(context.SubKey, "test")
ctx.Set(context.UsernameKey, "usernametest")
ctx.Set(context.WorkspaceKey, "coolworkspace")
tt := map[string]struct {
name string
contains string
notContains string
ctxSet map[string]interface{}
}{
"default": {},
"impersonateUser is set": {
ctxSet: map[string]interface{}{context.ImpersonateUser: "user"},
contains: `"impersonate-user":"user"`,
},
"impersonateUser is not set": {
ctxSet: map[string]interface{}{},
notContains: `impersonate-user`,
},
"public-viewer-enabled is set to true": {
ctxSet: map[string]interface{}{context.PublicViewerEnabled: true},
contains: `"public-viewer-enabled":true`,
},
"public-viewer-enabled is set to false": {
ctxSet: map[string]interface{}{context.PublicViewerEnabled: false},
contains: `"public-viewer-enabled":false`,
},
"public-viewer-enabled is not set": {
ctxSet: map[string]interface{}{},
notContains: `public-viewer-enabled`,
},
}

InfoEchof(ctx, "test %s", "info")
value := buf.String()
assert.Contains(t, value, `"logger":"logger_tests"`)
assert.Contains(t, value, `"msg":"test info"`)
assert.Contains(t, value, `"user_id":"test"`) // subject -> user_id
assert.Contains(t, value, `"username":"usernametest"`)
assert.Contains(t, value, `"level":"info"`)
assert.Contains(t, value, `"timestamp":"`)
assert.Contains(t, value, `"workspace":"coolworkspace"`)
assert.Contains(t, value, `"method":"GET"`)
assert.Contains(t, value, `"url":"https://api-server.com/api/workspaces/path"`)
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
buf.Reset()
req := httptest.NewRequest(http.MethodGet, "https://api-server.com/api/workspaces/path", strings.NewReader("{}"))
rec := httptest.NewRecorder()
ctx := echo.New().NewContext(req, rec)
ctx.Set(context.SubKey, "test")
ctx.Set(context.UsernameKey, "usernametest")
ctx.Set(context.WorkspaceKey, "coolworkspace")
for k, v := range tc.ctxSet {
ctx.Set(k, v)
}

InfoEchof(ctx, "test %s", "info")
value := buf.String()
assert.Contains(t, value, `"logger":"logger_tests"`)
assert.Contains(t, value, `"msg":"test info"`)
assert.Contains(t, value, `"user_id":"test"`) // subject -> user_id
assert.Contains(t, value, `"username":"usernametest"`)
assert.Contains(t, value, `"level":"info"`)
assert.Contains(t, value, `"timestamp":"`)
assert.Contains(t, value, `"workspace":"coolworkspace"`)
assert.Contains(t, value, `"method":"GET"`)
assert.Contains(t, value, `"url":"https://api-server.com/api/workspaces/path"`)

if tc.contains != "" {
assert.Contains(t, value, tc.contains)
}
if tc.notContains != "" {
assert.NotContains(t, value, tc.notContains)
}
})
}
})

t.Run("log infof with no arguments", func(t *testing.T) {
Expand Down
80 changes: 73 additions & 7 deletions pkg/proxy/handlers/spacelister_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"time"

toolchainv1alpha1 "github.com/codeready-toolchain/api/api/v1alpha1"
"github.com/codeready-toolchain/registration-service/pkg/configuration"
"github.com/codeready-toolchain/registration-service/pkg/context"
regsercontext "github.com/codeready-toolchain/registration-service/pkg/context"
"github.com/codeready-toolchain/registration-service/pkg/proxy/metrics"
"github.com/codeready-toolchain/registration-service/pkg/signup"
Expand All @@ -27,6 +29,8 @@ func HandleSpaceGetRequest(spaceLister *SpaceLister, GetMembersFunc cluster.GetM
// get specific workspace
return func(ctx echo.Context) error {
requestReceivedTime := ctx.Get(regsercontext.RequestReceivedTime).(time.Time)
publicViewerEnabled := configuration.GetRegistrationServiceConfig().PublicViewerEnabled()
ctx.Set(context.PublicViewerEnabled, publicViewerEnabled)
filariow marked this conversation as resolved.
Show resolved Hide resolved
filariow marked this conversation as resolved.
Show resolved Hide resolved
workspace, err := GetUserWorkspaceWithBindings(ctx, spaceLister, ctx.Param("workspace"), GetMembersFunc)
if err != nil {
spaceLister.ProxyMetrics.RegServWorkspaceHistogramVec.WithLabelValues(fmt.Sprintf("%d", http.StatusInternalServerError), metrics.MetricsLabelVerbGet).Observe(time.Since(requestReceivedTime).Seconds()) // using list as the default value for verb to minimize label combinations for prometheus to process
Expand All @@ -43,7 +47,7 @@ func HandleSpaceGetRequest(spaceLister *SpaceLister, GetMembersFunc cluster.GetM
}
}

// GetUserWorkspace returns a workspace object with the required fields used by the proxy
// GetUserWorkspace returns a workspace object with the required fields used by the proxy.
func GetUserWorkspace(ctx echo.Context, spaceLister *SpaceLister, workspaceName string) (*toolchainv1alpha1.Workspace, error) {
userSignup, space, err := getUserSignupAndSpace(ctx, spaceLister, workspaceName)
if err != nil {
Expand All @@ -54,6 +58,56 @@ func GetUserWorkspace(ctx echo.Context, spaceLister *SpaceLister, workspaceName
return nil, nil
}

// retrieve user space binding
userSpaceBinding, err := getUserOrPublicViewerSpaceBinding(ctx, spaceLister, space, userSignup, workspaceName)
if err != nil {
return nil, err
}
// consider this as not found
if userSpaceBinding == nil {
return nil, nil
}

// create and return the result workspace object
return createWorkspaceObject(userSignup.Name, space, userSpaceBinding), nil
}

// getUserOrPublicViewerSpaceBinding retrieves the user space binding for an user and a space.
// If the SpaceBinding is not found and the PublicViewer feature is enabled, it will retry
// with the PublicViewer credentials.
func getUserOrPublicViewerSpaceBinding(ctx echo.Context, spaceLister *SpaceLister, space *toolchainv1alpha1.Space, userSignup *signup.Signup, workspaceName string) (*toolchainv1alpha1.SpaceBinding, error) {
userSpaceBinding, err := getUserSpaceBinding(ctx, spaceLister, space, userSignup)
if err != nil {
return nil, err
}

// if user space binding is not found and PublicViewer is enabled,
// retry with PublicViewer's signup
if userSpaceBinding == nil {
if context.IsPublicViewerEnabled(ctx) {
publicViewerUserSignup := signup.Signup{
Name: toolchainv1alpha1.KubesawAuthenticatedUsername,
CompliantUsername: toolchainv1alpha1.KubesawAuthenticatedUsername,
}
pvSb, err := getUserSpaceBinding(ctx, spaceLister, space, &publicViewerUserSignup)
if err != nil {
ctx.Logger().Error(fmt.Sprintf("error checking if SpaceBinding is present for user %s and the workspace %s", publicViewerUserSignup.CompliantUsername, workspaceName))
return nil, err
}
if pvSb == nil {
ctx.Logger().Error(fmt.Sprintf("unauthorized access - there is no SpaceBinding present for the user %s and the workspace %s", userSignup.CompliantUsername, workspaceName))
filariow marked this conversation as resolved.
Show resolved Hide resolved
return nil, nil
}
return pvSb, nil
}
ctx.Logger().Error(fmt.Sprintf("unauthorized access - there is no SpaceBinding present for the user %s and the workspace %s", userSignup.CompliantUsername, workspaceName))
}

return userSpaceBinding, nil
}

// getUserSpaceBinding retrieves the user space binding for an user and a space.
filariow marked this conversation as resolved.
Show resolved Hide resolved
func getUserSpaceBinding(ctx echo.Context, spaceLister *SpaceLister, space *toolchainv1alpha1.Space, userSignup *signup.Signup) (*toolchainv1alpha1.SpaceBinding, error) {
filariow marked this conversation as resolved.
Show resolved Hide resolved
// recursively get all the spacebindings for the current workspace
listSpaceBindingsFunc := func(spaceName string) ([]toolchainv1alpha1.SpaceBinding, error) {
spaceSelector, err := labels.NewRequirement(toolchainv1alpha1.SpaceBindingSpaceLabelKey, selection.Equals, []string{spaceName})
Expand All @@ -74,7 +128,6 @@ func GetUserWorkspace(ctx echo.Context, spaceLister *SpaceLister, workspaceName
}
if len(userSpaceBindings) == 0 {
// let's only log the issue and consider this as not found
filariow marked this conversation as resolved.
Show resolved Hide resolved
ctx.Logger().Error(fmt.Sprintf("unauthorized access - there is no SpaceBinding present for the user %s and the workspace %s", userSignup.CompliantUsername, workspaceName))
return nil, nil
}

Expand All @@ -84,10 +137,10 @@ func GetUserWorkspace(ctx echo.Context, spaceLister *SpaceLister, workspaceName
return nil, userBindingsErr
}

return createWorkspaceObject(userSignup.Name, space, &userSpaceBindings[0]), nil
return &userSpaceBindings[0], nil
}

// GetUserWorkspaceWithBindings returns a workspace object with the required fields+bindings (the list with all the users access details)
// GetUserWorkspaceWithBindings returns a workspace object with the required fields+bindings (the list with all the users access details).
func GetUserWorkspaceWithBindings(ctx echo.Context, spaceLister *SpaceLister, workspaceName string, GetMembersFunc cluster.GetMemberClustersFunc) (*toolchainv1alpha1.Workspace, error) {
userSignup, space, err := getUserSignupAndSpace(ctx, spaceLister, workspaceName)
if err != nil {
Expand Down Expand Up @@ -116,9 +169,16 @@ func GetUserWorkspaceWithBindings(ctx echo.Context, spaceLister *SpaceLister, wo
// check if user has access to this workspace
userBinding := filterUserSpaceBinding(userSignup.CompliantUsername, allSpaceBindings)
if userBinding == nil {
// let's only log the issue and consider this as not found
ctx.Logger().Error(fmt.Sprintf("unauthorized access - there is no SpaceBinding present for the user %s and the workspace %s", userSignup.CompliantUsername, workspaceName))
return nil, nil
// if PublicViewer is enabled, check if the Space is visibile to PublicViewer
if context.IsPublicViewerEnabled(ctx) && userSignup.CompliantUsername != toolchainv1alpha1.KubesawAuthenticatedUsername {
mfrancisc marked this conversation as resolved.
Show resolved Hide resolved
userBinding = filterUserSpaceBinding(toolchainv1alpha1.KubesawAuthenticatedUsername, allSpaceBindings)
}

if userBinding == nil {
// let's only log the issue and consider this as not found
ctx.Logger().Error(fmt.Sprintf("unauthorized access - there is no SpaceBinding present for the user %s and the workspace %s", userSignup.CompliantUsername, workspaceName))
return nil, nil
}
}

// list all SpaceBindingRequests , just in case there might be some failing to create a SpaceBinding resource.
Expand Down Expand Up @@ -155,6 +215,12 @@ func getUserSignupAndSpace(ctx echo.Context, spaceLister *SpaceLister, workspace
if err != nil {
return nil, nil, err
}
if userSignup == nil && context.IsPublicViewerEnabled(ctx) {
userSignup = &signup.Signup{
CompliantUsername: toolchainv1alpha1.KubesawAuthenticatedUsername,
Name: toolchainv1alpha1.KubesawAuthenticatedUsername,
}
}

space, err := spaceLister.GetInformerServiceFunc().GetSpace(workspaceName)
if err != nil {
Expand Down
Loading
Loading