fix: [OCISDEV-1207] enforce permissions on vault routes (#12884)

* fix: [OCISDEV-1207] enforce permissions on vault routes

* fix: [OCISDEV-1207] enforce permissions on vault routes

* fix: [OCISDEV-1207] enforce permissions on vault routes

* fix: [OCISDEV-1207] enforce permissions on vault routes, adapt test role

* fix: [OCISDEV-1207] enforce permissions on vault routes, adapt test

* fix: [OCISDEV-1207] enforce permissions on vault routes, adapt test
This commit is contained in:
Michal Klos authored and GitHub committed 2026-09-09 12:44:45 +02:00
1 parent 6ad3d81a77
commit 768f7d4fa0
9 files changed
+286 -9

No files matched your search

@@ -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
+44
View File
@@ -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 {
@@ -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)
}
})
}
}
+2
View File
@@ -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)
@@ -219,7 +219,6 @@ func generateBundleUserRole() *settingsmsg.Bundle {
LanguageManagementPermission(Own),
ListFavoritesPermission(Own),
SelfManagementPermission(Own),
VaultModePermission(Own),
WriteFavoritesPermission(Own),
},
}
@@ -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 "<user-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 "<user-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": <permission-count>,
"maxItems": <permission-count>,
"uniqueItems": true,
"not": {
"contains": {
@@ -1185,4 +1198,8 @@ Feature: vault
}
}
"""
Examples:
| user-role | permission-count |
| User | 19 |
| User Light | 13 |
@@ -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`,
@@ -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<User>
}) => {
const authService = new AuthService()
const mockSignInRedirect = vi.fn()
Object.defineProperty(authService, 'userManager', {
value: mock<UserManager>({
getUser: vi.fn().mockImplementation(getUser),
signinRedirect: mockSignInRedirect,
setPostLoginRedirectUrl: vi.fn()
})
})
const ability = { can: vi.fn().mockReturnValue(canAccessVault) } as unknown as Ability
const capabilityStore = mock<CapabilityStore>({
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<User>({ 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' })
})
})
})
@@ -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' })
})