fix(proxy): [OCISDEV-1464] fix the role assignment of multi-instance guests (#13250)
* fix(proxy): [OCISDEV-1464] fail on an unknown multi-instance guest role The OIDC role assigner did not check that OCIS_MULTI_INSTANCE_GUEST_ROLE exists. When the guest role name is wrong, the role name has no role id. The proxy then sent AssignRoleToUser with an empty RoleId on each request. The role assigner now returns an "unknown role" error and does not change the role assignment. A test covers a guest that no guest role mapping matches. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(proxy): [OCISDEV-1464] check the guest role mapping more strictly GuestRoleMapping now trims the spaces around the claim value and the role name. The env var parser trims list elements, but the yaml parser does not. Before this change, the yaml entry "spaceadmin: user-light-vault" gave the role name " user-light-vault", and each matching guest login failed with "unknown role". GuestRoleMapping now also rejects a mapping when OCIS_MULTI_INSTANCE_GUEST_ROLE is empty. The role assigner applies the mapping only to users that get the guest role. Without a guest role, the proxy ignored the mapping and gave guests a member role. gofmt also fixes the indent of a TODO comment in the same file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(proxy): [OCISDEV-1464] log why the guest role mapping does not apply mapGuestRole dropped the extractRoles error without a log line. When PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM had a wrong claim name, each guest kept the guest role, and the admin could not find the cause. mapGuestRole now writes a debug log line with the claim name and the error. A guest without a roles claim is valid, and the role assigner runs on each request, so the log level is debug and not warning. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(proxy): [OCISDEV-1464] tell that guest claim values are regexes The guest role mapping uses the same claim matcher as the role mapping. A claim value is an exact string or a regular expression that must match the full claim value. The description of OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING did not tell this. An admin who writes 'school.admin' also matches the claim 'schoolXadmin', and that guest can get a role with more permissions. The description now tells that claim values are regexes. It also tells the admin to escape regex metacharacters in an exact string. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(proxy): [OCISDEV-1464] read the roles again for an unknown guest role The OIDC role assigner checks the guest role and the mapped guest role against a role cache with a 5 minute TTL. A role that an admin created after the last cache read was unknown. For up to 5 minutes, each request of a matching guest failed with "unknown role" and HTTP 500. The new function guestRoleName reads the roles again one time when the role is unknown. It reads the roles again only when the cache is older than 30 seconds. Thus a role that does not exist causes a maximum of one ListRoles request in 30 seconds, and not one request for each guest request. The check for an unknown guest role moves into guestRoleName. roleNamesToRoleIDs now has a maxAge parameter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: [OCISDEV-1464] add the changelog for the guest role mapping fixes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
64b18f5432
commit
4680d9d905
4 files changed
+193
-17
No files matched your search
@@ -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
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
Reference in new issue
Block a user