diff --git a/changelog/unreleased/fix-multi-instance-guest-role-mapping.md b/changelog/unreleased/fix-multi-instance-guest-role-mapping.md new file mode 100644 index 00000000000..3cd2f5d2b6f --- /dev/null +++ b/changelog/unreleased/fix-multi-instance-guest-role-mapping.md @@ -0,0 +1,19 @@ +Bugfix: Fix the role assignment of multi-instance guests + +The proxy now rejects an unknown multi-instance guest role. Before this +fix, the proxy assigned an empty role id when +`OCIS_MULTI_INSTANCE_GUEST_ROLE` named a role that does not exist. + +The proxy now trims the spaces in the pairs of +`OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING`. The proxy does not start when the +mapping is set and `OCIS_MULTI_INSTANCE_GUEST_ROLE` is empty. + +When a guest role is not in the role cache, the proxy reads the roles again. +Thus a new role works before the cache time ends. The proxy reads the roles +a maximum of one time in 30 seconds. + +The proxy writes a debug log line when the roles claim of a guest is missing. +The description of `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` now tells that +a claim value is a regular expression. + +https://github.com/owncloud/ocis/pull/13250 diff --git a/services/proxy/pkg/config/config.go b/services/proxy/pkg/config/config.go index 73160af6f5c..311742276e1 100644 --- a/services/proxy/pkg/config/config.go +++ b/services/proxy/pkg/config/config.go @@ -265,5 +265,5 @@ type MultiInstanceConfig struct { MemberClaim string `yaml:"member_claim" env:"OCIS_MULTI_INSTANCE_MEMBER_CLAIM" desc:"The claim name for the 'memberOf' property" introductionVersion:"8.0.0"` GuestClaim string `yaml:"guest_claim" env:"OCIS_MULTI_INSTANCE_GUEST_CLAIM" desc:"The claim name for the 'guestOf' property" introductionVersion:"8.0.0"` GuestRole string `yaml:"guest_role" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE" desc:"The role that should be assigned to a guest user" introductionVersion:"8.0.0"` - GuestRoleMapping []string `yaml:"guest_role_mapping" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING" desc:"(Optional) Mapping of PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM values to the role a guest gets instead of OCIS_MULTI_INSTANCE_GUEST_ROLE. Example: 'spaceadmin:user-light-vault'. The first match wins. Role names must not contain a colon. Only applies to the 'oidc' role assignment driver." introductionVersion:"9.0.0"` + GuestRoleMapping []string `yaml:"guest_role_mapping" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING" desc:"(Optional) Mapping of PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM values to the role a guest gets instead of OCIS_MULTI_INSTANCE_GUEST_ROLE. Example: 'spaceadmin:user-light-vault'. A claim value is an exact string or a regular expression that must match the full claim value, the same as the claim_value of the role mapping. Escape regex metacharacters such as '.' in an exact string. The first match wins. Role names must not contain a colon. Only applies to the 'oidc' role assignment driver." introductionVersion:"9.0.0"` } diff --git a/services/proxy/pkg/userroles/oidcroles.go b/services/proxy/pkg/userroles/oidcroles.go index ea79a5a6eaa..641deeaafd9 100644 --- a/services/proxy/pkg/userroles/oidcroles.go +++ b/services/proxy/pkg/userroles/oidcroles.go @@ -103,15 +103,15 @@ func matchesClaimMapping(mappingValue string, claimRoles map[string]struct{}) bo func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *cs3user.User, claims map[string]interface{}, overwriteRole string) (*cs3user.User, error) { userID := user.GetId().GetOpaqueId() logger := ra.logger.SubloggerWithRequestID(ctx).With().Str("userid", userID).Logger() - roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx) + roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx, roleCacheTTL) if err != nil { logger.Error().Err(err).Msg("Error mapping role names to role ids") return nil, err } // the account resolver passes the guest role as overwriteRole for multi-instance guests - if overwriteRole != "" && len(ra.guestMapping) > 0 { - overwriteRole, err = ra.mapGuestRole(claims, overwriteRole, roleNamesToRoleIDs) + if overwriteRole != "" { + overwriteRole, roleNamesToRoleIDs, err = ra.guestRoleName(ctx, claims, overwriteRole, roleNamesToRoleIDs) if err != nil { logger.Error().Err(err).Msg("Error mapping guest role") return nil, err @@ -186,7 +186,7 @@ func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *c return nil, err } - // TODO: check if it's ctx or newctx + // TODO: check if it's ctx or newctx canCreateDrives, err := utils.CheckPermission(revactx.ContextSetUser(ctx, user), "Drives.Create", client) if err != nil { // The permission could not be determined. Fail closed: leave the personal @@ -226,18 +226,62 @@ func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) { if len(pairs) > 0 && cfg.RoleAssignment.Driver != "oidc" { return nil, fmt.Errorf("the guest role mapping requires the 'oidc' role assignment driver, not '%s'", cfg.RoleAssignment.Driver) } + // the role assigner only applies the mapping to users that get the guest role + if len(pairs) > 0 && cfg.MultiInstance.GuestRole == "" { + return nil, errors.New("the guest role mapping requires OCIS_MULTI_INSTANCE_GUEST_ROLE") + } mappings := make([]config.RoleMapping, 0, len(pairs)) for _, pair := range pairs { i := strings.LastIndex(pair, ":") - if i <= 0 || i == len(pair)-1 { + // the env var parser trims list elements, the yaml parser does not + claimValue, roleName := "", "" + if i >= 0 { + claimValue, roleName = strings.TrimSpace(pair[:i]), strings.TrimSpace(pair[i+1:]) + } + if claimValue == "" || roleName == "" { return nil, fmt.Errorf("invalid guest role mapping '%s', expected 'claimvalue:rolename'", pair) } - mappings = append(mappings, config.RoleMapping{ClaimValue: pair[:i], RoleName: pair[i+1:]}) + mappings = append(mappings, config.RoleMapping{ClaimValue: claimValue, RoleName: roleName}) } return mappings, nil } +// guestRoleName returns the role name of a multi-instance guest and the role name to role id map +// that knows this role. A role that the cached map does not know can be a new role, so +// guestRoleName reads the roles again one time. An unknown role is an error: do not assign an +// empty role id. +func (ra oidcRoleAssigner) guestRoleName(ctx context.Context, claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, map[string]string, error) { + resolve := func(roleNamesToRoleIDs map[string]string) (string, error) { + roleName := guestRole + if len(ra.guestMapping) > 0 { + var err error + if roleName, err = ra.mapGuestRole(claims, guestRole, roleNamesToRoleIDs); err != nil { + return "", err + } + } + if _, ok := roleNamesToRoleIDs[roleName]; !ok { + return "", fmt.Errorf("unknown role '%s'", roleName) + } + return roleName, nil + } + + roleName, err := resolve(roleNamesToRoleIDs) + if err == nil { + return roleName, roleNamesToRoleIDs, nil + } + // the minimum age limits the reads for a role that does not exist + roleNamesToRoleIDs, rerr := ra.roleNamesToRoleIDs(ctx, roleCacheMinAge) + if rerr != nil { + return "", nil, rerr + } + roleName, err = resolve(roleNamesToRoleIDs) + if err != nil { + return "", nil, err + } + return roleName, roleNamesToRoleIDs, nil +} + // mapGuestRole returns the role of the first guest role mapping that matches a value of the // user's roles claim, or guestRole when nothing matches. A mapping to a role that does not exist // is an error: it can only be a misconfiguration, and falling back to guestRole could give the @@ -245,6 +289,8 @@ func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) { func (ra oidcRoleAssigner) mapGuestRole(claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, error) { claimRoles, err := extractRoles(ra.rolesClaim, claims) if err != nil || len(claimRoles) == 0 { + // a guest without roles claim is valid, log at debug level to help find a wrong claim name + ra.logger.Debug().Err(err).Str("claim", ra.rolesClaim).Msg("no roles in claim, the guest keeps the guest role") return guestRole, nil } @@ -297,11 +343,19 @@ type roleNameToIDCache struct { var roleNameToID roleNameToIDCache -func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]string, error) { - cacheTTL := 5 * time.Minute +const ( + // roleCacheTTL is the maximum age of the cached role name to role id map + roleCacheTTL = 5 * time.Minute + // roleCacheMinAge is the age that the cached map must have before a read for an unknown role + roleCacheMinAge = 30 * time.Second +) + +// roleNamesToRoleIDs returns the cached role name to role id map. When the map is older than +// maxAge, roleNamesToRoleIDs reads the roles from the settings service. +func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context, maxAge time.Duration) (map[string]string, error) { roleNameToID.lock.RLock() - if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL { + if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge { defer roleNameToID.lock.RUnlock() return roleNameToID.roleNameToID, nil } @@ -313,7 +367,7 @@ func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]s defer roleNameToID.lock.Unlock() // check again, another goroutine might have updated while we "upgraded" the lock - if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL { + if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge { return roleNameToID.roleNameToID, nil } diff --git a/services/proxy/pkg/userroles/oidcroles_test.go b/services/proxy/pkg/userroles/oidcroles_test.go index c5dcbaea551..bc1f86805d7 100644 --- a/services/proxy/pkg/userroles/oidcroles_test.go +++ b/services/proxy/pkg/userroles/oidcroles_test.go @@ -485,15 +485,25 @@ func TestUpdateUserRoleAssignmentFailsOnUnknownGuestRole(t *testing.T) { t.Fatalf("expected an error for the guest role mapping to an unknown role, got %v", err) } roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything) + + // a guest that no mapping matches gets the guest role, which must exist too + claims = map[string]interface{}{"roles": []interface{}{"user"}} + _, err = ra.UpdateUserRoleAssignment(context.Background(), user, claims, "no-such-guest-role") + if err == nil || !strings.Contains(err.Error(), "unknown role 'no-such-guest-role'") { + t.Fatalf("expected an error for an unknown guest role, got %v", err) + } + roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything) } func TestGuestRoleMapping(t *testing.T) { tests := []struct { - name string - driver string - pairs []string - want []config.RoleMapping - wantErr bool + name string + driver string + // noGuestRole leaves OCIS_MULTI_INSTANCE_GUEST_ROLE empty + noGuestRole bool + pairs []string + want []config.RoleMapping + wantErr bool }{ { name: "empty", @@ -516,16 +526,29 @@ func TestGuestRoleMapping(t *testing.T) { pairs: []string{"urn:ocis:spaceadmin:user-light-vault"}, want: []config.RoleMapping{{ClaimValue: "urn:ocis:spaceadmin", RoleName: "user-light-vault"}}, }, + { + name: "spaces around the claim value and the role name are trimmed", + driver: "oidc", + pairs: []string{" spaceadmin : user-light-vault "}, + want: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}}, + }, {name: "requires the oidc driver", driver: "default", pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true}, + {name: "requires a guest role", driver: "oidc", noGuestRole: true, pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true}, {name: "missing colon", driver: "oidc", pairs: []string{"spaceadmin"}, wantErr: true}, {name: "missing claim value", driver: "oidc", pairs: []string{":user-light-vault"}, wantErr: true}, {name: "missing role name", driver: "oidc", pairs: []string{"spaceadmin:"}, wantErr: true}, + {name: "blank claim value", driver: "oidc", pairs: []string{" :user-light-vault"}, wantErr: true}, + {name: "blank role name", driver: "oidc", pairs: []string{"spaceadmin: "}, wantErr: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + guestRole := "user-light" + if tt.noGuestRole { + guestRole = "" + } cfg := &config.Config{ RoleAssignment: config.RoleAssignment{Driver: tt.driver}, - MultiInstance: config.MultiInstanceConfig{GuestRoleMapping: tt.pairs}, + MultiInstance: config.MultiInstanceConfig{GuestRole: guestRole, GuestRoleMapping: tt.pairs}, } got, err := GuestRoleMapping(cfg) if tt.wantErr { @@ -543,3 +566,83 @@ func TestGuestRoleMapping(t *testing.T) { }) } } + +// TestGuestRoleNameRefreshesRoles verifies that a role which the cached role map does not know +// makes the assigner read the roles again, so a new role works before the cache TTL ends. The +// assigner reads the roles again only when the cached map is older than roleCacheMinAge. +func TestGuestRoleNameRefreshesRoles(t *testing.T) { + gatewayClient := &cs3mocks.GatewayAPIClient{} + gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient]( + "GatewaySelector", + "com.owncloud.api.gateway", + func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient { + return gatewayClient + }, + ) + defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway") + + // listing the roles needs a service account context + gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{ + Status: &rpc.Status{Code: rpc.Code_CODE_OK}, + Token: "service-token", + }, nil) + + claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}} + cached := map[string]string{"user-light": "user-light-id"} + + tests := []struct { + name string + cacheAge time.Duration + wantRole string + wantErr bool + wantReads int + }{ + {name: "an old cache is read again", cacheAge: time.Minute, wantRole: "user-light-vault", wantReads: 1}, + {name: "a fresh cache is not read again", cacheAge: 0, wantErr: true, wantReads: 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + roleNameToID.lock.Lock() + roleNameToID.roleNameToID = cached + roleNameToID.lastRead = time.Now().Add(-tt.cacheAge) + roleNameToID.lock.Unlock() + + roleService := &graphmocks.RoleService{} + roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return( + &settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{ + {Id: "user-light-id", Name: "user-light"}, + {Id: "user-light-vault-id", Name: "user-light-vault"}, + }}, nil) + + ra := oidcRoleAssigner{Options: Options{ + logger: log.NopLogger(), + gatewaySelector: gatewaySelector, + roleService: roleService, + rolesClaim: "roles", + guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}}, + serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"}, + }} + + got, roleIDs, err := ra.guestRoleName(context.Background(), claims, "user-light", cached) + roleService.AssertNumberOfCalls(t, "ListRoles", tt.wantReads) + if tt.wantErr { + if err == nil || !strings.Contains(err.Error(), "unknown role 'user-light-vault'") { + t.Fatalf("expected an unknown role error, got role %q and error %v", got, err) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != tt.wantRole || roleIDs[got] != "user-light-vault-id" { + t.Fatalf("got role %q with id %q, want %q", got, roleIDs[got], tt.wantRole) + } + }) + } + + // reset the package-global role-name cache for the other tests + roleNameToID.lock.Lock() + roleNameToID.roleNameToID = nil + roleNameToID.lastRead = time.Time{} + roleNameToID.lock.Unlock() +}