Merge branch 'stable-8.2' into fix/8.2/OCISDEV-1502
This commit is contained in:
28 files changed
+739
-104
No files matched your search
@@ -0,0 +1,13 @@
|
||||
Bugfix: Fix AuthApp and basic auth requests with custom PROXY_USER_OIDC_CLAIM
|
||||
|
||||
We fixed AuthApp (app password) and HTTP basic auth requests returning an
|
||||
internal server error whenever PROXY_USER_OIDC_CLAIM was set to anything
|
||||
other than its default value. Both authenticators put the already
|
||||
authenticated user directly into the request context instead of faking
|
||||
incomplete claims for the account resolver to re-resolve. We also made sure
|
||||
a user who only ever authenticates this way still gets a default role
|
||||
assigned, and that these requests keep getting rejected on deployments with
|
||||
multiple instances enabled, since neither carries tenant-membership
|
||||
information.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13078
|
||||
@@ -0,0 +1,25 @@
|
||||
Bugfix: Fix the LDAP master-ID filter when the base filter is empty
|
||||
|
||||
The function `EnhanceFilterWithMasterID` in `ocis-pkg/ldap/filter.go` adds a
|
||||
master-ID clause to an LDAP filter with OR. An empty filter means "no
|
||||
restriction". Before this fix, the function replaced an empty filter with a
|
||||
master-ID-only filter. This action restricted an unrestricted search to
|
||||
master-ID users only.
|
||||
|
||||
The bug broke the search for a user on another instance in multi-instance
|
||||
deployments. This search uses the Graph API endpoint `/graph/v1.0/users`.
|
||||
Multi-instance deployments use this search to find a user to share a resource
|
||||
with.
|
||||
|
||||
Now the function keeps an empty filter unchanged. The function still adds a
|
||||
master-ID clause to a filter that is not empty.
|
||||
|
||||
The `graph`, `auth-basic`, `users`, and `groups` services also use this
|
||||
function to compute their default LDAP user filter when
|
||||
`OCIS_MULTI_INSTANCE_MASTER_ID` is set. An empty user filter now means these
|
||||
services resolve or authenticate every user in the shared LDAP directory,
|
||||
not only master-ID users. Each of these services now rejects startup when
|
||||
`OCIS_MULTI_INSTANCE_MASTER_ID` is set and its own user filter is empty.
|
||||
Set an explicit `OCIS_LDAP_USER_FILTER` for every multi-instance deployment.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13096
|
||||
+6
-11
@@ -7,14 +7,13 @@ import (
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// EnhanceFilterWithMasterID OR's the given LDAP filter with master-id match clauses.
|
||||
// Returns filter unchanged when masterID is empty or both attributes are empty.
|
||||
// EnhanceFilterWithMasterID adds master-ID match clauses to the given LDAP filter with OR.
|
||||
// An empty filter means "no restriction". Do not OR an empty filter with a master-ID clause.
|
||||
// This action would restrict an unrestricted search to the master ID only.
|
||||
// The function returns the filter without a change when masterID is empty, when both
|
||||
// attributes are empty, or when filter is empty.
|
||||
func EnhanceFilterWithMasterID(filter, masterID, memberAttr, guestAttr string) string {
|
||||
if masterID == "" {
|
||||
return filter
|
||||
}
|
||||
|
||||
if memberAttr == "" && guestAttr == "" {
|
||||
if masterID == "" || (memberAttr == "" && guestAttr == "") || filter == "" {
|
||||
return filter
|
||||
}
|
||||
|
||||
@@ -35,9 +34,5 @@ func EnhanceFilterWithMasterID(filter, masterID, memberAttr, guestAttr string) s
|
||||
masterIDFilter = fmt.Sprintf("(|%s)", strings.Join(masterIDParts, ""))
|
||||
}
|
||||
|
||||
if filter == "" {
|
||||
return masterIDFilter
|
||||
}
|
||||
|
||||
return fmt.Sprintf("(|%s%s)", filter, masterIDFilter)
|
||||
}
|
||||
@@ -54,12 +54,12 @@ func TestEnhanceFilterWithMasterID(t *testing.T) {
|
||||
expectedFilter: "(|(ownCloudGuestOf=instance-1)(ownCloudGuestOf=0000-0000-000-0000))",
|
||||
},
|
||||
{
|
||||
name: "empty existing filter",
|
||||
name: "empty existing filter stays unrestricted",
|
||||
filter: "",
|
||||
masterID: "0000-0000-000-0000",
|
||||
memberAttr: "ownCloudMemberOf",
|
||||
guestAttr: "ownCloudGuestOf",
|
||||
expectedFilter: "(|(ownCloudMemberOf=0000-0000-000-0000)(ownCloudGuestOf=0000-0000-000-0000))",
|
||||
expectedFilter: "",
|
||||
},
|
||||
{
|
||||
name: "LDAP injection protection",
|
||||
|
||||
@@ -46,6 +46,13 @@ func MissingLDAPBindPassword(service string) error {
|
||||
service, defaults.BaseConfigPath())
|
||||
}
|
||||
|
||||
func MissingLDAPUserFilterForMasterID(service string) error {
|
||||
return fmt.Errorf("The ldap user_filter has not been set for %s, but OCIS_MULTI_INSTANCE_MASTER_ID is set. "+
|
||||
"Set an explicit user_filter to scope this instance to its own users. "+
|
||||
"Without a user_filter, every user in the shared LDAP directory can access this instance.",
|
||||
service)
|
||||
}
|
||||
|
||||
func MissingServiceUserPassword(service, serviceUser string) error {
|
||||
return fmt.Errorf("The password of service user %s has not been set properly in your config for %s. "+
|
||||
"Make sure your %s config contains the proper values "+
|
||||
|
||||
@@ -82,7 +82,7 @@ type LDAPProvider struct {
|
||||
IDP string `yaml:"idp" env:"OCIS_URL;OCIS_OIDC_ISSUER;AUTH_BASIC_IDP_URL" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
|
||||
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;AUTH_BASIC_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Valid options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed." introductionVersion:"pre5.0"`
|
||||
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;AUTH_BASIC_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance allows login for every user in the shared LDAP directory." introductionVersion:"7.0"`
|
||||
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
|
||||
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
|
||||
UserSchema LDAPUserSchema `yaml:"user_schema"`
|
||||
|
||||
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
|
||||
return shared.MissingLDAPBindPassword(cfg.Service.Name)
|
||||
}
|
||||
|
||||
if cfg.AuthProvider == "ldap" && cfg.AuthProviders.LDAP.MasterID != "" && cfg.AuthProviders.LDAP.UserFilter == "" {
|
||||
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/auth-basic/pkg/config"
|
||||
)
|
||||
|
||||
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "auth-basic"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
AuthProvider: "ldap",
|
||||
AuthProviders: config.AuthProviders{
|
||||
LDAP: config.LDAPProvider{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "auth-basic"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
AuthProvider: "ldap",
|
||||
AuthProviders: config.AuthProviders{
|
||||
LDAP: config.LDAPProvider{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "(ownCloudMemberOf=instance-1)",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "auth-basic"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
AuthProvider: "ldap",
|
||||
AuthProviders: config.AuthProviders{
|
||||
LDAP: config.LDAPProvider{
|
||||
BindPassword: "secret",
|
||||
MasterID: "",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -198,6 +198,6 @@ type Validation struct {
|
||||
type MultiInstanceConfig struct {
|
||||
Enabled bool `yaml:"enabled" env:"OCIS_MULTI_INSTANCE_ENABLED" desc:"Enable multiple instances of Infinite Scale." introductionVersion:"8.0.0"`
|
||||
InstanceID string `yaml:"instanceid" env:"OCIS_MULTI_INSTANCE_INSTANCEID" desc:"The unique ID of this instance." introductionVersion:"8.0.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable." introductionVersion:"8.1.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable. Also set 'OCIS_LDAP_USER_FILTER'. Without an explicit user filter, this instance resolves every user in the shared LDAP directory." introductionVersion:"8.1.0"`
|
||||
QueryRegexp string `yaml:"query_regexp" env:"OCIS_MULTI_INSTANCE_QUERY_TEMPLATE" desc:"The regular expression extracting username and instancename from a user provided search." introductionVersion:"8.0.0"`
|
||||
}
|
||||
@@ -98,6 +98,10 @@ func validateLDAPSettings(cfg *config.Config) error {
|
||||
return shared.MissingLDAPBindPassword(cfg.Service.Name)
|
||||
}
|
||||
|
||||
if cfg.MultiInstance.MasterID != "" && cfg.Identity.LDAP.UserFilter == "" {
|
||||
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
|
||||
}
|
||||
|
||||
// ensure that "GroupBaseDN" is below "GroupBaseDN"
|
||||
if cfg.Identity.LDAP.WriteEnabled && cfg.Identity.LDAP.GroupCreateBaseDN != cfg.Identity.LDAP.GroupBaseDN {
|
||||
baseDN, err := ldap.ParseDN(cfg.Identity.LDAP.GroupBaseDN)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
|
||||
)
|
||||
|
||||
func TestValidateLDAPSettingsMasterIDRequiresUserFilter(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "graph"},
|
||||
Identity: config.Identity{
|
||||
LDAP: config.LDAP{
|
||||
BindPassword: "secret",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
MultiInstance: config.MultiInstanceConfig{
|
||||
MasterID: "master-1",
|
||||
},
|
||||
}
|
||||
|
||||
err := validateLDAPSettings(cfg)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidateLDAPSettingsMasterIDWithUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "graph"},
|
||||
Identity: config.Identity{
|
||||
LDAP: config.LDAP{
|
||||
BindPassword: "secret",
|
||||
UserFilter: "(ownCloudMemberOf=instance-1)",
|
||||
},
|
||||
},
|
||||
MultiInstance: config.MultiInstanceConfig{
|
||||
MasterID: "master-1",
|
||||
},
|
||||
}
|
||||
|
||||
err := validateLDAPSettings(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateLDAPSettingsNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "graph"},
|
||||
Identity: config.Identity{
|
||||
LDAP: config.LDAP{
|
||||
BindPassword: "secret",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
MultiInstance: config.MultiInstanceConfig{
|
||||
MasterID: "",
|
||||
},
|
||||
}
|
||||
|
||||
err := validateLDAPSettings(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -79,7 +79,7 @@ type LDAPDriver struct {
|
||||
UserObjectClass string `yaml:"user_object_class" env:"OCIS_LDAP_USER_OBJECTCLASS;GROUPS_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
|
||||
GroupObjectClass string `yaml:"group_object_class" env:"OCIS_LDAP_GROUP_OBJECTCLASS;GROUPS_LDAP_GROUP_OBJECTCLASS" desc:"The object class to use for groups in the default group search filter ('groupOfNames')." introductionVersion:"pre5.0"`
|
||||
IDP string `yaml:"idp" env:"OCIS_URL;OCIS_OIDC_ISSUER;GROUPS_IDP_URL" desc:"The identity provider value to set in the group IDs of the CS3 group objects for groups returned by this group provider." introductionVersion:"pre5.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance resolves every user in the shared LDAP directory." introductionVersion:"7.0"`
|
||||
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
|
||||
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
|
||||
UserSchema LDAPUserSchema `yaml:"user_schema"`
|
||||
|
||||
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
|
||||
return shared.MissingLDAPBindPassword(cfg.Service.Name)
|
||||
}
|
||||
|
||||
if cfg.Driver == "ldap" && cfg.Drivers.LDAP.MasterID != "" && cfg.Drivers.LDAP.UserFilter == "" {
|
||||
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/groups/pkg/config"
|
||||
)
|
||||
|
||||
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "groups"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "groups"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "(ownCloudMemberOf=instance-1)",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "groups"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
@@ -285,15 +285,19 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
if cfg.EnableBasicAuth {
|
||||
logger.Warn().Msg("basic auth enabled, use only for testing or development")
|
||||
authenticators = append(authenticators, middleware.BasicAuthenticator{
|
||||
Logger: logger,
|
||||
UserProvider: userProvider,
|
||||
Logger: logger,
|
||||
UserProvider: userProvider,
|
||||
UserRoleAssigner: roleAssigner,
|
||||
MultiInstanceEnabled: cfg.MultiInstance.Enabled,
|
||||
})
|
||||
}
|
||||
|
||||
if cfg.AuthMiddleware.AllowAppAuth {
|
||||
authenticators = append(authenticators, middleware.AppAuthAuthenticator{
|
||||
Logger: logger,
|
||||
RevaGatewaySelector: gatewaySelector,
|
||||
Logger: logger,
|
||||
RevaGatewaySelector: gatewaySelector,
|
||||
UserRoleAssigner: roleAssigner,
|
||||
MultiInstanceEnabled: cfg.MultiInstance.Enabled,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,15 @@ func (m accountResolver) verifyUser(w http.ResponseWriter, req *http.Request, us
|
||||
return
|
||||
}
|
||||
|
||||
if errors.Is(err, backend.ErrAccountNotFound) {
|
||||
// the identity backend excludes disabled accounts from by-claim
|
||||
// lookups, so a disabled account also ends up here, not just a
|
||||
// genuinely unknown username.
|
||||
m.logger.Debug().Interface("user", user).Msg("Not found")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
m.logger.Error().Err(err).Msg("Could not get user by claim")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
@@ -472,3 +472,35 @@ func TestResolveUserType(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestVerifyUserUnauthorizedOnUserNotFound covers the verifyUser fast path
|
||||
// (user already in context, e.g. via AppAuthAuthenticator/BasicAuthenticator),
|
||||
// as opposed to TestUnauthorizedOnUserNotFound which covers the claims-based
|
||||
// resolveUserFromClaims path. A disabled account is looked up by username and
|
||||
// comes back as ErrAccountNotFound (the identity backend excludes disabled
|
||||
// accounts from by-claim lookups), which must map to 401, not 500.
|
||||
func TestVerifyUserUnauthorizedOnUserNotFound(t *testing.T) {
|
||||
user := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{Idp: "https://idx.example.com", OpaqueId: "123"},
|
||||
Username: "alice",
|
||||
}
|
||||
|
||||
ub := mocks.UserBackend{}
|
||||
ub.On("GetUserByClaims", mock.Anything, "username", "alice").Return(nil, "", backend.ErrAccountNotFound)
|
||||
|
||||
ra := userRoleMocks.UserRoleAssigner{}
|
||||
|
||||
sut := AccountResolver(
|
||||
Logger(log.NewLogger()),
|
||||
UserProvider(&ub),
|
||||
UserRoleAssigner(&ra),
|
||||
)(mockHandler{})
|
||||
|
||||
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
|
||||
req = req.WithContext(revactx.ContextSetUser(context.Background(), user))
|
||||
rw := httptest.NewRecorder()
|
||||
|
||||
sut.ServeHTTP(rw, req)
|
||||
|
||||
assert.Equal(t, http.StatusUnauthorized, rw.Code)
|
||||
}
|
||||
@@ -6,15 +6,17 @@ import (
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
)
|
||||
|
||||
// AppAuthAuthenticator defines the app auth authenticator
|
||||
type AppAuthAuthenticator struct {
|
||||
Logger log.Logger
|
||||
RevaGatewaySelector pool.Selectable[gateway.GatewayAPIClient]
|
||||
Logger log.Logger
|
||||
RevaGatewaySelector pool.Selectable[gateway.GatewayAPIClient]
|
||||
UserRoleAssigner userroles.UserRoleAssigner
|
||||
MultiInstanceEnabled bool
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via app auth.
|
||||
@@ -26,6 +28,15 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, erro
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
if m.MultiInstanceEnabled {
|
||||
// App passwords carry no OIDC claims, so there is no way to verify
|
||||
// tenant membership (OCIS_MULTI_INSTANCE_MEMBER_CLAIM/GUEST_CLAIM)
|
||||
// for them. Reject rather than let the request bypass the tenant
|
||||
// check in services/proxy/pkg/middleware/account_resolver.go's
|
||||
// resolveUserType.
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
return nil, ErrAuthenticationFailed
|
||||
@@ -48,17 +59,19 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, erro
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
r.Header.Set(revactx.TokenHeader, authenticateResponse.GetToken())
|
||||
|
||||
user := authenticateResponse.GetUser()
|
||||
// fake oidc claims for the account resolver
|
||||
claims := map[string]interface{}{
|
||||
oidc.Iss: user.GetId().GetIdp(),
|
||||
oidc.PreferredUsername: user.GetUsername(),
|
||||
oidc.Email: user.GetMail(),
|
||||
oidc.OwncloudUUID: user.GetId().GetOpaqueId(),
|
||||
user, err := m.UserRoleAssigner.ApplyUserRole(r.Context(), authenticateResponse.GetUser())
|
||||
if err != nil {
|
||||
m.Logger.Error().Err(err).Msg("could not apply user role")
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
r = r.WithContext(oidc.NewContext(r.Context(), claims))
|
||||
|
||||
// only mutate the request once we know we're returning success, so a
|
||||
// failed authentication attempt can't leave a stale access token behind
|
||||
// for a later authenticator in the chain to build on.
|
||||
r.Header.Set(revactx.TokenHeader, authenticateResponse.GetToken())
|
||||
// the user is already authenticated, put it into the context directly
|
||||
// instead of faking oidc claims for the account resolver to re-resolve.
|
||||
r = r.WithContext(revactx.ContextSetUser(r.Context(), user))
|
||||
|
||||
return r, nil
|
||||
}
|
||||
@@ -1,27 +1,41 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
backendmocks "github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/scope"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/token/manager/jwt"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"google.golang.org/grpc"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
)
|
||||
|
||||
var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func() {
|
||||
var authenticator Authenticator
|
||||
var roleAssigner *mocks.UserRoleAssigner
|
||||
BeforeEach(func() {
|
||||
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
|
||||
|
||||
roleAssigner = &mocks.UserRoleAssigner{}
|
||||
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
|
||||
).Maybe()
|
||||
|
||||
authenticator = AppAuthAuthenticator{
|
||||
Logger: log.NewLogger(),
|
||||
Logger: log.NewLogger(),
|
||||
UserRoleAssigner: roleAssigner,
|
||||
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
|
||||
"GatewaySelector",
|
||||
"com.owncloud.api.gateway",
|
||||
@@ -68,12 +82,81 @@ var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func(
|
||||
Expect(req2).ToNot(BeNil())
|
||||
Expect(req2.Header.Get("x-access-token")).To(Equal("reva-token"))
|
||||
|
||||
claims := oidc.FromContext(req2.Context())
|
||||
Expect(claims).ToNot(BeNil())
|
||||
Expect(claims[oidc.Iss]).To(Equal("testIDP"))
|
||||
Expect(claims[oidc.PreferredUsername]).To(Equal("alice"))
|
||||
Expect(claims[oidc.Email]).To(Equal("alice@example.prv"))
|
||||
Expect(claims[oidc.OwncloudUUID]).To(Equal("abcd-1234"))
|
||||
user, ok := revactx.ContextGetUser(req2.Context())
|
||||
Expect(ok).To(Equal(true))
|
||||
Expect(user.GetId().GetIdp()).To(Equal("testIDP"))
|
||||
Expect(user.GetId().GetOpaqueId()).To(Equal("abcd-1234"))
|
||||
Expect(user.GetUsername()).To(Equal("alice"))
|
||||
Expect(user.GetMail()).To(Equal("alice@example.prv"))
|
||||
})
|
||||
})
|
||||
|
||||
When("multi-instance mode is enabled", func() {
|
||||
It("rejects the request, since app passwords carry no tenant-membership claims", func() {
|
||||
multiInstanceAuthenticator := AppAuthAuthenticator{
|
||||
Logger: log.NewLogger(),
|
||||
UserRoleAssigner: roleAssigner,
|
||||
MultiInstanceEnabled: true,
|
||||
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
|
||||
"GatewaySelector",
|
||||
"com.owncloud.api.gateway",
|
||||
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
|
||||
return mockGatewayClient{
|
||||
AuthenticateFunc: func(authType, clientID, clientSecret string) *gateway.AuthenticateResponse {
|
||||
return &gateway.AuthenticateResponse{Status: &rpcv1beta1.Status{Code: rpcv1beta1.Code_CODE_OK}}
|
||||
},
|
||||
}
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("test-user", "AppPassword")
|
||||
|
||||
req2, err := multiInstanceAuthenticator.Authenticate(req)
|
||||
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(req2).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
When("the account resolver is configured with a non-default PROXY_USER_OIDC_CLAIM", func() {
|
||||
It("still resolves the already-authenticated user, bypassing claim-based lookup", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me", http.NoBody)
|
||||
req.SetBasicAuth("test-user", "AppPassword")
|
||||
|
||||
authenticatedReq, err := authenticator.Authenticate(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
resolvedUser := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{Idp: "testIDP", OpaqueId: "abcd-1234"},
|
||||
Username: "alice",
|
||||
}
|
||||
tokenManager, err := jwt.New(map[string]interface{}{"secret": "change-me", "expires": int64(60)})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
s, err := scope.AddOwnerScope(nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
token, err := tokenManager.MintToken(context.Background(), resolvedUser, s)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
ub := backendmocks.UserBackend{}
|
||||
// services/proxy/pkg/middleware/account_resolver.go's verifyUser always looks
|
||||
// up the user by "username", regardless of the configured PROXY_USER_OIDC_CLAIM,
|
||||
// because the user arrives already authenticated via the request context.
|
||||
ub.On("GetUserByClaims", mock.Anything, "username", "alice", mock.Anything).Return(resolvedUser, token, nil)
|
||||
|
||||
resolver := AccountResolver(
|
||||
Logger(log.NewLogger()),
|
||||
UserProvider(&ub),
|
||||
UserRoleAssigner(roleAssigner),
|
||||
UserOIDCClaim("sub"),
|
||||
UserCS3Claim("userid"),
|
||||
)(mockHandler{})
|
||||
|
||||
rw := httptest.NewRecorder()
|
||||
resolver.ServeHTTP(rw, authenticatedReq)
|
||||
|
||||
Expect(rw.Code).To(Equal(http.StatusOK))
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/router"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
|
||||
userRoleMocks "github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"go-micro.dev/v4/store"
|
||||
@@ -81,10 +83,17 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
|
||||
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
|
||||
|
||||
logger := log.NewLogger()
|
||||
|
||||
roleAssigner := &userRoleMocks.UserRoleAssigner{}
|
||||
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
|
||||
).Maybe()
|
||||
|
||||
authenticators = []Authenticator{
|
||||
BasicAuthenticator{
|
||||
Logger: logger,
|
||||
UserProvider: &ub,
|
||||
Logger: logger,
|
||||
UserProvider: &ub,
|
||||
UserRoleAssigner: roleAssigner,
|
||||
},
|
||||
&OIDCAuthenticator{
|
||||
OIDCIss: "http://idp.example.com",
|
||||
@@ -151,7 +160,7 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
|
||||
testHandler.ServeHTTP(rr, req)
|
||||
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
|
||||
})
|
||||
It("ensures the context oidc data when user the Basic authentication is successful", func() {
|
||||
It("ensures the authenticated user is in the context when the Basic authentication is successful", func() {
|
||||
req := httptest.NewRequest("PROPFIND", "http://example.com/remote.php/dav/public-files/", http.NoBody)
|
||||
req = req.WithContext(router.SetRoutingInfo(context.Background(), router.RoutingInfo{}))
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
@@ -160,12 +169,12 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
|
||||
EnableBasicAuth(true),
|
||||
)
|
||||
testHandler := handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
Expect(oidc.FromContext(r.Context())).To(Equal(map[string]interface{}{
|
||||
"email": "testuser@example.com",
|
||||
"ownclouduuid": "OpaqueId",
|
||||
"iss": "IdpId",
|
||||
"preferred_username": "testuser",
|
||||
}))
|
||||
user, ok := revactx.ContextGetUser(r.Context())
|
||||
Expect(ok).To(Equal(true))
|
||||
Expect(user.GetId().GetIdp()).To(Equal("IdpId"))
|
||||
Expect(user.GetId().GetOpaqueId()).To(Equal("OpaqueId"))
|
||||
Expect(user.GetUsername()).To(Equal("testuser"))
|
||||
Expect(user.GetMail()).To(Equal("testuser@example.com"))
|
||||
}))
|
||||
rr := httptest.NewRecorder()
|
||||
testHandler.ServeHTTP(rr, req)
|
||||
|
||||
@@ -4,16 +4,17 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
)
|
||||
|
||||
// BasicAuthenticator is the authenticator responsible for HTTP Basic authentication.
|
||||
type BasicAuthenticator struct {
|
||||
Logger log.Logger
|
||||
UserProvider backend.UserBackend
|
||||
UserCS3Claim string
|
||||
UserOIDCClaim string
|
||||
Logger log.Logger
|
||||
UserProvider backend.UserBackend
|
||||
UserRoleAssigner userroles.UserRoleAssigner
|
||||
MultiInstanceEnabled bool
|
||||
}
|
||||
|
||||
// Authenticate implements the authenticator interface to authenticate requests via basic auth.
|
||||
@@ -25,6 +26,15 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, error)
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
if m.MultiInstanceEnabled {
|
||||
// Basic auth credentials carry no OIDC claims, so there is no way to
|
||||
// verify tenant membership (OCIS_MULTI_INSTANCE_MEMBER_CLAIM/GUEST_CLAIM)
|
||||
// for them. Reject rather than let the request bypass the tenant
|
||||
// check in services/proxy/pkg/middleware/account_resolver.go's
|
||||
// resolveUserType.
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
login, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
return nil, ErrAuthenticationFailed
|
||||
@@ -40,23 +50,21 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, error)
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
// fake oidc claims
|
||||
claims := map[string]interface{}{
|
||||
oidc.Iss: user.Id.Idp,
|
||||
oidc.PreferredUsername: user.Username,
|
||||
oidc.Email: user.Mail,
|
||||
oidc.OwncloudUUID: user.Id.OpaqueId,
|
||||
user, err = m.UserRoleAssigner.ApplyUserRole(r.Context(), user)
|
||||
if err != nil {
|
||||
m.Logger.Error().
|
||||
Err(err).
|
||||
Str("authenticator", "basic").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("could not apply user role")
|
||||
return nil, ErrAuthenticationFailed
|
||||
}
|
||||
|
||||
if m.UserCS3Claim == "userid" {
|
||||
// set the custom user claim only if users will be looked up by the userid on the CS3api
|
||||
// OpaqueId contains the userid configured in STORAGE_LDAP_USER_SCHEMA_UID
|
||||
claims[m.UserOIDCClaim] = user.Id.OpaqueId
|
||||
|
||||
}
|
||||
m.Logger.Debug().
|
||||
Str("authenticator", "basic").
|
||||
Str("path", r.URL.Path).
|
||||
Msg("successfully authenticated request")
|
||||
return r.WithContext(oidc.NewContext(r.Context(), claims)), nil
|
||||
// the user is already authenticated, put it into the context directly
|
||||
// instead of faking oidc claims for the account resolver to re-resolve.
|
||||
return r.WithContext(revactx.ContextSetUser(r.Context(), user)), nil
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
@@ -10,13 +11,17 @@ import (
|
||||
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
|
||||
userRoleMocks "github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/scope"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/token/manager/jwt"
|
||||
)
|
||||
|
||||
var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func() {
|
||||
var authenticator Authenticator
|
||||
var roleAssigner *userRoleMocks.UserRoleAssigner
|
||||
ub := mocks.UserBackend{}
|
||||
ub.On("Authenticate", mock.Anything, "testuser", "testpassword").Return(
|
||||
&userv1beta1.User{
|
||||
@@ -33,9 +38,15 @@ var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func()
|
||||
ub.On("Authenticate", mock.Anything, mock.Anything, mock.Anything).Return(nil, "", backend.ErrAccountNotFound)
|
||||
|
||||
BeforeEach(func() {
|
||||
roleAssigner = &userRoleMocks.UserRoleAssigner{}
|
||||
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
|
||||
).Maybe()
|
||||
|
||||
authenticator = BasicAuthenticator{
|
||||
Logger: log.NewLogger(),
|
||||
UserProvider: &ub,
|
||||
Logger: log.NewLogger(),
|
||||
UserProvider: &ub,
|
||||
UserRoleAssigner: roleAssigner,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -49,19 +60,83 @@ var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(req2).ToNot(BeNil())
|
||||
})
|
||||
It("adds claims to the request context", func() {
|
||||
It("puts the authenticated user into the request context", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
|
||||
req2, err := authenticator.Authenticate(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
claims := oidc.FromContext(req2.Context())
|
||||
Expect(claims).ToNot(BeNil())
|
||||
Expect(claims[oidc.Iss]).To(Equal("IdpId"))
|
||||
Expect(claims[oidc.PreferredUsername]).To(Equal("testuser"))
|
||||
Expect(claims[oidc.Email]).To(Equal("testuser@example.com"))
|
||||
Expect(claims[oidc.OwncloudUUID]).To(Equal("OpaqueId"))
|
||||
user, ok := revactx.ContextGetUser(req2.Context())
|
||||
Expect(ok).To(Equal(true))
|
||||
Expect(user.GetId().GetIdp()).To(Equal("IdpId"))
|
||||
Expect(user.GetId().GetOpaqueId()).To(Equal("OpaqueId"))
|
||||
Expect(user.GetUsername()).To(Equal("testuser"))
|
||||
Expect(user.GetMail()).To(Equal("testuser@example.com"))
|
||||
})
|
||||
})
|
||||
|
||||
When("multi-instance mode is enabled", func() {
|
||||
It("rejects the request, since basic auth credentials carry no tenant-membership claims", func() {
|
||||
multiInstanceAuthenticator := BasicAuthenticator{
|
||||
Logger: log.NewLogger(),
|
||||
UserProvider: &ub,
|
||||
UserRoleAssigner: roleAssigner,
|
||||
MultiInstanceEnabled: true,
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
|
||||
req2, err := multiInstanceAuthenticator.Authenticate(req)
|
||||
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(req2).To(BeNil())
|
||||
})
|
||||
})
|
||||
|
||||
When("the account resolver is configured with a non-default PROXY_USER_OIDC_CLAIM", func() {
|
||||
It("still resolves the already-authenticated user, bypassing claim-based lookup", func() {
|
||||
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me", http.NoBody)
|
||||
req.SetBasicAuth("testuser", "testpassword")
|
||||
|
||||
authenticatedReq, err := authenticator.Authenticate(req)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
resolvedUser := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{Idp: "IdpId", OpaqueId: "OpaqueId"},
|
||||
Username: "testuser",
|
||||
}
|
||||
tokenManager, err := jwt.New(map[string]interface{}{"secret": "change-me", "expires": int64(60)})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
s, err := scope.AddOwnerScope(nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
token, err := tokenManager.MintToken(context.Background(), resolvedUser, s)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
resolverBackend := mocks.UserBackend{}
|
||||
// services/proxy/pkg/middleware/account_resolver.go's verifyUser always looks
|
||||
// up the user by "username", regardless of the configured PROXY_USER_OIDC_CLAIM,
|
||||
// because the user arrives already authenticated via the request context.
|
||||
resolverBackend.On("GetUserByClaims", mock.Anything, "username", "testuser", mock.Anything).Return(resolvedUser, token, nil)
|
||||
|
||||
roleAssigner := &userRoleMocks.UserRoleAssigner{}
|
||||
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
|
||||
).Maybe()
|
||||
|
||||
resolver := AccountResolver(
|
||||
Logger(log.NewLogger()),
|
||||
UserProvider(&resolverBackend),
|
||||
UserRoleAssigner(roleAssigner),
|
||||
UserOIDCClaim("sub"),
|
||||
UserCS3Claim("userid"),
|
||||
)(mockHandler{})
|
||||
|
||||
rw := httptest.NewRecorder()
|
||||
resolver.ServeHTTP(rw, authenticatedReq)
|
||||
|
||||
Expect(rw.Code).To(Equal(http.StatusOK))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,11 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
cs3 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
|
||||
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
|
||||
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"go-micro.dev/v4/metadata"
|
||||
)
|
||||
|
||||
type defaultRoleAssigner struct {
|
||||
@@ -39,27 +35,9 @@ func (d defaultRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(roleIDs) == 0 {
|
||||
// This user doesn't have a role assignment yet. Assign a
|
||||
// default user role. At least until proper roles are provided. See
|
||||
// https://github.com/owncloud/ocis/issues/1825 for more context.
|
||||
if user.Id.Type == cs3.UserType_USER_TYPE_PRIMARY || user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
|
||||
roleId := settingsService.BundleUUIDRoleUser
|
||||
if user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
|
||||
roleId = settingsService.BundleUUIDRoleUserLight
|
||||
}
|
||||
d.logger.Info().Str("userid", user.Id.OpaqueId).Msg("user has no role assigned, assigning default user role")
|
||||
ctx = metadata.Set(ctx, middleware.AccountID, user.Id.OpaqueId)
|
||||
_, err := d.roleService.AssignRoleToUser(ctx, &settingssvc.AssignRoleToUserRequest{
|
||||
AccountUuid: user.Id.OpaqueId,
|
||||
RoleId: roleId,
|
||||
})
|
||||
if err != nil {
|
||||
d.logger.Error().Err(err).Msg("Could not add default role")
|
||||
return nil, err
|
||||
}
|
||||
roleIDs = append(roleIDs, roleId)
|
||||
}
|
||||
roleIDs, err = bootstrapDefaultRoleIfNeeded(ctx, user, roleIDs, d.roleService, d.logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +54,11 @@ func (d defaultRoleAssigner) ApplyUserRole(ctx context.Context, user *cs3.User)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
roleIDs, err = bootstrapDefaultRoleIfNeeded(ctx, user, roleIDs, d.roleService, d.logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user.Opaque = utils.AppendJSONToOpaque(user.Opaque, "roles", roleIDs)
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package userroles
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
cs3user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
|
||||
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
|
||||
graphmocks "github.com/owncloud/ocis/v2/services/graph/mocks"
|
||||
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// TestApplyUserRoleBootstrapsDefaultRoleForNewUser verifies that ApplyUserRole,
|
||||
// just like UpdateUserRoleAssignment, assigns a default role to a user who
|
||||
// doesn't have one yet. This matters for authentication paths (such as app
|
||||
// passwords) that only call ApplyUserRole and never go through claims-based
|
||||
// UpdateUserRoleAssignment, so a user who never logged in interactively must
|
||||
// still end up with a role.
|
||||
func TestApplyUserRoleBootstrapsDefaultRoleForNewUser(t *testing.T) {
|
||||
const userOpaqueID = "user-1"
|
||||
|
||||
roleService := &graphmocks.RoleService{}
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListRoleAssignmentsResponse{}, nil)
|
||||
roleService.On("AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
|
||||
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == settingsService.BundleUUIDRoleUser
|
||||
}), mock.Anything).Return(&settingssvc.AssignRoleToUserResponse{Assignment: &settingsmsg.UserRoleAssignment{
|
||||
Id: "new-assignment-id",
|
||||
AccountUuid: userOpaqueID,
|
||||
RoleId: settingsService.BundleUUIDRoleUser,
|
||||
}}, nil)
|
||||
|
||||
ra := NewDefaultRoleAssigner(WithRoleService(roleService), WithLogger(log.NopLogger()))
|
||||
|
||||
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID, Type: cs3user.UserType_USER_TYPE_PRIMARY}}
|
||||
|
||||
updated, err := ra.ApplyUserRole(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
var roleIDs []string
|
||||
if err := utils.ReadJSONFromOpaque(updated.GetOpaque(), "roles", &roleIDs); err != nil {
|
||||
t.Fatalf("could not read roles from opaque: %v", err)
|
||||
}
|
||||
if len(roleIDs) != 1 || roleIDs[0] != settingsService.BundleUUIDRoleUser {
|
||||
t.Fatalf("expected the default user role to be bootstrapped, got %v", roleIDs)
|
||||
}
|
||||
|
||||
roleService.AssertCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
|
||||
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == settingsService.BundleUUIDRoleUser
|
||||
}), mock.Anything)
|
||||
}
|
||||
|
||||
// TestApplyUserRoleDoesNotBootstrapForLightweightUser verifies that
|
||||
// ApplyUserRole never assigns a default role to a lightweight (federated)
|
||||
// user, mirroring UpdateUserRoleAssignment's existing behavior.
|
||||
func TestApplyUserRoleDoesNotBootstrapForLightweightUser(t *testing.T) {
|
||||
const userOpaqueID = "lightweight-user-1"
|
||||
|
||||
roleService := &graphmocks.RoleService{}
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListRoleAssignmentsResponse{}, nil)
|
||||
|
||||
ra := NewDefaultRoleAssigner(WithRoleService(roleService), WithLogger(log.NopLogger()))
|
||||
|
||||
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID, Type: cs3user.UserType_USER_TYPE_LIGHTWEIGHT}}
|
||||
|
||||
_, err := ra.ApplyUserRole(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
@@ -6,9 +6,12 @@ import (
|
||||
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
|
||||
cs3 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
ocismiddleware "github.com/owncloud/ocis/v2/ocis-pkg/middleware"
|
||||
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
|
||||
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"go-micro.dev/v4/metadata"
|
||||
)
|
||||
|
||||
// UserRoleAssigner allows providing different implementations for how users get their default roles
|
||||
@@ -77,6 +80,35 @@ func WithServiceAccount(c config.ServiceAccount) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// bootstrapDefaultRoleIfNeeded assigns the default "User" role (or "User Light"
|
||||
// for guests) when the user has no role assignment yet, so that users who only
|
||||
// ever authenticate without going through UpdateUserRoleAssignment (e.g. via an
|
||||
// app password) still end up with a role. See
|
||||
// https://github.com/owncloud/ocis/issues/1825 for context.
|
||||
func bootstrapDefaultRoleIfNeeded(ctx context.Context, user *cs3.User, roleIDs []string, roleService settingssvc.RoleService, logger log.Logger) ([]string, error) {
|
||||
if len(roleIDs) != 0 {
|
||||
return roleIDs, nil
|
||||
}
|
||||
if user.Id.Type != cs3.UserType_USER_TYPE_PRIMARY && user.Id.Type != cs3.UserType_USER_TYPE_GUEST {
|
||||
return roleIDs, nil
|
||||
}
|
||||
|
||||
roleID := settingsService.BundleUUIDRoleUser
|
||||
if user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
|
||||
roleID = settingsService.BundleUUIDRoleUserLight
|
||||
}
|
||||
logger.Info().Str("userid", user.Id.OpaqueId).Msg("user has no role assigned, assigning default user role")
|
||||
ctx = metadata.Set(ctx, ocismiddleware.AccountID, user.Id.OpaqueId)
|
||||
if _, err := roleService.AssignRoleToUser(ctx, &settingssvc.AssignRoleToUserRequest{
|
||||
AccountUuid: user.Id.OpaqueId,
|
||||
RoleId: roleID,
|
||||
}); err != nil {
|
||||
logger.Error().Err(err).Msg("Could not add default role")
|
||||
return nil, err
|
||||
}
|
||||
return append(roleIDs, roleID), nil
|
||||
}
|
||||
|
||||
// loadRolesIDs returns the role-ids assigned to an user
|
||||
func loadRolesIDs(ctx context.Context, opaqueUserID string, rs settingssvc.RoleService) ([]string, error) {
|
||||
req := &settingssvc.ListRoleAssignmentsRequest{AccountUuid: opaqueUserID}
|
||||
|
||||
@@ -84,7 +84,7 @@ type LDAPDriver struct {
|
||||
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;USERS_LDAP_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Valid options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed." introductionVersion:"pre5.0"`
|
||||
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;USERS_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
|
||||
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;USERS_LDAP_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance resolves every user in the shared LDAP directory." introductionVersion:"7.0"`
|
||||
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
|
||||
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
|
||||
UserSchema LDAPUserSchema `yaml:"user_schema"`
|
||||
|
||||
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
|
||||
return shared.MissingLDAPBindPassword(cfg.Service.Name)
|
||||
}
|
||||
|
||||
if cfg.Driver == "ldap" && cfg.Drivers.LDAP.MasterID != "" && cfg.Drivers.LDAP.UserFilter == "" {
|
||||
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/owncloud/ocis/v2/services/users/pkg/config"
|
||||
)
|
||||
|
||||
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "users"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "users"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "master-1",
|
||||
UserFilter: "(ownCloudMemberOf=instance-1)",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Service: config.Service{Name: "users"},
|
||||
TokenManager: &config.TokenManager{JWTSecret: "secret"},
|
||||
Driver: "ldap",
|
||||
Drivers: config.Drivers{
|
||||
LDAP: config.LDAPDriver{
|
||||
BindPassword: "secret",
|
||||
MasterID: "",
|
||||
UserFilter: "",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := Validate(cfg)
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
Reference in new issue
Block a user