diff --git a/changelog/unreleased/bugfix-vault-route-permission.md b/changelog/unreleased/bugfix-vault-route-permission.md new file mode 100644 index 00000000000..5e36d99f35c --- /dev/null +++ b/changelog/unreleased/bugfix-vault-route-permission.md @@ -0,0 +1,6 @@ +Bugfix: Deny Safe/Vault access to users without permission + +Users whose role did not grant Safe access could still reach it by editing the URL. +Such users are now denied and shown the access-denied page. + +https://github.com/owncloud/ocis/pull/12884 diff --git a/services/graph/pkg/middleware/require.go b/services/graph/pkg/middleware/require.go index 585caaf6584..2c9385e23b5 100644 --- a/services/graph/pkg/middleware/require.go +++ b/services/graph/pkg/middleware/require.go @@ -9,6 +9,7 @@ import ( "github.com/owncloud/ocis/v2/ocis-pkg/roles" "github.com/owncloud/ocis/v2/services/graph/pkg/errorcode" settings "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0" + settingsdefaults "github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults" revactx "github.com/owncloud/reva/v2/pkg/ctx" ) @@ -55,6 +56,49 @@ func RequireAdmin(rm *roles.Manager, logger log.Logger) func(next http.Handler) } } +// RequireVaultPermission middleware is used to require the user in context to have the vault mode permission +func RequireVaultPermission(rm *roles.Manager, logger log.Logger) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + l := logger.With().Str("middleware", "requireVaultPermission").Logger() + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u, ok := revactx.ContextGetUser(r.Context()) + if !ok { + errorcode.AccessDenied.Render(w, r, http.StatusUnauthorized, "Unauthorized") + return + } + if u.Id == nil || u.Id.OpaqueId == "" { + errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "user is missing an id") + return + } + // get roles from context + roleIDs, ok := roles.ReadRoleIDsFromContext(r.Context()) + if !ok { + l.Debug().Str("userid", u.Id.OpaqueId).Msg("No roles in context, contacting settings service") + var err error + roleIDs, err = rm.FindRoleIDsForUser(r.Context(), u.Id.OpaqueId) + if err != nil { + l.Error().Err(err).Str("userid", u.Id.OpaqueId).Msg("Failed to get roles for user") + errorcode.AccessDenied.Render(w, r, http.StatusUnauthorized, "Unauthorized") + return + } + if len(roleIDs) == 0 { + l.Error().Err(err).Str("userid", u.Id.OpaqueId).Msg("No roles assigned to user") + errorcode.AccessDenied.Render(w, r, http.StatusUnauthorized, "Unauthorized") + return + } + } + + // check if permission is present in roles of the authenticated account + if rm.FindPermissionByID(r.Context(), roleIDs, settingsdefaults.VaultModePermission(settingsdefaults.Own).GetId()) != nil { + next.ServeHTTP(w, r) + return + } + + errorcode.AccessDenied.Render(w, r, http.StatusForbidden, "Forbidden") + }) + } +} + // RequireSelfUserID middleware ensures the "userID" URL parameter matches the opaque ID of the user in context. // It is used to restrict endpoints so that users can only act on their own resources. func RequireSelfUserID(logger log.Logger) func(next http.Handler) http.Handler { diff --git a/services/graph/pkg/middleware/require_test.go b/services/graph/pkg/middleware/require_test.go new file mode 100644 index 00000000000..8bb73a1156e --- /dev/null +++ b/services/graph/pkg/middleware/require_test.go @@ -0,0 +1,98 @@ +package middleware + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1" + "github.com/owncloud/ocis/v2/ocis-pkg/log" + ocismw "github.com/owncloud/ocis/v2/ocis-pkg/middleware" + "github.com/owncloud/ocis/v2/ocis-pkg/roles" + settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0" + settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0" + settingsdefaults "github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults" + revactx "github.com/owncloud/reva/v2/pkg/ctx" + "go-micro.dev/v4/client" + "go-micro.dev/v4/metadata" +) + +// roleService adds the method the generated MockRoleService lacks, so it satisfies settingssvc.RoleService. +type roleService struct { + settingssvc.MockRoleService +} + +func (roleService) ListRoleAssignmentsFiltered(context.Context, *settingssvc.ListRoleAssignmentsFilteredRequest, ...client.CallOption) (*settingssvc.ListRoleAssignmentsResponse, error) { + panic("ListRoleAssignmentsFiltered was called in test but not mocked") +} + +func TestRequireVaultPermission(t *testing.T) { + const roleID = "role-1" + vaultPermissionID := settingsdefaults.VaultModePermission(settingsdefaults.Own).GetId() + + bundleWith := func(permissionIDs ...string) *settingsmsg.Bundle { + settings := make([]*settingsmsg.Setting, 0, len(permissionIDs)) + for _, id := range permissionIDs { + settings = append(settings, &settingsmsg.Setting{Id: id}) + } + return &settingsmsg.Bundle{Id: roleID, Settings: settings} + } + + newManager := func(bundle *settingsmsg.Bundle) *roles.Manager { + rs := roleService{MockRoleService: settingssvc.MockRoleService{ + ListRolesFunc: func(ctx context.Context, req *settingssvc.ListBundlesRequest, opts ...client.CallOption) (*settingssvc.ListBundlesResponse, error) { + return &settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{bundle}}, nil + }, + }} + m := roles.NewManager(roles.Logger(log.NopLogger()), roles.RoleService(rs)) + return &m + } + + withUserAndRoles := func(ctx context.Context) context.Context { + ctx = revactx.ContextSetUser(ctx, &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: "user-1"}}) + roleIDsJSON, _ := json.Marshal([]string{roleID}) + return metadata.Set(ctx, ocismw.RoleIDs, string(roleIDsJSON)) + } + + tests := []struct { + name string + ctx context.Context + bundle *settingsmsg.Bundle + wantStatus int + }{ + { + name: "role holds the vault permission -> allowed", + ctx: withUserAndRoles(context.Background()), + bundle: bundleWith(vaultPermissionID), + wantStatus: http.StatusOK, + }, + { + name: "role lacks the vault permission -> forbidden", + ctx: withUserAndRoles(context.Background()), + bundle: bundleWith("some-other-permission"), + wantStatus: http.StatusForbidden, + }, + { + name: "no user in context -> unauthorized", + ctx: context.Background(), + bundle: bundleWith(vaultPermissionID), + wantStatus: http.StatusUnauthorized, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + handler := RequireVaultPermission(newManager(tt.bundle), log.NopLogger())(dummyHandler{}) + + req := httptest.NewRequest(http.MethodGet, "/vault/graph", nil).WithContext(tt.ctx) + rr := httptest.NewRecorder() + handler.ServeHTTP(rr, req) + + if rr.Code != tt.wantStatus { + t.Errorf("got status %d, want %d", rr.Code, tt.wantStatus) + } + }) + } +} diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go index f99d0848786..6e9b004d41b 100644 --- a/services/graph/pkg/service/v0/service.go +++ b/services/graph/pkg/service/v0/service.go @@ -420,8 +420,10 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx // Initialize the Vault routes if options.Config.EnableVaultMode { + requireVaultPermission := graphmw.RequireVaultPermission(roleManager, options.Logger) m.Route("/vault/graph", func(r chi.Router) { r.Use(autoprop.NewHttpHandler()) + r.Use(requireVaultPermission) r.Use(requireMFA) r.Use(graphmw.VaultModeMiddleware()) graphRoutes(r, blankMW) diff --git a/services/settings/pkg/store/defaults/defaults.go b/services/settings/pkg/store/defaults/defaults.go index e284b2cb96c..10d9d7995ba 100644 --- a/services/settings/pkg/store/defaults/defaults.go +++ b/services/settings/pkg/store/defaults/defaults.go @@ -219,7 +219,6 @@ func generateBundleUserRole() *settingsmsg.Bundle { LanguageManagementPermission(Own), ListFavoritesPermission(Own), SelfManagementPermission(Own), - VaultModePermission(Own), WriteFavoritesPermission(Own), }, } diff --git a/tests/acceptance/features/apiVault/vault.feature b/tests/acceptance/features/apiVault/vault.feature index ad60348f956..087346edfdb 100644 --- a/tests/acceptance/features/apiVault/vault.feature +++ b/tests/acceptance/features/apiVault/vault.feature @@ -8,6 +8,7 @@ Feature: vault And these users have been created with default attributes: | username | | Alice | + And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API Scenario: user can create folders and files in personal space in vault @@ -396,6 +397,7 @@ Feature: vault Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API: @@ -474,6 +476,7 @@ Feature: vault Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API And user "Admin" has disabled a space "new-space" in vault @@ -522,6 +525,7 @@ Feature: vault Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API And user "Admin" has disabled a space "new-space" in vault @@ -569,6 +573,7 @@ Feature: vault Scenario Outline: try to send share invitation for personal space in vault to user with different roles (permissions endpoint) Given user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API: | space | Personal | @@ -615,6 +620,7 @@ Feature: vault Scenario Outline: try to share Shares space in vault with a user (permissions endpoint) Given user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API: | space | Shares | @@ -662,6 +668,7 @@ Feature: vault Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API When user "Alice" sends the following space share invitation using root endpoint of the Graph API: @@ -740,6 +747,7 @@ Feature: vault Scenario Outline: try to invite user to personal drive in vault with different roles using root endpoint Given user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI When user "Alice" tries to send the following space share invitation using root endpoint of the Graph API: | space | Personal | @@ -786,6 +794,7 @@ Feature: vault Scenario Outline: try to invite user to Shares drive in vault with different roles using root endpoint Given user "Alice" has logged in via web UI And user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Brian" has logged in via web UI When user "Alice" tries to send the following space share invitation using root endpoint of the Graph API: | space | Shares | @@ -994,6 +1003,7 @@ Feature: vault Scenario Outline: folder share received from vault and drive personal space should be isolated Given user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has logged in via web UI And user "Alice" has created a folder "driveFolder" in space "Personal" @@ -1028,6 +1038,7 @@ Feature: vault Scenario Outline: file share received from vault and drive personal space should be isolated Given user "Brian" has been created with default attributes + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has logged in via web UI And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFile.txt" @@ -1062,6 +1073,7 @@ Feature: vault Scenario Outline: folder share received from vault and drive project space should be isolated Given user "Brian" has been created with default attributes And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" with the default quota using the Graph API @@ -1099,6 +1111,7 @@ Feature: vault Scenario Outline: folder share received from vault and drive project space should be isolated Given user "Brian" has been created with default attributes And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API + And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API And user "Alice" has logged in via web UI And user "Brian" has logged in via web UI And user "Alice" has created a space "new-space" with the default quota using the Graph API @@ -1132,7 +1145,7 @@ Feature: vault | File Editor | - Scenario Outline: users with role Admin, Space Admin or User should have access to vault + Scenario Outline: users with role Admin or Space Admin should have access to vault Given the administrator has assigned the role "" to user "Alice" using the Graph API When user "Alice" gets the permissions list using the settings API Then the HTTP status code should be "201" @@ -1158,12 +1171,12 @@ Feature: vault | user-role | permission-count | | Admin | 33 | | Space Admin | 27 | - | User | 20 | - Scenario: user with role User Light should not have access to vault - Given the administrator has assigned the role "User Light" to user "Alice" using the Graph API - When user "Alice" gets the permissions list using the settings API + Scenario Outline: users with role User or User Light should not have access to vault + Given user "Brian" has been created with default attributes + And the administrator has assigned the role "" to user "Brian" using the Graph API + When user "Brian" gets the permissions list using the settings API Then the HTTP status code should be "201" And the JSON data of the response should match """ @@ -1173,8 +1186,8 @@ Feature: vault "properties": { "permissions": { "type": "array", - "minItems": 13, - "maxItems": 13, + "minItems": , + "maxItems": , "uniqueItems": true, "not": { "contains": { @@ -1185,4 +1198,8 @@ Feature: vault } } """ + Examples: + | user-role | permission-count | + | User | 19 | + | User Light | 13 | diff --git a/web/packages/web-runtime/src/services/auth/authService.ts b/web/packages/web-runtime/src/services/auth/authService.ts index 530979d2ac2..195f78ef9d8 100644 --- a/web/packages/web-runtime/src/services/auth/authService.ts +++ b/web/packages/web-runtime/src/services/auth/authService.ts @@ -131,6 +131,16 @@ export class AuthService implements AuthServiceInterface { } if (to.params.scope === 'vault') { + // Deny users without vault access instead of handing them to the IdP for MFA. Abilities + // are only loaded once the user context is ready; on a cold load the backend guard applies. + if (this.authStore.userContextReady && !this.ability.can('read-all', 'Vault')) { + await this.router.push({ + name: 'accessDenied', + query: { redirectUrl: to.fullPath } + }) + return + } + // Capabilities carry the required MFA level name. Fetch them directly (without // establishing the user context) so we can enforce the ACR before any vault data // is loaded. Establishing the user context here would flip `userContextReady`, diff --git a/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts b/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts index be9dab594eb..73db0e6be85 100644 --- a/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts +++ b/web/packages/web-runtime/tests/unit/services/auth/authService.spec.ts @@ -1,6 +1,7 @@ -import { ConfigStore, useAuthStore, useConfigStore } from '@ownclouders/web-pkg' +import { CapabilityStore, ConfigStore, useAuthStore, useConfigStore } from '@ownclouders/web-pkg' import { mock } from 'vitest-mock-extended' import { Router } from 'vue-router' +import { Ability } from '@ownclouders/web-client' import { AuthService } from '../../../../src/services/auth/authService' import { UserManager } from '../../../../src/services/auth/userManager' import { RouteLocation, createRouter, createTestingPinia } from '@ownclouders/web-test-helpers' @@ -370,4 +371,100 @@ describe('AuthService', () => { expect(mockSignInRedirect).not.toHaveBeenCalled() }) }) + + describe('vault scope', () => { + const vaultRoute = { + params: { scope: 'vault' }, + fullPath: '/vault' + } as unknown as RouteLocation + + const setupVaultAuthService = ({ + canAccessVault, + userContextReady, + getUser + }: { + canAccessVault: boolean + userContextReady: boolean + getUser: () => Promise + }) => { + const authService = new AuthService() + const mockSignInRedirect = vi.fn() + + Object.defineProperty(authService, 'userManager', { + value: mock({ + getUser: vi.fn().mockImplementation(getUser), + signinRedirect: mockSignInRedirect, + setPostLoginRedirectUrl: vi.fn() + }) + }) + + const ability = { can: vi.fn().mockReturnValue(canAccessVault) } as unknown as Ability + const capabilityStore = mock({ + isInitialized: true, + authMfaRequiredLevelname: 'advanced' + }) + const router = createRouter() + const pushSpy = vi.spyOn(router, 'push').mockResolvedValue(undefined) + + createTestingPinia() + const authStore = useAuthStore() + authStore.userContextReady = userContextReady + const configStore = useConfigStore() + authService.initialize( + configStore, + null, + router, + ability, + null, + null, + authStore, + capabilityStore, + null + ) + + return { authService, pushSpy, mockSignInRedirect } + } + + it('when the user lacks the vault ability, routes to accessDenied instead of the IdP', async () => { + const { authService, pushSpy, mockSignInRedirect } = setupVaultAuthService({ + canAccessVault: false, + userContextReady: true, + getUser: () => Promise.resolve(mock({ profile: { acr: 'advanced' }, expired: false })) + }) + + await authService.initializeContext(vaultRoute) + + expect(pushSpy).toHaveBeenCalledWith({ + name: 'accessDenied', + query: { redirectUrl: '/vault' } + }) + expect(mockSignInRedirect).not.toHaveBeenCalled() + }) + + it('when the user holds the vault ability, does not route to accessDenied and enforces MFA', async () => { + const { authService, pushSpy, mockSignInRedirect } = setupVaultAuthService({ + canAccessVault: true, + userContextReady: true, + getUser: () => Promise.resolve(null) + }) + + await authService.initializeContext(vaultRoute) + + expect(pushSpy).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'accessDenied' })) + expect(mockSignInRedirect).toHaveBeenCalledWith({ acr_values: 'advanced' }) + }) + + it('when the user context is not yet established, does not deny (backend guard is the boundary)', async () => { + const { authService, pushSpy, mockSignInRedirect } = setupVaultAuthService({ + canAccessVault: false, + userContextReady: false, + getUser: () => Promise.resolve(null) + }) + + await authService.initializeContext(vaultRoute) + + expect(pushSpy).not.toHaveBeenCalledWith(expect.objectContaining({ name: 'accessDenied' })) + expect(mockSignInRedirect).toHaveBeenCalledWith({ acr_values: 'advanced' }) + }) + }) }) diff --git a/web/tests/e2e/specs/vault-storage/vault.spec.ts b/web/tests/e2e/specs/vault-storage/vault.spec.ts index 4296eded0ef..e54b8ae8acd 100644 --- a/web/tests/e2e/specs/vault-storage/vault.spec.ts +++ b/web/tests/e2e/specs/vault-storage/vault.spec.ts @@ -8,6 +8,10 @@ test.describe('Vault Mode', { tag: '@predefined-users' }, () => { stepUser: 'Admin', users: ['Alice'] }) + await api.userHasAssignedRolesToUsers({ + stepUser: 'Admin', + users: [{ id: 'Alice', role: 'Space Admin' }] + }) await ui.userLogsIn({ stepUser: 'Alice' }) })