Compare commits

..
Author SHA1 Message Date
Matteo cd9821abe6 feat(web): [OCISDEV-1516] warn about group members without vault access when sharing
Show a notice in the share form when a group is selected for a vault resource, and add the same information to the "Share with people" help.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 b5cc5cc415 refactor: [OCISDEV-1516] share the vault recipient filter
- Move the VaultMode recipient filter to ocis-pkg/vault as
  FilterVaultModeUsers. The notifications and userlog services both use
  it.
- Run the checks in parallel, with at most 10 at the same time, so that
  a large group does not block the event handler.
- Add a tracing span with the number of checked, allowed and failed
  users.
- In the notifications service, check the vault permission before the
  settings and user lookups, so that a member without the permission
  costs one call only.
- Log a failed check with the user ID only, without the "event" field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 f7790d7be5 test: [OCISDEV-1516] check vault notifications and access for group members
- Add a scenario outline for a vault resource share to a group: only the
  group members with the VaultMode permission get an in-app
  notification and can download the file. The other members get no
  notification, cannot download the file, and do not see it in the
  Shares space.
- Add a scenario outline for a vault space membership of a group, with
  the space roles Manager, Space Viewer and Space Editor. Only the group
  members with the VaultMode permission get the notification and can
  access the space. The other members cannot download the file and do
  not see the space in their drive list.
- The examples cover the roles Space Admin, Admin, User Light and User.
- Assign the role "Space Admin" to Brian in the group share scenario,
  because the default role has no VaultMode permission.
- Add NotificationContext to the apiVault suite.
- Fix the pull request number in the changelog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:17 +01:00
Roman PerekhodandClaude Opus 5.5 f456f905c8 feat: [OCISDEV-1516] allow group shares in the vault
- web: the share dialog searches for groups in vault mode.
- notifications, userlog: send vault notifications only to the users
  who hold the VaultMode permission. A group can contain other users.
- ocis-pkg/vault: add the shared helpers for the vault checks.
- acceptance: a group invitation to a vault resource now succeeds.

The gateway change is in owncloud/reva#787.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 13:55:13 +01:00
68 changed files with 1084 additions and 2143 deletions

No files matched your search

-8
View File
@@ -7,8 +7,6 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -23,8 +21,6 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -39,8 +35,6 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -57,8 +51,6 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
+9 -49
View File
@@ -4,9 +4,6 @@ on:
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
detect-changes:
name: detect-changes
@@ -18,7 +15,6 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check if changes are docs-only
id: check
@@ -61,8 +57,6 @@ jobs:
timeout-minutes: 60
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
@@ -75,7 +69,7 @@ jobs:
- name: Enable pnpm
run: corepack enable && corepack prepare pnpm@10.33.3 --activate
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -88,7 +82,6 @@ jobs:
sudo NEEDRESTART_MODE=a apt-get install -y libvips-dev
- name: Pre-checks and generate
# zizmor: ignore[adhoc-packages] gherlint is version-pinned (@1.1.0)
run: |
# Phase 1 — I/O + light CPU, no contention between tasks.
# wa (I/O wait) will spike during npm/pnpm downloads.
@@ -235,17 +228,10 @@ jobs:
# collaboration (needs WOPI)
- apiCollaboration
- apiVault
include:
# same suite against the Tika 4.x line (the default entry above uses 3.x)
- suite: apiSearchContent-tika4
behat_suite: apiSearchContent
tika_image: apache/tika:4.2.0-full
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -304,9 +290,7 @@ jobs:
- name: Run ${{ matrix.suite }}
run: |
mkdir -p "$GOCOVERDIR"
BEHAT_SUITES=${{ matrix.behat_suite || matrix.suite }} python3 tests/acceptance/run-github.py
env:
TIKA_IMAGE: ${{ matrix.tika_image }}
BEHAT_SUITES=${{ matrix.suite }} python3 tests/acceptance/run-github.py
- name: Upload raw coverage data
if: always()
@@ -330,10 +314,8 @@ jobs:
- cliCommands,apiServiceAvailability # grouped: both need ClamAV + email services
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -380,10 +362,8 @@ jobs:
- apiGraphUser,apiGraph,apiGraphGroup
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -438,10 +418,8 @@ jobs:
- "coreApiWebdavMove1,coreApiWebdavPreviews,coreApiWebdavUpload,coreApiWebdavUploadTUS"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -556,8 +534,6 @@ jobs:
vault_storage: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
@@ -728,8 +704,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -755,8 +729,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -782,8 +754,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -809,8 +779,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -836,8 +804,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
@@ -871,8 +837,6 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
@@ -906,8 +870,6 @@ jobs:
GOCOVERDIR: ${{ github.workspace }}/coverage-reports
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
@@ -921,14 +883,14 @@ jobs:
merge-multiple: true
- name: Convert coverage counters to profile
run: go tool covdata textfmt -i=${GOCOVERDIR} -o=coverage.out
run: go tool covdata textfmt -i=${{ env.GOCOVERDIR }} -o=coverage.out
- name: Publish coverage summary
run: |
{
echo "## Acceptance test coverage"
echo '```'
go tool covdata percent -i=${GOCOVERDIR}
go tool covdata percent -i=${{ env.GOCOVERDIR }}
echo '```'
echo
echo "<details>"
@@ -949,12 +911,10 @@ jobs:
- name: Check all jobs passed
run: |
# If docs-only, all test jobs are expected to be skipped — that's a pass
if [[ "${NEEDS_DETECT_CHANGES_OUTPUTS_DOCS_ONLY}" == "true" ]]; then
if [[ "${{ needs.detect-changes.outputs.docs-only }}" == "true" ]]; then
echo "Docs-only change — skipping tests is expected."
exit 0
fi
if [[ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
exit 1
fi
env:
NEEDS_DETECT_CHANGES_OUTPUTS_DOCS_ONLY: ${{ needs.detect-changes.outputs.docs-only }}
-5
View File
@@ -4,9 +4,6 @@ on:
push:
branches: [master, stable-*]
permissions:
contents: read
jobs:
license-check:
runs-on: ubuntu-latest
@@ -14,8 +11,6 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install REUSE tool
run: pip install reuse
-4
View File
@@ -5,9 +5,6 @@ on:
schedule:
- cron: "0 1 * * *"
permissions:
contents: read
jobs:
test:
name: ${{ matrix.example }}
@@ -40,7 +37,6 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: owncloud/ocis
persist-credentials: false
- name: Prepare hosts entry
run: |
+32 -134
View File
@@ -18,9 +18,6 @@ env:
OCIS_WRAPPER_URL: http://localhost:5200
K8S: true
permissions:
contents: read
jobs:
api-tests:
name: ${{ matrix.suite }}-k8s
@@ -83,11 +80,9 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup PHP ${{ env.PHP_VERSION }}
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
with:
php-version: ${{ env.PHP_VERSION }}
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -493,15 +488,13 @@ jobs:
- suite: ocm
args: "--type playwright --suites ocm"
federated: true
- suite: vault-storage
args: "--type playwright --suites vault-storage"
vault_storage: true
# - suite: vault-storage
# args: "--type playwright --suites vault-storage"
# vault_storage: true
steps:
- name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
@@ -548,8 +541,6 @@ jobs:
- name: Prepare Helm Charts
env:
ENABLE_TIKA: ${{ matrix.suite == 'vault-storage' }}
ENABLE_VAULT: ${{ matrix.suite == 'vault-storage' }}
ENABLE_WOPI: ${{ matrix.suite == 'app-provider' }}
ENABLE_OCM: ${{ matrix.suite == 'ocm' }}
run: |
@@ -561,83 +552,6 @@ jobs:
- name: Deploy Suite-Specific External Backends
run: |
if [[ "${{ matrix.suite }}" == "vault-storage" ]]; then
docker run -d \
-p 9998:9998 \
--name tika \
apache/tika:3.2.2.0-full
for i in {1..60}; do
if curl -sf http://localhost:9998 > /dev/null; then
break
fi
echo "Waiting for tika... ($i/60)"
sleep 2
done
curl -sf http://localhost:9998 > /dev/null
bash tests/config/k8s/expose-external-svc.sh tika:9998
# GitHub runners ship PostgreSQL pre-installed on 5432, but not always
# already running - reuse it for keycloak's DB instead of running our
# own container for it, once it's up.
sudo systemctl start postgresql
for i in {1..30}; do
sudo -u postgres pg_isready && break
echo "Waiting for postgres... ($i/30)"
sleep 2
done
sudo -u postgres pg_isready
sudo -u postgres psql -c "CREATE USER keycloak WITH PASSWORD 'keycloak';"
sudo -u postgres psql -c "CREATE DATABASE keycloak OWNER keycloak;"
mkdir -p keycloak-certs
openssl req -x509 -newkey rsa:2048 \
-keyout keycloak-certs/keycloakkey.pem \
-out keycloak-certs/keycloakcrt.pem \
-nodes -days 365 -subj "/CN=keycloak"
chmod 777 keycloak-certs/*
# patch the realm so the "web" client's redirect/origin URLs match
# the k8s ingress domain instead of the non-k8s "localhost:9200" one
sed "s|https://localhost:9200|${TEST_SERVER_URL}|g" \
tests/config/ci/ocis-mfa-ci-realm.dist.json > /tmp/ocis-realm.json
docker run -d --name keycloak --network host \
-e OCIS_DOMAIN="$TEST_SERVER_URL" \
-e KC_HOSTNAME=keycloak \
-e KC_PORT=8443 \
-e KC_DB=postgres \
-e KC_DB_URL=jdbc:postgresql://localhost:5432/keycloak \
-e KC_DB_USERNAME=keycloak \
-e KC_DB_PASSWORD=keycloak \
-e KC_FEATURES=impersonation \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
-e KC_HTTPS_CERTIFICATE_FILE=/keycloak-certs/keycloakcrt.pem \
-e KC_HTTPS_CERTIFICATE_KEY_FILE=/keycloak-certs/keycloakkey.pem \
-v "$(pwd)/keycloak-certs:/keycloak-certs:ro" \
-v /tmp/ocis-realm.json:/opt/keycloak/data/import/ocis-mfa-ci-realm.dist.json:ro \
quay.io/keycloak/keycloak:26.5.6 \
start-dev --proxy-headers xforwarded \
--spi-connections-http-client-default-disable-trust-manager=true \
--import-realm --health-enabled=true
keycloak_ready=false
for i in {1..60}; do
if curl -skf https://localhost:9000/health/ready > /dev/null; then
keycloak_ready=true
break
fi
echo "Waiting for keycloak... ($i/60)"
sleep 5
done
if [[ "$keycloak_ready" != "true" ]]; then
docker logs keycloak --tail 80
exit 1
fi
bash tests/config/k8s/expose-external-svc.sh keycloak:8443
fi
if [[ "${{ matrix.suite }}" == "app-provider" ]]; then
# Start Collabora
docker run -d \
@@ -713,15 +627,6 @@ jobs:
bash tests/config/k8s/expose-nodeports.sh collaboration-onlyoffice 9300 30302
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9304 30304
- name: Expose proxy readyz
if: ${{ matrix.suite == 'vault-storage' }}
run: |
(
while true; do
kubectl -n "$TEST_SERVER_DOMAIN" port-forward deployment/proxy 19205:9205 >> /tmp/proxy-readyz-portforward.log 2>&1
sleep 1
done
) &
- name: Wait for oCIS to be ready
env:
FILE_URL: ${{ env.TEST_SERVER_URL }}/remote.php/dav/files/admin/hello1.txt
@@ -757,48 +662,41 @@ jobs:
return 1
}
if [[ "${{ matrix.suite }}" == "vault-storage" ]]; then
retry "proxy readyz" curl -sf http://localhost:19205/readyz || exit 1
else
echo "Creating test file in oCIS..."
echo "Creating test file in oCIS..."
request() {
local method=$1
shift
curl -ks -o /dev/null -w "%{http_code}" \
-X "$method" \
-u admin:admin \
"$@" \
"$FILE_URL"
}
put_file() {
request PUT \
-H "Content-Type: text/plain" \
--data "Hello from GitHub Actions!"
}
delete_file() {
request DELETE
}
check_status() {
local expected=$1
shift
status=$("$@")
[ "$status" = "$expected" ]
}
echo "Creating test file..."
retry "create file (HTTP 201)" check_status 201 put_file || exit 1
echo "Deleting test file..."
retry "delete file (HTTP 204)" check_status 204 delete_file || exit 1
fi
request() {
local method=$1
shift
curl -ks -o /dev/null -w "%{http_code}" \
-X "$method" \
-u admin:admin \
"$@" \
"$FILE_URL"
}
put_file() {
request PUT \
-H "Content-Type: text/plain" \
--data "Hello from GitHub Actions!"
}
delete_file() {
request DELETE
}
check_status() {
local expected=$1
shift
status=$("$@")
[ "$status" = "$expected" ]
}
echo "Creating test file..."
retry "create file (HTTP 201)" check_status 201 put_file || exit 1
echo "Deleting test file..."
retry "delete file (HTTP 204)" check_status 204 delete_file || exit 1
- name: Run e2e ${{ matrix.suite }} tests
env:
E2E_ARGS: "${{ matrix.args }}"
K8S: ${{ env.K8S }}
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
KEYCLOAK: ${{ matrix.suite == 'vault-storage' }}
KEYCLOAK_HOST: keycloak:8443
VAULT_MODE: ${{ matrix.suite == 'vault-storage' }}
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
FED_SERVER_URL: ${{ env.FED_SERVER_URL }}
FEDERATED_NEEDED: ${{ matrix.federated == true && 'true' || 'false' }}
+5 -14
View File
@@ -27,8 +27,6 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
@@ -46,7 +44,7 @@ jobs:
- name: Determine package
id: package
run: |
TAG="${GITHUB_REF_NAME}"
TAG="${{ github.ref_name }}"
PACKAGES="babel-preset design-system eslint-config extension-sdk prettier-config tsconfig web-client web-pkg web-test-helpers"
for pkg in $PACKAGES; do
if [[ "$TAG" == "${pkg}-v"* ]]; then
@@ -60,36 +58,29 @@ jobs:
- name: Verify package version
run: |
PKG="${STEPS_PACKAGE_OUTPUTS_NAME}"
VERSION="${STEPS_PACKAGE_OUTPUTS_VERSION}"
PKG="${{ steps.package.outputs.name }}"
VERSION="${{ steps.package.outputs.version }}"
ACTUAL_VERSION=$(jq -r '.version' < "packages/${PKG}/package.json")
echo "Build ${PKG} ${VERSION} package.json: ${ACTUAL_VERSION}"
if [ "${ACTUAL_VERSION}" != "${VERSION}" ]; then
echo "git tag does not match version in web/packages/${PKG}/package.json"
exit 1
fi
env:
STEPS_PACKAGE_OUTPUTS_NAME: ${{ steps.package.outputs.name }}
STEPS_PACKAGE_OUTPUTS_VERSION: ${{ steps.package.outputs.version }}
- name: Build tokens
run: pnpm build:tokens
- name: Build package
run: |
PKG="${STEPS_PACKAGE_OUTPUTS_NAME}"
PKG="${{ steps.package.outputs.name }}"
case "$PKG" in
design-system|web-client|web-pkg|web-test-helpers)
pnpm --filter "@ownclouders/${PKG}" vite build
;;
esac
env:
STEPS_PACKAGE_OUTPUTS_NAME: ${{ steps.package.outputs.name }}
- name: Publish to NPM
run: |
pnpm publish \
--no-git-checks --filter "@ownclouders/${STEPS_PACKAGE_OUTPUTS_NAME}" \
--no-git-checks --filter "@ownclouders/${{ steps.package.outputs.name }}" \
--access public --tag latest
env:
STEPS_PACKAGE_OUTPUTS_NAME: ${{ steps.package.outputs.name }}
+15 -44
View File
@@ -18,9 +18,6 @@ env:
PNPM_VERSION: '10.28.1'
GOLANG_BUILD_IMAGE: 'golang:1.26.8-alpine3.23@sha256:a8fa79c5bd40d880b52bd3b6d7669ecdcfd00e85facdd427d279efb5ddd79cb1'
permissions:
contents: read
jobs:
determine-release-type:
runs-on: ubuntu-latest
@@ -34,7 +31,6 @@ jobs:
with:
fetch-depth: 0
fetch-tags: true
persist-credentials: false
- id: info
env:
@@ -57,17 +53,18 @@ jobs:
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
VERSION="$VERSION_OVERRIDE"
[[ -z "$VERSION" ]] && VERSION=$(next_dev)
elif [[ "${GITHUB_REF_TYPE}" == "branch" ]]; then
elif [[ "${{ github.ref_type }}" == "branch" ]]; then
VERSION=$(next_dev)
else
VERSION="${GITHUB_REF#refs/tags/v}"
fi
# `version` below is read back by the later jobs' `run:` blocks through
# NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION in their env:, so it is never
# substituted into script text. Refusing anything that is not a version token
# here is a second safeguard -- and a release version that is not a version
# token is a bug in its own right.
# `version` below is read back by nine `run:` blocks in this file (thirteen
# interpolations) as ${{ needs.determine-release-type.outputs.version }}, and each
# of those is substituted into the script text before bash sees it. Refusing
# anything that is not a version token here is what keeps those nine safe, instead
# of nine more env: blocks -- and a release version that is not a version token is
# a bug in its own right.
if [[ ! "$VERSION" =~ ^[0-9A-Za-z][0-9A-Za-z.+-]*$ ]]; then
echo "::error title=Invalid release version::'$VERSION' is not a version string (expected ^[0-9A-Za-z][0-9A-Za-z.+-]*$)"
exit 1
@@ -84,18 +81,14 @@ jobs:
needs: [determine-release-type]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
cache: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
package-manager-cache: false
- run: npm install --silent -g yarn npx --force # zizmor: ignore[adhoc-packages] pre-existing unpinned install, left to the maintainers
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- run: npm install --silent -g yarn npx --force
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v4
with:
version: ${{ env.PNPM_VERSION }}
- run: pnpm config set store-dir ./.pnpm-store && make ci-node-generate
@@ -106,10 +99,8 @@ jobs:
BUF_TOKEN: ${{ secrets.BUF_API_TOKEN }}
- name: bump LatestTag
run: |
VERSION="${NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION}"
VERSION="${{ needs.determine-release-type.outputs.version }}"
sed -i "s/LatestTag = \".*\"/LatestTag = \"$VERSION\"/" ocis-pkg/version/version.go
env:
NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION: ${{ needs.determine-release-type.outputs.version }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: generated-code
@@ -129,8 +120,6 @@ jobs:
os: [linux, darwin]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: generated-code
@@ -138,15 +127,12 @@ jobs:
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
cache: false
- run: |
make -C ocis release-${{ matrix.os }} OUTPUT=${NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION}
make -C ocis release-${{ matrix.os }} OUTPUT=${{ needs.determine-release-type.outputs.version }}
make -C ocis release-finish
if [[ "${{ matrix.os }}" == "linux" ]]; then
cp assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf ocis/dist/release/
fi
env:
NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION: ${{ needs.determine-release-type.outputs.version }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: binaries-${{ matrix.os }}
@@ -158,8 +144,6 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
scan-type: fs
@@ -174,8 +158,6 @@ jobs:
needs: [determine-release-type, generate-code]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: generated-code
@@ -183,12 +165,10 @@ jobs:
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
package-manager-cache: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
cache: false
- run: npm install --silent -g yarn npx "pnpm@$PNPM_VERSION" --force # zizmor: ignore[adhoc-packages] pre-existing unpinned install, left to the maintainers
- run: npm install --silent -g yarn npx "pnpm@$PNPM_VERSION" --force
# web is excluded from the generated-code artifact (see generate-code) to
# avoid OOM on upload, so its node_modules — which provides the
# license-checker-rseidelsohn binary — must be reinstalled here.
@@ -210,20 +190,16 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
cache: false
- run: |
make changelog CHANGELOG_VERSION=$(echo "${NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION}" | cut -d'-' -f1)
make changelog CHANGELOG_VERSION=$(echo "${{ needs.determine-release-type.outputs.version }}" | cut -d'-' -f1)
# calens produces empty output when no versioned changelog directory exists (e.g. dev builds).
# Fall back to a pointer to the unreleased entries.
if [[ $(wc -l < ocis/dist/CHANGELOG.md) -lt 5 ]]; then
echo "Development release — no release notes yet. See [unreleased changes](https://github.com/owncloud/ocis/tree/master/changelog/unreleased/)." > ocis/dist/CHANGELOG.md
fi
env:
NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION: ${{ needs.determine-release-type.outputs.version }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: changelog
@@ -232,8 +208,6 @@ jobs:
create-github-release:
runs-on: ubuntu-latest
permissions:
contents: write
timeout-minutes: 30
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
steps:
@@ -254,7 +228,7 @@ jobs:
name: changelog
path: .
- uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with: # zizmor: ignore[superfluous-actions] the publish path only runs on a real release, CI cannot exercise a rewrite
with:
tag_name: v${{ needs.determine-release-type.outputs.version }}
name: v${{ needs.determine-release-type.outputs.version }}
body_path: CHANGELOG.md
@@ -274,8 +248,6 @@ jobs:
- create-github-release
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: binaries-linux
@@ -290,10 +262,9 @@ jobs:
path: release-assets
- run: |
python3 scripts/audit-release.py \
--version "${NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION}" \
--version "${{ needs.determine-release-type.outputs.version }}" \
--dir release-assets/ \
--github-release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NEEDS_DETERMINE_RELEASE_TYPE_OUTPUTS_VERSION: ${{ needs.determine-release-type.outputs.version }}
-5
View File
@@ -5,9 +5,6 @@ on:
push:
branches: [master, stable-*]
permissions:
contents: read
jobs:
detect-web-changes:
name: detect-web-changes
@@ -21,7 +18,6 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check if web/ changed
id: check
@@ -74,7 +70,6 @@ jobs:
with:
# nx affected --base=<pr-base-sha> (used below) needs that commit present locally
fetch-depth: 0
persist-credentials: false
- name: Setup pnpm
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+1 -3
View File
@@ -19,9 +19,7 @@ jobs:
container: golang:1.25-alpine
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
- name: Run CI Reporter
working-directory: tools/ci-reporter
-30
View File
@@ -1,30 +0,0 @@
name: Zizmor
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
- reopened
schedule:
# Weekly: online audits (known-vulnerable actions, impostor commits) can
# start failing without a code change.
- cron: '0 4 * * 1'
workflow_dispatch:
permissions:
contents: read
# Only pull request runs cancel each other: a push to the default branch and
# the weekly run share a ref, and neither should cancel the other.
concurrency:
group: zizmor-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
zizmor:
name: Zizmor
uses: owncloud/reusable-workflows/.github/workflows/zizmor.yml@main
@@ -1,17 +0,0 @@
Bugfix: Share vault resources with guests before their first login
A user of another instance only gets a role on an instance at their first
login there. Until then, the vault share search did not show them and sharing
a vault resource with them was refused, even if that login would give them a
role with the "Vault mode" permission.
The graph service now derives that role from the user's `userClass` LDAP
attribute with `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING`, like the proxy does
with the roles claim at login. If the role grants vault mode, the vault share
search shows the user, and sharing a vault resource with them assigns the role
first. Users who already have a role are not affected. The graph service needs
`OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` set as well, and `userClass` must hold
the same values as the `PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM` claim. Otherwise the
first login replaces the role again.
https://github.com/owncloud/ocis/pull/13273
@@ -1,16 +0,0 @@
Enhancement: Support Apache Tika 4.x in content extraction
The search service can now extract content from an Apache Tika 4.x server in
addition to Tika 3.x. Tika 4.0 renamed the `X-TIKA:content` metadata key to
`tk:content`, replaced the `/language/string` endpoint with `/language` and
reports the GPS altitude as `geo:alt` instead of `GPS:GPS Altitude`. Without
support for these changes, a 4.x server would return no content for oCIS, so file
contents were no longer searchable, stop word cleaning was skipped and the
altitude of photos was missing.
The extractor now reads `tk:content` and falls back to `X-TIKA:content`, reads
the altitude from both `geo:alt` and `GPS:GPS Altitude`, and picks the language
endpoint from the version the Tika server reports at startup. Both Tika 3.x and
4.x servers are supported.
https://github.com/owncloud/ocis/pull/13279
@@ -0,0 +1,11 @@
Enhancement: Allow group shares in the vault
Users can now invite a group to a resource in the vault (Safe). Before this
change, the server accepted only users as vault share recipients. The share
dialog in Web now also searches for groups in vault mode. The
notifications and userlog services now send a vault notification only to the
group members who have the permission to use the vault. The other group
members get no email and no in-app notification.
https://github.com/owncloud/ocis/pull/13260
https://github.com/owncloud/reva/pull/787
@@ -1,31 +0,0 @@
Bugfix: Reindex no longer aborts on unresolvable files; threshold configurable
`IndexSpace` aborted the walk after 5 consecutive files failed, on the assumption
that the content extractor was down. Two things made that fire on healthy
systems:
1. A file the walker listed but that could not be stat'ed by its path (a node
whose stored name no longer matched its directory entry) counted as an
extraction failure. The extractor was never involved.
2. The counter only ever saw files that actually needed work. On a space that
was already almost fully indexed, five problem files scattered anywhere in
walk order looked "consecutive", the walk aborted at the same point every
time, and nothing after that point was indexed until the files were fixed
by hand.
The walk still resolves each file by its path. When Stat by path does not find
a file, the walk tries again with the ID it listed, so such a node is indexed.
A healthy file costs no extra GetPath call. A file that Stat or GetPath does not find (CODE_NOT_FOUND, deleted
since it was listed) is skipped without counting; auth, gateway, transport and
deadline failures still count. Because the gateway also answers NOT_FOUND when
it cannot reach a storage provider, a walk in which at least 5 files, and more
than half of the files that needed work, were not found ends with an error
instead of reporting the space as indexed. Already-indexed, unchanged files
reset the counter, a cancelled or timed-out walk (including its retry waits)
stops with an error, and each walk logs a summary of indexed, unchanged, failed
and not-found files. The threshold became configurable with
`SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES` (default 5, unchanged; 0 never
aborts and logs a warning at startup; negative values are rejected).
https://github.com/owncloud/ocis/pull/13034
https://github.com/owncloud/ocis/issues/13033
+1 -1
View File
@@ -67,7 +67,7 @@ require (
github.com/open-policy-agent/opa v1.21.1
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.25.0
+2 -4
View File
@@ -736,10 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575 h1:GOsblJHW/dvNdxxXmCb/PZOGRIg1ci4SVs+pA7hw6t4=
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629 h1:h0jekinxPFEwKl0IkGT8iYOca9ZdIXJDixIIFI/yhfY=
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574 h1:BDRlgU05VSMDzQC/7RWKtLHT8VcGxbQ9z0v7ycHQcEI=
github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
-48
View File
@@ -1,48 +0,0 @@
// Package rolemapping holds what the proxy and the graph service share to map values of a user to
// the name of a role: the proxy maps the values of the roles claim at login, the graph service the
// userClass of multi-instance guests who did not log in yet.
package rolemapping
import (
"fmt"
"regexp"
"strings"
)
// ParsePair splits a 'claimvalue:rolename' pair of OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING at its
// last colon, so the value may contain colons but the role name must not. Roles created through
// the settings service can't contain a colon, their names are restricted to letters, digits, '-'
// and '_'.
func ParsePair(pair string) (value string, roleName string, err error) {
i := strings.LastIndex(pair, ":")
// the env var parser trims list elements, the yaml parser does not
if i >= 0 {
value, roleName = strings.TrimSpace(pair[:i]), strings.TrimSpace(pair[i+1:])
}
if value == "" || roleName == "" {
return "", "", fmt.Errorf("invalid guest role mapping '%s', expected 'claimvalue:rolename'", pair)
}
return value, roleName, nil
}
// Matcher matches values against the value of a mapping: an exact value, or a regular expression
// that must match a whole value.
type Matcher struct {
value string
// rx is nil if the value is no valid regular expression, then only the exact value matches
rx *regexp.Regexp
}
// NewMatcher compiles the value of a mapping.
func NewMatcher(value string) Matcher {
rx, err := regexp.Compile("^(?:" + value + ")$")
if err != nil {
rx = nil
}
return Matcher{value: value, rx: rx}
}
// Matches reports whether v matches the value of the mapping.
func (m Matcher) Matches(v string) bool {
return v == m.value || (m.rx != nil && m.rx.MatchString(v))
}
-61
View File
@@ -1,61 +0,0 @@
package rolemapping
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParsePair(t *testing.T) {
tests := []struct {
pair string
value string
roleName string
wantErr bool
}{
{pair: "lehrer:user-light-vault", value: "lehrer", roleName: "user-light-vault"},
{pair: " lehrer : user-light-vault ", value: "lehrer", roleName: "user-light-vault"},
// split at the last colon, the value may contain colons
{pair: "urn:ocis:lehrer:user-light-vault", value: "urn:ocis:lehrer", roleName: "user-light-vault"},
{pair: "lehrer", wantErr: true},
{pair: ":user-light-vault", wantErr: true},
{pair: "lehrer:", wantErr: true},
{pair: " :user-light-vault", wantErr: true},
{pair: "lehrer: ", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.pair, func(t *testing.T) {
value, roleName, err := ParsePair(tt.pair)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.value, value)
assert.Equal(t, tt.roleName, roleName)
})
}
}
func TestMatcher(t *testing.T) {
tests := []struct {
name string
value string
v string
matches bool
}{
{name: "exact value", value: "lehrer", v: "lehrer", matches: true},
{name: "other value", value: "lehrer", v: "schueler", matches: false},
{name: "case matters", value: "lehrer", v: "Lehrer", matches: false},
{name: "regex", value: "lehr.*", v: "lehrer", matches: true},
{name: "regex alternatives", value: "lehrer|Nutzerverwalter", v: "Nutzerverwalter", matches: true},
{name: "a regex must match the whole value", value: "lehrer", v: "nichtlehrer", matches: false},
{name: "invalid regex matches its exact value", value: "lehrer[", v: "lehrer[", matches: true},
{name: "invalid regex matches nothing else", value: "lehrer[", v: "lehrer", matches: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.matches, NewMatcher(tt.value).Matches(tt.v))
})
}
}
+103
View File
@@ -0,0 +1,103 @@
// Package vault provides helpers for resources in the vault storage provider.
package vault
import (
"context"
"fmt"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
)
// maxConcurrentChecks bounds how many VaultMode checks run at the same time, so that a large
// group does not send all its checks to the gateway at once.
const maxConcurrentChecks = 10
const tracerName = "github.com/owncloud/ocis/v2/ocis-pkg/vault"
// IsVaultStorage reports whether the storage ID belongs to the vault storage provider.
func IsVaultStorage(storageID string) bool {
return storageID == utils.VaultStorageProviderID
}
// IsVaultSpace reports whether the space ID belongs to the vault storage provider.
// It returns true for a space ID that it cannot parse, so that callers fail closed.
func IsVaultSpace(spaceID string) bool {
rid, err := storagespace.ParseID(spaceID)
if err != nil {
return true
}
return IsVaultStorage(rid.GetStorageId())
}
// HasVaultMode reports whether the user holds the VaultMode permission.
// A non-nil error means undetermined, so callers must treat the user as not allowed.
func HasVaultMode(ctx context.Context, gwc gateway.GatewayAPIClient, userID *user.UserId) (bool, error) {
res, err := gwc.CheckPermission(ctx, &permissions.CheckPermissionRequest{
SubjectRef: &permissions.SubjectReference{
Spec: &permissions.SubjectReference_UserId{UserId: userID},
},
Permission: permission.VaultMode,
})
if err != nil {
return false, err
}
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
return true, nil
case rpc.Code_CODE_PERMISSION_DENIED:
return false, nil
default:
return false, fmt.Errorf("vault permission check returned status %q: %s", code, res.GetStatus().GetMessage())
}
}
// FilterVaultModeUsers returns the users from userIDs who hold the VaultMode permission, in the
// same order. A group can contain users without the permission, because the gateway does not
// check the group members. The checks run in parallel, with a bound. When a check fails, the
// function calls onError for that user and leaves the user out, so that the caller fails closed.
func FilterVaultModeUsers(ctx context.Context, gwc gateway.GatewayAPIClient, userIDs []*user.UserId, onError func(*user.UserId, error)) []*user.UserId {
ctx, span := trace.SpanFromContext(ctx).TracerProvider().Tracer(tracerName).Start(ctx, "FilterVaultModeUsers")
defer span.End()
span.SetAttributes(attribute.Int("vault.users.checked", len(userIDs)))
allowed := make([]bool, len(userIDs))
errs := make([]error, len(userIDs))
var eg errgroup.Group
eg.SetLimit(maxConcurrentChecks)
for i, id := range userIDs {
eg.Go(func() error {
allowed[i], errs[i] = HasVaultMode(ctx, gwc, id)
return nil
})
}
_ = eg.Wait()
filtered := make([]*user.UserId, 0, len(userIDs))
failed := 0
for i, id := range userIDs {
if errs[i] != nil {
failed++
if onError != nil {
onError(id, errs[i])
}
continue
}
if allowed[i] {
filtered = append(filtered, id)
}
}
span.SetAttributes(
attribute.Int("vault.users.allowed", len(filtered)),
attribute.Int("vault.users.failed", failed),
)
return filtered
}
+110
View File
@@ -0,0 +1,110 @@
package vault
import (
"context"
"errors"
"fmt"
"slices"
"testing"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
)
func TestIsVaultSpace(t *testing.T) {
tests := []struct {
name string
spaceID string
want bool
}{
{"vault space", utils.VaultStorageProviderID + "$space-id", true},
{"regular space", "storage-id$space-id", false},
{"unparsable space id fails closed", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsVaultSpace(tt.spaceID); got != tt.want {
t.Errorf("IsVaultSpace(%q) = %v, want %v", tt.spaceID, got, tt.want)
}
})
}
}
func TestHasVaultMode(t *testing.T) {
tests := []struct {
name string
res *permissions.CheckPermissionResponse
err error
want bool
wantErr bool
}{
{"ok grants", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil, true, false},
{"permission denied denies", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED}}, nil, false, false},
{"internal status fails closed", &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_INTERNAL}}, nil, false, true},
{"transport error fails closed", nil, errors.New("unavailable"), false, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gwc := &cs3mocks.GatewayAPIClient{}
gwc.On("CheckPermission", mock.Anything, mock.MatchedBy(func(req *permissions.CheckPermissionRequest) bool {
return req.GetPermission() == permission.VaultMode && req.GetSubjectRef().GetUserId().GetOpaqueId() == "alice"
})).Return(tt.res, tt.err)
got, err := HasVaultMode(context.Background(), gwc, &user.UserId{OpaqueId: "alice"})
if (err != nil) != tt.wantErr {
t.Fatalf("HasVaultMode() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("HasVaultMode() = %v, want %v", got, tt.want)
}
gwc.AssertExpectations(t)
})
}
}
func TestFilterVaultModeUsers(t *testing.T) {
// alice and every "ok-" user hold the permission, bob does not, and the check for carol fails
gwc := &cs3mocks.GatewayAPIClient{}
gwc.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
switch id := r.GetSubjectRef().GetUserId().GetOpaqueId(); {
case id == "carol":
return nil, errors.New("unavailable")
case id == "bob":
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED}}, nil
default:
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil
}
})
ids := []*user.UserId{{OpaqueId: "alice"}, {OpaqueId: "bob"}, {OpaqueId: "carol"}}
for i := range 50 {
ids = append(ids, &user.UserId{OpaqueId: fmt.Sprintf("ok-%02d", i)})
}
var failed []string
got := FilterVaultModeUsers(context.Background(), gwc, ids, func(id *user.UserId, err error) {
failed = append(failed, id.GetOpaqueId())
})
want := []string{"alice"}
for i := range 50 {
want = append(want, fmt.Sprintf("ok-%02d", i))
}
gotIDs := make([]string, 0, len(got))
for _, id := range got {
gotIDs = append(gotIDs, id.GetOpaqueId())
}
if !slices.Equal(gotIDs, want) {
t.Errorf("FilterVaultModeUsers() = %v, want %v", gotIDs, want)
}
if !slices.Equal(failed, []string{"carol"}) {
t.Errorf("onError called for %v, want [carol]", failed)
}
gwc.AssertNumberOfCalls(t, "CheckPermission", len(ids))
}
+4 -5
View File
@@ -202,9 +202,8 @@ type Validation struct {
// MultiInstanceConfig holds configuration for multi-instance-ocis
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. 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"`
GuestRoleMapping []string `yaml:"guest_role_mapping" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING" desc:"(Optional) The guest role mapping of the proxy service. The graph service matches it against the LDAP attribute 'userClass' of guests without a role on this instance, so they can receive vault shares before their first login here. 'userClass' must hold the same values as the PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM claim." introductionVersion:"9.0.0"`
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. 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"`
}
-2
View File
@@ -41,8 +41,6 @@ type Backend interface {
GetUser(ctx context.Context, nameOrID string, oreq *godata.GoDataRequest) (*libregraph.User, error)
GetPreciseUser(ctx context.Context, name string, instancename string, oreq *godata.GoDataRequest) (*libregraph.User, error)
// GetUserClass returns the userClass of a user and whether they are a member of this instance.
GetUserClass(ctx context.Context, id string) (userClass []string, member bool, err error)
GetUsers(ctx context.Context, oreq *godata.GoDataRequest) ([]*libregraph.User, error)
// FilterUsers returns a list of users that match the filter
FilterUsers(ctx context.Context, oreq *godata.GoDataRequest, filter *godata.ParseNode) ([]*libregraph.User, error)
-5
View File
@@ -81,11 +81,6 @@ func (i *CS3) GetPreciseUser(ctx context.Context, name string, instancename stri
return nil, errNotImplemented
}
// GetUserClass is not implemented
func (i *CS3) GetUserClass(_ context.Context, _ string) ([]string, bool, error) {
return nil, false, errNotImplemented
}
// GetUsers implements the Backend Interface.
func (i *CS3) GetUsers(ctx context.Context, oreq *godata.GoDataRequest) ([]*libregraph.User, error) {
logger := i.Logger.SubloggerWithRequestID(ctx)
-27
View File
@@ -815,33 +815,6 @@ func (i *LDAP) GetPreciseUser(ctx context.Context, name string, instancename str
return i.refineUser(e, q)
}
// GetUserClass implements the Backend Interface. Like the proxy, it treats users with this
// instance's id or the master id in their member attribute as members.
func (i *LDAP) GetUserClass(ctx context.Context, id string) ([]string, bool, error) {
logger := i.logger.SubloggerWithRequestID(ctx)
logger.Debug().Str("backend", "ldap").Msg("GetUserClass")
idString, err := filterEscapeUUID(i.userIDisOctetString, id)
if err != nil {
return nil, false, fmt.Errorf("invalid User id: %w", err)
}
userClass := newEducationUserAttributeMap().primaryRole
filter := fmt.Sprintf("(&(objectClass=%s)(%s=%s))", i.userObjectClass, i.userAttributeMap.id, idString)
e, err := i.searchLDAPEntryByFilter(i.userBaseDN, []string{userClass, i.userAttributeMap.userMemberAttribute}, filter)
if err != nil {
return nil, false, err
}
member := false
for _, iid := range e.GetEqualFoldAttributeValues(i.userAttributeMap.userMemberAttribute) {
if iid != "" && (iid == i.instanceID || iid == i.masterID) {
member = true
break
}
}
return e.GetEqualFoldAttributeValues(userClass), member, nil
}
func (i *LDAP) refineUser(e *ldap.Entry, query *godata.GoDataQuery) (*libregraph.User, error) {
u := i.createUserModelFromLDAP(e)
if u == nil {
-53
View File
@@ -238,59 +238,6 @@ func TestCreateUserModelFromLDAP(t *testing.T) {
}
}
func TestGetUserClass(t *testing.T) {
cfg := lconfig
cfg.UserMemberAttribute = "ocMemberOfSchool"
// expectSearch returns an entry for the lookup by id, which ignores the user filter and only
// asks for the userClass and the member attribute
expectSearch := func(lm *mocks.Client, memberOf ...string) {
entry := ldap.NewEntry("uid=teacher", map[string][]string{
"userClass": {"teacher"},
"ocMemberOfSchool": memberOf,
})
lm.On("Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool {
return sr.Filter == "(&(objectClass=inetOrgPerson)(entryUUID=teacher-id))" &&
assert.ObjectsAreEqual([]string{"userClass", "ocMemberOfSchool"}, sr.Attributes)
})).Return(&ldap.SearchResult{Entries: []*ldap.Entry{entry}}, nil)
}
tests := []struct {
name string
masterID string
memberOf []string
wantMember bool
}{
{name: "a user of another instance", memberOf: []string{"school2"}, wantMember: false},
{name: "a member of this instance", memberOf: []string{"school2", "school1"}, wantMember: true},
{name: "a member of all instances through the master id", masterID: "master-id", memberOf: []string{"master-id"}, wantMember: true},
{name: "a user without instances", memberOf: nil, wantMember: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lm := &mocks.Client{}
expectSearch(lm, tt.memberOf...)
b, err := NewLDAPBackend(lm, cfg, &logger, "school1", tt.masterID)
assert.NoError(t, err)
userClass, member, err := b.GetUserClass(context.Background(), "teacher-id")
assert.NoError(t, err)
assert.Equal(t, []string{"teacher"}, userClass)
assert.Equal(t, tt.wantMember, member)
})
}
t.Run("an unknown user", func(t *testing.T) {
lm := &mocks.Client{}
lm.On("Search", mock.Anything).Return(&ldap.SearchResult{}, nil)
b, err := NewLDAPBackend(lm, cfg, &logger, "school1", "")
assert.NoError(t, err)
_, _, err = b.GetUserClass(context.Background(), "teacher-id")
assert.ErrorIs(t, err, ErrNotFound)
})
}
func TestGetUser(t *testing.T) {
// Mock a Sizelimit Error
lm := &mocks.Client{}
@@ -707,72 +707,6 @@ func (_c *Backend_GetUser_Call) RunAndReturn(run func(context.Context, string, *
return _c
}
// GetUserClass provides a mock function with given fields: ctx, id
func (_m *Backend) GetUserClass(ctx context.Context, id string) ([]string, bool, error) {
ret := _m.Called(ctx, id)
if len(ret) == 0 {
panic("no return value specified for GetUserClass")
}
var r0 []string
var r1 bool
var r2 error
if rf, ok := ret.Get(0).(func(context.Context, string) ([]string, bool, error)); ok {
return rf(ctx, id)
}
if rf, ok := ret.Get(0).(func(context.Context, string) []string); ok {
r0 = rf(ctx, id)
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).([]string)
}
}
if rf, ok := ret.Get(1).(func(context.Context, string) bool); ok {
r1 = rf(ctx, id)
} else {
r1 = ret.Get(1).(bool)
}
if rf, ok := ret.Get(2).(func(context.Context, string) error); ok {
r2 = rf(ctx, id)
} else {
r2 = ret.Error(2)
}
return r0, r1, r2
}
// Backend_GetUserClass_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetUserClass'
type Backend_GetUserClass_Call struct {
*mock.Call
}
// GetUserClass is a helper method to define mock.On call
// - ctx context.Context
// - id string
func (_e *Backend_Expecter) GetUserClass(ctx interface{}, id interface{}) *Backend_GetUserClass_Call {
return &Backend_GetUserClass_Call{Call: _e.mock.On("GetUserClass", ctx, id)}
}
func (_c *Backend_GetUserClass_Call) Run(run func(ctx context.Context, id string)) *Backend_GetUserClass_Call {
_c.Call.Run(func(args mock.Arguments) {
run(args[0].(context.Context), args[1].(string))
})
return _c
}
func (_c *Backend_GetUserClass_Call) Return(userClass []string, member bool, err error) *Backend_GetUserClass_Call {
_c.Call.Return(userClass, member, err)
return _c
}
func (_c *Backend_GetUserClass_Call) RunAndReturn(run func(context.Context, string) ([]string, bool, error)) *Backend_GetUserClass_Call {
_c.Call.Return(run)
return _c
}
// GetUsers provides a mock function with given fields: ctx, oreq
func (_m *Backend) GetUsers(ctx context.Context, oreq *godata.GoDataRequest) ([]*libregraph.User, error) {
ret := _m.Called(ctx, oreq)
@@ -73,7 +73,6 @@ type DriveItemPermissionsService struct {
tp trace.TracerProvider
identityBackend identity.Backend
hasExternalSharePermission externalSharePermissionChecker
createVaultShare vaultShareCreator
}
type permissionType int
@@ -89,20 +88,12 @@ const (
// supposed to return true if the user can share to users from other instances (multi-instance only)
type externalSharePermissionChecker func(context.Context) bool
// supposed to create a vault share for the user with createShare, and to give a user who never
// logged in here the role with vault mode the guest role mapping gives them (multi-instance only)
type vaultShareCreator func(ctx context.Context, userID string, createShare func() error) error
// NewDriveItemPermissionsService creates a new DriveItemPermissionsService
func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], identityCache identity.IdentityCache, config *config.Config, tp trace.TracerProvider, be identity.Backend, espc externalSharePermissionChecker, vsc vaultShareCreator) (DriveItemPermissionsService, error) {
func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], identityCache identity.IdentityCache, config *config.Config, tp trace.TracerProvider, be identity.Backend, espc externalSharePermissionChecker) (DriveItemPermissionsService, error) {
f := func(context.Context) bool { return false }
if espc != nil {
f = espc
}
c := func(_ context.Context, _ string, createShare func() error) error { return createShare() }
if vsc != nil {
c = vsc
}
return DriveItemPermissionsService{
BaseGraphService: BaseGraphService{
@@ -114,7 +105,6 @@ func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Sele
tp: tp,
identityBackend: be,
hasExternalSharePermission: f,
createVaultShare: c,
}, nil
}
@@ -285,20 +275,8 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
if shareExpiration != nil {
createShareRequest.GetGrant().Expiration = shareExpiration
}
var createShareResponse *collaboration.CreateShareResponse
createShare := func() error {
var err error
createShareResponse, err = gatewayClient.CreateShare(ctx, createShareRequest)
return errorcode.FromCS3Status(createShareResponse.GetStatus(), err)
}
// the vault share check needs a role with vault mode, which a user of another instance only
// gets at their first login here. Only a sharer who may share the resource gets it assigned.
if IsVaultResource(resourceID) && statResponse.GetInfo().GetPermissionSet().GetAddGrant() {
err = s.createVaultShare(ctx, user.GetId(), createShare)
} else {
err = createShare()
}
if err != nil {
createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest)
if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil {
s.logger.Error().Err(err).Str("resourceId", resourceId.GetStorageId()).Interface("userId", objectID).Msg("share creation failed")
return libregraph.Permission{}, err
}
@@ -55,7 +55,7 @@ var _ = Describe("createLinkTests", func() {
cache := identity.NewIdentityCache(identity.IdentityCacheWithGatewaySelector(gatewaySelector))
cfg := defaults.FullDefaultConfig()
svc, err = service.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil, nil)
svc, err = service.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil)
Expect(err).ToNot(HaveOccurred())
driveItemId = &provider.ResourceId{
StorageId: "1",
@@ -80,7 +80,7 @@ var _ = Describe("DriveItemPermissionsService", func() {
cfg.UnifiedRoles.AvailableRoles = slices.DeleteFunc(cfg.UnifiedRoles.AvailableRoles, func(s string) bool {
return s == unifiedrole.UnifiedRoleSecureViewerID
})
service, err := svc.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil, nil)
service, err := svc.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil)
Expect(err).ToNot(HaveOccurred())
driveItemPermissionsService = service
ctx = revactx.ContextSetUser(context.Background(), currentUser)
@@ -174,80 +174,6 @@ var _ = Describe("DriveItemPermissionsService", func() {
Expect(permission.GrantedToV2.Group.GetId()).To(Equal("2"))
})
Describe("a vault share with the guest vault role", func() {
var (
// wrapped records the users whose share creation went through the guest vault role
wrapped []string
vaultItem *provider.ResourceId
)
BeforeEach(func() {
wrapped = nil
service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil,
func(_ context.Context, userID string, createShare func() error) error {
wrapped = append(wrapped, userID)
return createShare()
})
Expect(err).ToNot(HaveOccurred())
driveItemPermissionsService = service
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")},
}
createShareResponse.Share = &collaboration.Share{Id: &collaboration.ShareId{OpaqueId: "123"}}
// the sharer may share the resource
statResponse.Info.PermissionSet = &provider.ResourcePermissions{Stat: true, AddGrant: true}
vaultItem = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: driveItemId.SpaceId,
OpaqueId: driveItemId.OpaqueId,
}
})
It("is created through it", func() {
statResponse.Info.Id = vaultItem
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil)
permission, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(permission.GetId()).To(Equal("123"))
Expect(wrapped).To(Equal([]string{"1"}))
})
It("returns the error of the share creation", func() {
statResponse.Info.Id = vaultItem
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{
Status: status.NewAlreadyExists(ctx, nil, "the share already exists"),
}, nil)
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).To(HaveOccurred())
Expect(wrapped).To(Equal([]string{"1"}))
})
It("is not used when the sharer may not share the resource", func() {
statResponse.Info.Id = vaultItem
statResponse.Info.PermissionSet = &provider.ResourcePermissions{Stat: true}
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(&collaboration.CreateShareResponse{
Status: status.NewPermissionDenied(ctx, nil, "no permission to share"),
}, nil)
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).To(HaveOccurred())
Expect(wrapped).To(BeEmpty())
gatewayClient.AssertCalled(GinkgoT(), "CreateShare", mock.Anything, mock.Anything)
})
It("is not used for a share outside the vault", func() {
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil)
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(wrapped).To(BeEmpty())
})
})
It("applies a default 30-day expiration to a vault user share created without one", func() {
statResponse.Info.Id = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
@@ -459,7 +385,7 @@ var _ = Describe("DriveItemPermissionsService", func() {
// remove SecureViewer from allowed roles for this unit test
return s == unifiedrole.UnifiedRoleSecureViewerID
})
service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil, nil)
service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil)
Expect(err).ToNot(HaveOccurred())
driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID, unifiedrole.UnifiedRoleSecureViewerID}
@@ -1,13 +1,6 @@
package svc
import "context"
var (
CS3ReceivedShareToLibreGraphPermissions = cs3ReceivedShareToLibreGraphPermissions
Cs3ReceivedSharesToDriveItems = cs3ReceivedSharesToDriveItems
)
// WithGuestVaultRole exposes withGuestVaultRole to the tests
func (g Graph) WithGuestVaultRole(ctx context.Context, userID string, createShare func() error) error {
return g.withGuestVaultRole(ctx, userID, createShare)
}
-1
View File
@@ -59,7 +59,6 @@ type Graph struct {
identityBackend identity.Backend
identityEducationBackend identity.EducationBackend
roleService RoleService
guestRoleMapping []guestRoleMapping
permissionsService Permissions
valueService settingssvc.ValueService
specialDriveItemsCache *ttlcache.Cache[string, interface{}]
@@ -1,204 +0,0 @@
package svc
import (
"context"
"slices"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/utils"
"go-micro.dev/v4/metadata"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/rolemapping"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
)
// guestRoleMapping maps a value to the role a multi-instance guest gets, see
// OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING. The proxy applies it to the roles claim at login.
type guestRoleMapping struct {
value rolemapping.Matcher
roleName string
}
// parseGuestRoleMapping parses the pairs like the proxy does, and compiles their values once.
func parseGuestRoleMapping(pairs []string) ([]guestRoleMapping, error) {
mappings := make([]guestRoleMapping, 0, len(pairs))
for _, pair := range pairs {
value, roleName, err := rolemapping.ParsePair(pair)
if err != nil {
return nil, err
}
mappings = append(mappings, guestRoleMapping{value: rolemapping.NewMatcher(value), roleName: roleName})
}
return mappings, nil
}
// guestVaultRoleID returns the id of the role the first mapping that matches the userClass gives,
// like the proxy picks it at login, if that role grants vault mode. It returns "" otherwise.
func guestVaultRoleID(mappings []guestRoleMapping, userClass []string, roles []*settingsmsg.Bundle) string {
for _, m := range mappings {
if !slices.ContainsFunc(userClass, m.value.Matches) {
continue
}
for _, role := range roles {
if role.GetName() == m.roleName && roleGrantsVaultMode(role) {
return role.GetId()
}
}
return ""
}
return ""
}
// guestVaultEligible reports whether the guest role mapping gives the user's userClass a role with
// vault mode. A failed lookup leaves them out, like members, who get their role from the role mapping
// of members at login.
func (g Graph) guestVaultEligible(ctx context.Context, userID string, roles []*settingsmsg.Bundle) bool {
userClass, member, err := g.identityBackend.GetUserClass(ctx, userID)
if err != nil || member {
return false
}
return guestVaultRoleID(g.guestRoleMapping, userClass, roles) != ""
}
// withGuestVaultRole creates a vault share for the user with createShare. The vault share check only
// reads role assignments, and a user of another instance only gets a role here at their first login
// here. So if the user has no role yet, withGuestVaultRole first assigns the role the guest role
// mapping gives their userClass, if it grants vault mode, and removes it again if the share fails.
func (g Graph) withGuestVaultRole(ctx context.Context, userID string, createShare func() error) error {
logger := g.logger.SubloggerWithRequestID(ctx)
role, err := g.assignGuestVaultRole(ctx, userID)
if err != nil {
// without the role the vault share check refuses the share
logger.Warn().Err(err).Str("userid", userID).Msg("could not assign the guest vault role")
}
if err := createShare(); err != nil {
role.undo()
return err
}
if err := role.finish(ctx); err != nil {
logger.Warn().Err(err).Str("userid", userID).Msg("could not adjust the personal space to the guest vault role")
}
return nil
}
// guestVaultRole is a guest vault role assigned for a vault share that is about to be created. The
// zero value is no role, its methods do nothing then.
type guestVaultRole struct {
g Graph
serviceCtx context.Context
gatewayClient gateway.GatewayAPIClient
userID string
roleID string
assignmentID string
}
// assignGuestVaultRole assigns a guest who has no role here yet the role the guest role mapping gives
// their userClass, if that role grants vault mode. It returns the zero value if it assigned no role.
//
// Only the mapping counts. A guest no mapping matches gets OCIS_MULTI_INSTANCE_GUEST_ROLE at login,
// which is not assigned here: such a guest can only receive vault shares after their first login.
func (g Graph) assignGuestVaultRole(ctx context.Context, userID string) (guestVaultRole, error) {
// like the proxy, only for multi-instance guests
if !g.config.MultiInstance.Enabled || len(g.guestRoleMapping) == 0 {
return guestVaultRole{}, nil
}
assignments, err := g.roleService.ListRoleAssignments(ctx, &settingssvc.ListRoleAssignmentsRequest{AccountUuid: userID})
if err != nil {
return guestVaultRole{}, err
}
if len(assignments.GetAssignments()) > 0 {
return guestVaultRole{}, nil
}
userClass, member, err := g.identityBackend.GetUserClass(ctx, userID)
if err != nil {
return guestVaultRole{}, err
}
// members get their role from the role mapping of members at login, not from the guest mapping
if member {
return guestVaultRole{}, nil
}
roles, err := g.roleService.ListRoles(ctx, &settingssvc.ListBundlesRequest{})
if err != nil {
return guestVaultRole{}, err
}
roleID := guestVaultRoleID(g.guestRoleMapping, userClass, roles.GetBundles())
if roleID == "" {
return guestVaultRole{}, nil
}
// assigning roles needs the role management permission. Start from a new context, the settings
// service would check the role ids of the sharing user in the request context instead.
gatewayClient, err := g.gatewaySelector.Next()
if err != nil {
return guestVaultRole{}, err
}
serviceCtx, err := utils.GetServiceUserContextWithContext(context.Background(), gatewayClient, g.config.ServiceAccount.ServiceAccountID, g.config.ServiceAccount.ServiceAccountSecret)
if err != nil {
return guestVaultRole{}, err
}
serviceCtx = metadata.Set(serviceCtx, middleware.AccountID, g.config.ServiceAccount.ServiceAccountID)
assignment, err := g.roleService.AssignRoleToUser(serviceCtx, &settingssvc.AssignRoleToUserRequest{
AccountUuid: userID,
RoleId: roleID,
})
if err != nil {
return guestVaultRole{}, err
}
return guestVaultRole{
g: g,
serviceCtx: serviceCtx,
gatewayClient: gatewayClient,
userID: userID,
roleID: roleID,
assignmentID: assignment.GetAssignment().GetId(),
}, nil
}
// undo removes the role, the user had none before
func (r guestVaultRole) undo() {
if r.roleID == "" {
return
}
r.g.revertRoleAssignment(r.serviceCtx, r.userID, "", r.assignmentID)
}
// finish adjusts the personal space to the role and announces the change, like the other role
// assignments. The share exists, so the role stays even if the personal space can't be adjusted.
func (r guestVaultRole) finish(ctx context.Context) error {
if r.roleID == "" {
return nil
}
canCreateDrives, err := r.g.checkUserPermission(r.serviceCtx, "Drives.Create", r.userID, r.gatewayClient)
switch {
case err != nil:
// leave the personal space as it is when it's unclear what the role allows
case canCreateDrives:
err = shared.RestorePersonalSpace(r.serviceCtx, r.gatewayClient, r.userID)
default:
err = shared.DisablePersonalSpace(r.serviceCtx, r.gatewayClient, r.userID)
}
oldRole := ""
e := events.UserFeatureChanged{
UserID: r.userID,
Features: []events.UserFeature{
{
Name: "roleChanged",
Value: r.roleID,
OldValue: &oldRole,
},
},
Timestamp: utils.TSNow(),
}
if currentUser, ok := revactx.ContextGetUser(ctx); ok {
e.Executant = currentUser.GetId()
}
r.g.publishEvent(ctx, e)
return err
}
+1 -7
View File
@@ -191,12 +191,6 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx
svc.roleService = options.RoleService
guestRoleMapping, err := parseGuestRoleMapping(options.Config.MultiInstance.GuestRoleMapping)
if err != nil {
return svc, err
}
svc.guestRoleMapping = guestRoleMapping
roleManager := options.RoleManager
if roleManager == nil {
storeOptions := []microstore.Option{
@@ -234,7 +228,7 @@ func NewService(opts ...Option) (Graph, error) { //nolint:maintidx
return svc, err
}
driveItemPermissionsService, err := NewDriveItemPermissionsService(options.Logger, options.GatewaySelector, identityCache, options.Config, options.TraceProvider, svc.identityBackend, svc.contextUserHasExternalSharePermission, svc.withGuestVaultRole)
driveItemPermissionsService, err := NewDriveItemPermissionsService(options.Logger, options.GatewaySelector, identityCache, options.Config, options.TraceProvider, svc.identityBackend, svc.contextUserHasExternalSharePermission)
if err != nil {
return svc, err
}
@@ -286,11 +286,9 @@ func (g Graph) applyFilterVaultEligible(ctx context.Context, req *godata.GoDataR
// unlike other filters, vaultEligible applies its own role check below, so it's safe to
// look up a cross-instance match here - the GetUsers switch only blocks a cross-instance
// lookup when it would bypass that check entirely.
var preciseUserID string
if username, instancename := g.parseExternalSearch(req); username != "" && instancename != "" &&
g.contextUserHasExternalSharePermission(ctx) {
if preciseUser, err := g.identityBackend.GetPreciseUser(ctx, username, instancename, req); err == nil {
preciseUserID = preciseUser.GetId()
found := false
for _, u := range users {
if u.GetId() == preciseUser.GetId() {
@@ -337,13 +335,6 @@ func (g Graph) applyFilterVaultEligible(ctx context.Context, req *godata.GoDataR
if err != nil {
return err
}
// a user of another instance only gets a role here at their first login here. Until
// then, check the role the guest role mapping gives their userClass, like
// assignGuestVaultRole does when the vault share is created.
if len(assignments.GetAssignments()) == 0 && user.GetId() == preciseUserID && len(g.guestRoleMapping) > 0 {
eligible[i] = g.guestVaultEligible(egCtx, user.GetId(), roles.GetBundles())
return nil
}
for _, assignment := range assignments.GetAssignments() {
if _, ok := vaultGrantingRoles[assignment.GetRoleId()]; ok {
eligible[i] = true
-396
View File
@@ -13,8 +13,6 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
invitepb "github.com/cs3org/go-cs3apis/cs3/ocm/invite/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/go-chi/chi/v5"
@@ -22,18 +20,14 @@ import (
. "github.com/onsi/gomega"
libregraph "github.com/owncloud/libre-graph-api-go"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"go-micro.dev/v4/client"
gmmetadata "go-micro.dev/v4/metadata"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
settings "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
@@ -872,396 +866,6 @@ var _ = Describe("Users", func() {
Expect(res.Value).To(BeEmpty())
})
})
Describe("the vaultEligible filter, with a cross-instance match without a role here", func() {
const (
crossInstanceUser = "cross-instance-user"
localUser = "local-user"
guestRole = "user-light"
vaultGuestRole = "user-light-vault"
)
mapping := []string{"lehrer:" + vaultGuestRole, "Nutzerverwalter:" + vaultGuestRole}
// search runs the vaultEligible search for a cross-instance match with the given
// userClass and membership, in a service with the given guest role mapping.
search := func(mapping []string, userClass []string, member bool, assignments []*settingsmsg.UserRoleAssignment) []string {
cfg.MultiInstance.GuestRoleMapping = mapping
mappedSvc, err := service.NewService(
service.Config(cfg),
service.WithGatewaySelector(gatewaySelector),
service.EventsPublisher(&eventsPublisher),
service.WithIdentityBackend(identityBackend),
service.WithRoleService(roleService),
service.WithValueService(valueService),
service.PermissionService(permissionService),
)
Expect(err).ToNot(HaveOccurred())
crossInstance := &libregraph.User{}
crossInstance.SetId(crossInstanceUser)
identityBackend.On("GetPreciseUser", mock.Anything, "someone", "school5", mock.Anything).
Return(crossInstance, nil)
identityBackend.On("GetUserClass", mock.Anything, crossInstanceUser).Return(userClass, member, nil)
expectAssignments(crossInstanceUser, assignments, nil)
// the mapping names roles, so the bundles need their names
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListBundlesResponse{
Bundles: []*settingsmsg.Bundle{
{
Id: vaultRole,
Name: vaultGuestRole,
Type: settingsmsg.Bundle_TYPE_ROLE,
Settings: []*settingsmsg.Setting{
{
Name: permission.VaultMode,
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
},
},
},
{
Id: vaultLessRole,
Name: guestRole,
Type: settingsmsg.Bundle_TYPE_ROLE,
},
},
}, nil)
r := httptest.NewRequest(http.MethodGet,
"/graph/v1.0/users?$search="+url.QueryEscape(`"someone@school5.example.test"`)+
"&$filter="+url.QueryEscape("vaultEligible eq true"), nil)
mappedSvc.GetUsers(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
data, err := io.ReadAll(rr.Body)
Expect(err).ToNot(HaveOccurred())
res := userList{}
Expect(json.Unmarshal(data, &res)).To(Succeed())
ids := make([]string, 0, len(res.Value))
for _, u := range res.Value {
ids = append(ids, u.GetId())
}
return ids
}
DescribeTable("checks the role their first login here will give them",
func(mapping []string, userClass []string, member bool, included bool) {
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
ids := search(mapping, userClass, member, nil)
if included {
Expect(ids).To(ConsistOf(crossInstanceUser))
} else {
Expect(ids).To(BeEmpty())
}
},
Entry("includes a teacher", mapping, []string{"lehrer"}, false, true),
Entry("includes a local admin", mapping, []string{"Nutzerverwalter"}, false, true),
Entry("excludes a student, no mapping matches", mapping, []string{"schueler"}, false, false),
Entry("excludes a user without userClass", mapping, nil, false, false),
Entry("excludes everyone without a mapping", nil, []string{"lehrer"}, false, false),
Entry("excludes a member of this instance, who gets the role of members at login",
mapping, []string{"lehrer"}, true, false),
Entry("matches a regular expression", []string{"lehr.*:" + vaultGuestRole}, []string{"lehrer"}, false, true),
Entry("excludes when the first matching mapping gives a role without vault mode",
[]string{"lehrer:" + guestRole, "lehrer:" + vaultGuestRole}, []string{"lehrer"}, false, false),
)
It("keeps the role the user got at a login here", func() {
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
ids := search(mapping, []string{"lehrer"}, false, []*settingsmsg.UserRoleAssignment{
{Id: "assignment-ID", AccountUuid: crossInstanceUser, RoleId: vaultLessRole},
})
Expect(ids).To(BeEmpty())
identityBackend.AssertNotCalled(GinkgoT(), "GetUserClass", mock.Anything, mock.Anything)
})
It("does not apply the mapping to users of this instance without a role", func() {
local := &libregraph.User{}
local.SetId(localUser)
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{local}, nil)
expectAssignments(localUser, nil, nil)
ids := search(mapping, []string{"lehrer"}, false, nil)
Expect(ids).To(ConsistOf(crossInstanceUser))
identityBackend.AssertNotCalled(GinkgoT(), "GetUserClass", mock.Anything, localUser)
})
It("refuses to start with an invalid mapping", func() {
cfg.MultiInstance.GuestRoleMapping = []string{"lehrer"}
_, err := service.NewService(
service.Config(cfg),
service.WithGatewaySelector(gatewaySelector),
service.EventsPublisher(&eventsPublisher),
service.WithIdentityBackend(identityBackend),
service.WithRoleService(roleService),
service.WithValueService(valueService),
service.PermissionService(permissionService),
)
Expect(err).To(HaveOccurred())
})
})
})
Describe("withGuestVaultRole", func() {
const (
guestUser = "guest-user"
guestRole = "user-light"
vaultGuestRole = "user-light-vault"
serviceAccount = "service-account-ID"
)
vaultMapping := []string{"lehrer:" + vaultGuestRole}
var (
guestSvc service.Graph
// a publisher of its own: the shared one keeps the events of other tests
guestEvents *mocks.Publisher
)
// newGuestService creates a service with the given guest role mapping
newGuestService := func(mapping []string) {
cfg.MultiInstance.Enabled = true
cfg.MultiInstance.GuestRoleMapping = mapping
cfg.ServiceAccount.ServiceAccountID = serviceAccount
guestEvents = &mocks.Publisher{}
guestEvents.On("Publish", mock.Anything, mock.Anything, mock.Anything).Return(nil)
var err error
guestSvc, err = service.NewService(
service.Config(cfg),
service.WithGatewaySelector(gatewaySelector),
service.EventsPublisher(guestEvents),
service.WithIdentityBackend(identityBackend),
service.WithRoleService(roleService),
service.WithValueService(valueService),
service.PermissionService(permissionService),
)
Expect(err).ToNot(HaveOccurred())
}
// expectUserClass reports the guest as a user of another instance with the given userClass
expectUserClass := func(userClass ...string) {
identityBackend.On("GetUserClass", mock.Anything, guestUser).Return(userClass, false, nil)
}
// the mapping names roles, so the bundles need their names
expectNamedRoles := func() {
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListBundlesResponse{
Bundles: []*settingsmsg.Bundle{
{
Id: vaultRole,
Name: vaultGuestRole,
Type: settingsmsg.Bundle_TYPE_ROLE,
Settings: []*settingsmsg.Setting{
{
Name: permission.VaultMode,
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
},
},
},
{
Id: vaultLessRole,
Name: guestRole,
Type: settingsmsg.Bundle_TYPE_ROLE,
},
},
}, nil)
}
expectAssignRole := func(err error) {
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).
Return(&gateway.AuthenticateResponse{Status: status.NewOK(ctx), Token: "service-token"}, nil)
roleService.On("AssignRoleToUser",
// as the service account, and without the role ids of the sharing user
mock.MatchedBy(func(ctx context.Context) bool {
accountID, _ := gmmetadata.Get(ctx, middleware.AccountID)
_, hasRoleIDs := gmmetadata.Get(ctx, middleware.RoleIDs)
return accountID == serviceAccount && !hasRoleIDs
}),
mock.MatchedBy(func(in *settings.AssignRoleToUserRequest) bool {
return in.GetAccountUuid() == guestUser && in.GetRoleId() == vaultRole
}),
mock.Anything,
).Return(&settings.AssignRoleToUserResponse{
Assignment: &settingsmsg.UserRoleAssignment{Id: "new-assignment-ID", AccountUuid: guestUser, RoleId: vaultRole},
}, err)
}
// expectPersonalSpace answers the Drives.Create check of the new role and lists the
// guest's personal spaces
expectPersonalSpace := func(drivesCreate *cs3rpc.Status, spaces ...*provider.StorageSpace) {
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserResponse{
Status: status.NewOK(ctx),
User: &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: guestUser}},
}, nil)
gatewayClient.On("CheckPermission", mock.Anything, mock.MatchedBy(func(in *permissions.CheckPermissionRequest) bool {
return in.GetPermission() == "Drives.Create"
})).Return(&permissions.CheckPermissionResponse{Status: drivesCreate}, nil)
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
Status: status.NewOK(ctx),
StorageSpaces: spaces,
}, nil)
}
sharerCtx := func() context.Context {
return revactx.ContextSetUser(gmmetadata.Set(ctx, middleware.RoleIDs, `["teacher-role-ID"]`), currentUser)
}
expectRemoveRole := func() {
roleService.On("RemoveRoleFromUser", mock.Anything, mock.MatchedBy(func(in *settings.RemoveRoleFromUserRequest) bool {
return in.GetId() == "new-assignment-ID"
}), mock.Anything).Return(&emptypb.Empty{}, nil)
}
roleChanged := mock.MatchedBy(func(e events.UserFeatureChanged) bool {
return e.UserID == guestUser && e.Executant.GetOpaqueId() == currentUser.GetId().GetOpaqueId() &&
len(e.Features) == 1 && e.Features[0].Name == "roleChanged" && e.Features[0].Value == vaultRole
})
// expectAssignedRole sets up a guest without a role whose userClass maps to the vault role
expectAssignedRole := func() {
newGuestService(vaultMapping)
expectAssignments(guestUser, nil, nil)
expectUserClass("lehrer")
expectNamedRoles()
expectAssignRole(nil)
}
// shareOK and shareFails stand in for the share creation
shareOK := func() error { return nil }
shareFails := func() error { return errors.New("the share already exists") }
It("assigns the role before the share is created and finishes it afterwards", func() {
expectAssignedRole()
// a guest usually has no personal space here, then there is nothing to disable
expectPersonalSpace(status.NewPermissionDenied(ctx, nil, "no Drives.Create"))
shared := false
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, func() error {
shared = true
roleService.AssertNumberOfCalls(GinkgoT(), "AssignRoleToUser", 1)
// nothing else happens before the share exists
gatewayClient.AssertNotCalled(GinkgoT(), "ListStorageSpaces", mock.Anything, mock.Anything)
guestEvents.AssertNotCalled(GinkgoT(), "Publish", mock.Anything, roleChanged, mock.Anything)
return nil
})).To(Succeed())
Expect(shared).To(BeTrue())
gatewayClient.AssertNotCalled(GinkgoT(), "DeleteStorageSpace", mock.Anything, mock.Anything)
guestEvents.AssertCalled(GinkgoT(), "Publish", mock.Anything, roleChanged, mock.Anything)
})
It("removes the role again when the share fails, and returns its error", func() {
expectAssignedRole()
expectRemoveRole()
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareFails)).To(MatchError("the share already exists"))
roleService.AssertNumberOfCalls(GinkgoT(), "RemoveRoleFromUser", 1)
gatewayClient.AssertNotCalled(GinkgoT(), "ListStorageSpaces", mock.Anything, mock.Anything)
guestEvents.AssertNotCalled(GinkgoT(), "Publish", mock.Anything, roleChanged, mock.Anything)
})
It("disables a personal space the guest role has no Drives.Create for", func() {
expectAssignedRole()
expectPersonalSpace(status.NewPermissionDenied(ctx, nil, "no Drives.Create"), &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: "personal-space-ID"},
SpaceType: "personal",
})
gatewayClient.On("DeleteStorageSpace", mock.Anything, mock.MatchedBy(func(in *provider.DeleteStorageSpaceRequest) bool {
return in.GetId().GetOpaqueId() == "personal-space-ID"
})).Return(&provider.DeleteStorageSpaceResponse{Status: status.NewOK(ctx)}, nil)
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareOK)).To(Succeed())
gatewayClient.AssertNumberOfCalls(GinkgoT(), "DeleteStorageSpace", 1)
})
// the share exists in both cases, so the role stays and there is no error
It("keeps the role and leaves the personal space as it is when its Drives.Create permission can't be determined", func() {
expectAssignedRole()
expectPersonalSpace(status.NewInternal(ctx, "settings unavailable"))
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareOK)).To(Succeed())
roleService.AssertNotCalled(GinkgoT(), "RemoveRoleFromUser", mock.Anything, mock.Anything, mock.Anything)
gatewayClient.AssertNotCalled(GinkgoT(), "ListStorageSpaces", mock.Anything, mock.Anything)
guestEvents.AssertCalled(GinkgoT(), "Publish", mock.Anything, roleChanged, mock.Anything)
})
It("keeps the role when the personal space can't be adjusted", func() {
expectAssignedRole()
expectPersonalSpace(status.NewPermissionDenied(ctx, nil, "no Drives.Create"), &provider.StorageSpace{
Id: &provider.StorageSpaceId{OpaqueId: "personal-space-ID"},
SpaceType: "personal",
})
gatewayClient.On("DeleteStorageSpace", mock.Anything, mock.Anything).
Return(&provider.DeleteStorageSpaceResponse{Status: status.NewInternal(ctx, "storage unavailable")}, nil)
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareOK)).To(Succeed())
roleService.AssertNotCalled(GinkgoT(), "RemoveRoleFromUser", mock.Anything, mock.Anything, mock.Anything)
guestEvents.AssertCalled(GinkgoT(), "Publish", mock.Anything, roleChanged, mock.Anything)
})
It("still creates the share when the role can't be assigned", func() {
newGuestService(vaultMapping)
expectAssignments(guestUser, nil, nil)
expectUserClass("lehrer")
expectNamedRoles()
expectAssignRole(errors.New("forbidden"))
shared := false
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, func() error {
shared = true
return nil
})).To(Succeed())
Expect(shared).To(BeTrue())
roleService.AssertNotCalled(GinkgoT(), "RemoveRoleFromUser", mock.Anything, mock.Anything, mock.Anything)
})
// expectNothingAssigned checks that the share is created without assigning, removing or
// finishing a role, and that a failing share still returns its error
expectNothingAssigned := func() {
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareOK)).To(Succeed())
Expect(guestSvc.WithGuestVaultRole(sharerCtx(), guestUser, shareFails)).To(MatchError("the share already exists"))
roleService.AssertNotCalled(GinkgoT(), "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
roleService.AssertNotCalled(GinkgoT(), "RemoveRoleFromUser", mock.Anything, mock.Anything, mock.Anything)
gatewayClient.AssertNotCalled(GinkgoT(), "ListStorageSpaces", mock.Anything, mock.Anything)
}
It("keeps a role the user already has", func() {
newGuestService(vaultMapping)
expectAssignments(guestUser, []*settingsmsg.UserRoleAssignment{
{Id: "assignment-ID", AccountUuid: guestUser, RoleId: vaultLessRole},
}, nil)
expectNothingAssigned()
identityBackend.AssertNotCalled(GinkgoT(), "GetUserClass", mock.Anything, mock.Anything)
})
DescribeTable("does not assign a role",
func(mapping []string, userClass []string) {
newGuestService(mapping)
expectAssignments(guestUser, nil, nil)
expectUserClass(userClass...)
expectNamedRoles()
expectNothingAssigned()
},
Entry("to a student, no mapping matches", vaultMapping, []string{"schueler"}),
Entry("to a user without userClass", vaultMapping, nil),
Entry("when the mapped role has no vault mode", []string{"lehrer:" + guestRole}, []string{"lehrer"}),
)
It("does not assign a guest role to a member of this instance", func() {
newGuestService(vaultMapping)
expectAssignments(guestUser, nil, nil)
identityBackend.On("GetUserClass", mock.Anything, guestUser).Return([]string{"lehrer"}, true, nil)
expectNothingAssigned()
})
It("does nothing without a mapping", func() {
newGuestService(nil)
expectNothingAssigned()
roleService.AssertNotCalled(GinkgoT(), "ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything)
})
It("does nothing without multi-instance", func() {
newGuestService(vaultMapping)
cfg.MultiInstance.Enabled = false
expectNothingAssigned()
roleService.AssertNotCalled(GinkgoT(), "ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything)
})
})
DescribeTable("GetUsers handles unsupported or invalid filters",
+32 -4
View File
@@ -26,6 +26,7 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/l10n"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/notifications/pkg/channels"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
@@ -196,8 +197,10 @@ func (s eventsNotifier) send(ctx context.Context, emails []*channels.Message) {
}
}
func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId) []*user.User {
granteeList, err := s.getGranteeList(ctx, executant, u, g)
// ensureGranteeList resolves the grantee to the users who get the notification.
// For a vault resource it keeps only the users who hold the VaultMode permission.
func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId, inVault bool) []*user.User {
granteeList, err := s.getGranteeList(ctx, executant, u, g, inVault)
if err != nil {
s.logger.Error().Err(err).Str("event", "ensureGranteeList").Msg("Could not get grantee list")
return nil
@@ -207,9 +210,18 @@ func (s eventsNotifier) ensureGranteeList(ctx context.Context, executant, u *use
return granteeList
}
func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId) ([]*user.User, error) {
func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.UserId, g *group.GroupId, inVault bool) ([]*user.User, error) {
switch {
case u != nil:
if inVault {
gatewayClient, err := s.gatewaySelector.Next()
if err != nil {
return nil, err
}
if len(s.filterVaultModeUsers(ctx, gatewayClient, []*user.UserId{u})) == 0 {
return nil, nil
}
}
if s.disableEmails(ctx, u) {
return nil, nil
}
@@ -236,12 +248,21 @@ func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.U
return nil, errors.New("could not get group")
}
userList := make([]*user.User, 0, len(res.GetGroup().GetMembers()))
members := make([]*user.UserId, 0, len(res.GetGroup().GetMembers()))
for _, userID := range res.GetGroup().GetMembers() {
// don't add the executant
if userID.GetOpaqueId() == executant.GetOpaqueId() {
continue
}
members = append(members, userID)
}
// check the vault permission first, so that members without it cost no further calls
if inVault {
members = s.filterVaultModeUsers(ctx, gatewayClient, members)
}
userList := make([]*user.User, 0, len(members))
for _, userID := range members {
// don't add users who opted out
if s.disableEmails(ctx, userID) {
continue
@@ -262,6 +283,13 @@ func (s eventsNotifier) getGranteeList(ctx context.Context, executant, u *user.U
}
}
// filterVaultModeUsers keeps only the users who hold the VaultMode permission.
func (s eventsNotifier) filterVaultModeUsers(ctx context.Context, gatewayClient gateway.GatewayAPIClient, userIDs []*user.UserId) []*user.UserId {
return vault.FilterVaultModeUsers(ctx, gatewayClient, userIDs, func(id *user.UserId, err error) {
s.logger.Error().Err(err).Str("userId", id.GetOpaqueId()).Msg("could not check the vault permission, user skipped")
})
}
func (s eventsNotifier) getUser(ctx context.Context, u *user.UserId) (*user.User, error) {
if u == nil {
return nil, errors.New("need at least one non-nil grantee")
@@ -24,6 +24,7 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
@@ -292,6 +293,7 @@ https://owncloud.com
DescribeTable("Vault resources are redacted in notifications",
func(ev events.Event, mustNotContain string) {
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(&permissions.CheckPermissionResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil)
received := make(chan *channels.Message, 1)
ch := make(chan events.Event)
evts := NewEventsNotifier(trace.NewNoopTracerProvider(), ch, capturingChannel{out: received}, log.NewLogger(), gatewaySelector, vs, "",
@@ -365,6 +367,66 @@ https://owncloud.com
},
}, "vault space"),
)
DescribeTable("Vault group grantees are filtered by the vault mode permission",
func(ev events.Event) {
outsider := &user.User{
Id: &user.UserId{OpaqueId: "outsider"},
Mail: "outsider@owncloud.com",
DisplayName: "Otto Outsider",
}
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&group.GetGroupResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Group: &group.Group{Members: []*user.UserId{sharee.GetId(), outsider.GetId()}},
}, nil)
gatewayClient.On("GetUser", mock.Anything, mock.MatchedBy(func(r *user.GetUserRequest) bool {
return r.GetUserId().GetOpaqueId() == outsider.GetId().GetOpaqueId()
})).Return(&user.GetUserResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, User: outsider}, nil)
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
code := rpc.Code_CODE_PERMISSION_DENIED
if r.GetSubjectRef().GetUserId().GetOpaqueId() == sharee.GetId().GetOpaqueId() {
code = rpc.Code_CODE_OK
}
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: code}}, nil
})
received := make(chan *channels.Message, 2)
ch := make(chan events.Event)
evts := NewEventsNotifier(trace.NewNoopTracerProvider(), ch, capturingChannel{out: received}, log.NewLogger(), gatewaySelector, vs, "",
"", "", "", "", "", "",
store.Create(), nil, nil)
go evts.Run()
ch <- ev
var msg *channels.Message
select {
case msg = <-received:
case <-time.Tick(3 * time.Second):
Fail("timeout waiting for notification")
}
Expect(msg.Recipient).To(Equal([]string{sharee.GetMail()}))
Consistently(received, 200*time.Millisecond).ShouldNot(Receive())
},
Entry("Share Created", events.Event{
Event: events.ShareCreated{
Sharer: sharer.GetId(),
GranteeGroupID: &group.GroupId{OpaqueId: "vaultgroup"},
CTime: utils.TimeToTS(time.Date(2023, 4, 17, 16, 42, 0, 0, time.UTC)),
ItemID: vaultResourceID,
},
}),
Entry("Added to Space", events.Event{
Event: events.SpaceShared{
Executant: sharer.GetId(),
Creator: sharer.GetId(),
GranteeGroupID: &group.GroupId{OpaqueId: "vaultgroup"},
ID: vaultSpaceID,
},
}),
)
})
var _ = Describe("Notifications X-Site Scripting", func() {
+4 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
"github.com/owncloud/reva/v2/pkg/events"
@@ -33,7 +34,7 @@ func (s eventsNotifier) handleShareCreated(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareCreated)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -123,7 +124,7 @@ func (s eventsNotifier) handleShareExpired(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareExpired)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -183,7 +184,7 @@ func (s eventsNotifier) handleShareRemoved(baseCtx context.Context, e events.Sha
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultStorage(e.ItemID.GetStorageId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventShareRemoved)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
+4 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
"github.com/owncloud/ocis/v2/services/notifications/pkg/email"
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
"github.com/owncloud/reva/v2/pkg/events"
@@ -23,7 +24,7 @@ func (s eventsNotifier) handleSpaceShared(baseCtx context.Context, e events.Spac
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.ID.GetOpaqueId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventSpaceShared)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -108,7 +109,7 @@ func (s eventsNotifier) handleSpaceUnshared(baseCtx context.Context, e events.Sp
return
}
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, executant.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.ID.GetOpaqueId()))
filteredGrantees := s.filter.execute(ctx, granteeList, defaults.SettingUUIDProfileEventSpaceUnshared)
recipientsInstant, recipientsDaily, recipientsInstantWeekly := s.splitter.execute(ctx, filteredGrantees)
@@ -207,7 +208,7 @@ func (s eventsNotifier) handleSpaceMembershipExpired(baseCtx context.Context, e
return
}
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID)
granteeList := s.ensureGranteeList(ctx, owner.GetId(), e.GranteeUserID, e.GranteeGroupID, vault.IsVaultSpace(e.SpaceID.GetOpaqueId()))
if granteeList == nil {
return
}
+23 -8
View File
@@ -4,13 +4,14 @@ import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"sync"
"time"
cs3user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
"github.com/owncloud/ocis/v2/ocis-pkg/rolemapping"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
@@ -81,9 +82,16 @@ func extractRoles(rolesClaim string, claims map[string]interface{}) (map[string]
// - regex match when ClaimValue is a regex pattern (e.g. "ocis-user-.*")
// The regex is matched against the entire claim value, not a substring.
func matchesClaimMapping(mappingValue string, claimRoles map[string]struct{}) bool {
m := rolemapping.NewMatcher(mappingValue)
if _, ok := claimRoles[mappingValue]; ok {
return true
}
rx, err := regexp.Compile("^(?:" + mappingValue + ")$")
if err != nil {
return false
}
for cr := range claimRoles {
if m.Matches(cr) {
if rx.MatchString(cr) {
return true
}
}
@@ -209,8 +217,10 @@ func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *c
return user, nil
}
// GuestRoleMapping reads the 'claimvalue:rolename' pairs of OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING,
// see rolemapping.ParsePair.
// GuestRoleMapping reads the 'claimvalue:rolename' pairs of OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING.
// A pair is split at its last colon, so the claim value may contain colons but the role name must not.
// Roles created through the settings service can't contain a colon, their names are restricted to
// letters, digits, '-' and '_'.
func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) {
pairs := cfg.MultiInstance.GuestRoleMapping
if len(pairs) > 0 && cfg.RoleAssignment.Driver != "oidc" {
@@ -223,9 +233,14 @@ func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) {
mappings := make([]config.RoleMapping, 0, len(pairs))
for _, pair := range pairs {
claimValue, roleName, err := rolemapping.ParsePair(pair)
if err != nil {
return nil, err
i := strings.LastIndex(pair, ":")
// 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: claimValue, RoleName: roleName})
}
+1 -1
View File
@@ -65,7 +65,7 @@ This extractor is the most simple one and just uses the resource information pro
### Tika Extractor
This extractor is more advanced compared to the [Basic extractor](#basic-extractor). The main difference is that this extractor is able to search file contents. However, [Apache Tika](https://tika.apache.org/) is required for this task. Read the [Apache Tika Server documentation](https://tika.apache.org/docs/4.2.x/using-tika/server/index.html) guide on how to install and run Tika or use a ready to run [Tika container](https://hub.docker.com/r/apache/tika). See the [Tika container usage document](https://github.com/apache/tika-docker#usage) for a quickstart. Note that at the time of writing, containers are only available for the amd64 platform.
This extractor is more advanced compared to the [Basic extractor](#basic-extractor). The main difference is that this extractor is able to search file contents. However, [Apache Tika](https://tika.apache.org/) is required for this task. Read the [Getting Started with Apache Tika](https://tika.apache.org/3.2.0/gettingstarted.html) guide on how to install and run Tika or use a ready to run [Tika container](https://hub.docker.com/r/apache/tika). See the [Tika container usage document](https://github.com/apache/tika-docker#usage) for a quickstart. Note that at the time of writing, containers are only available for the amd64 platform.
As soon as Tika is installed and accessible, the search service must be configured for the use with Tika. The following settings must be set:
-2
View File
@@ -5,8 +5,6 @@ type Extractor struct {
Type string `yaml:"type" env:"SEARCH_EXTRACTOR_TYPE" desc:"Defines the content extraction engine. Defaults to 'basic'. Supported values are: 'basic' and 'tika'." introductionVersion:"pre5.0"`
CS3AllowInsecure bool `yaml:"cs3_allow_insecure" env:"OCIS_INSECURE;SEARCH_EXTRACTOR_CS3SOURCE_INSECURE" desc:"Ignore untrusted SSL certificates when connecting to the CS3 source." introductionVersion:"pre5.0"`
Tika ExtractorTika `yaml:"tika"`
MaxConsecutiveFailures int `yaml:"max_consecutive_failures" env:"SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES" desc:"Abort a space (re)index walk after this many files in a row fail content extraction, which usually means the extraction service is down. Files that cannot be resolved at all are logged and skipped without counting towards this limit. Set to 0 to never abort." introductionVersion:"9.0.0"`
}
// ExtractorTika configures the Tika extractor
@@ -9,10 +9,6 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config"
)
// defaultMaxConsecutiveFailures is the number of consecutive extraction
// failures after which a space (re)index walk gives up on the extractor.
const defaultMaxConsecutiveFailures = 5
// FullDefaultConfig returns a fully initialized default configuration
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
@@ -50,7 +46,6 @@ func DefaultConfig() *config.Config {
TikaURL: "http://127.0.0.1:9998",
CleanStopWords: true,
},
MaxConsecutiveFailures: defaultMaxConsecutiveFailures,
},
Events: config.Events{
Endpoint: "127.0.0.1:9233",
@@ -2,7 +2,6 @@ package parser
import (
"errors"
"fmt"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
@@ -45,10 +44,6 @@ func Validate(cfg *config.Config) error {
if cfg.ServiceAccount.ServiceAccountSecret == "" {
return shared.MissingServiceAccountSecret(cfg.Service.Name)
}
if cfg.Extractor.MaxConsecutiveFailures < 0 {
return fmt.Errorf("%s: SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES must be 0 (never abort) or greater, got %d",
cfg.Service.Name, cfg.Extractor.MaxConsecutiveFailures)
}
return nil
}
@@ -1,44 +0,0 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/search/pkg/config"
"github.com/owncloud/ocis/v2/services/search/pkg/config/defaults"
)
func validConfig() *config.Config {
cfg := defaults.DefaultConfig()
cfg.TokenManager = &config.TokenManager{JWTSecret: "secret"}
cfg.ServiceAccount = config.ServiceAccount{ServiceAccountID: "id", ServiceAccountSecret: "secret"}
return cfg
}
func TestDefaultMaxConsecutiveFailures(t *testing.T) {
assert.Equal(t, 5, defaults.DefaultConfig().Extractor.MaxConsecutiveFailures)
}
func TestValidateMaxConsecutiveFailures(t *testing.T) {
for _, tc := range []struct {
name string
value int
wantErr bool
}{
{name: "default", value: 5},
{name: "never abort", value: 0},
{name: "negative", value: -1, wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := validConfig()
cfg.Extractor.MaxConsecutiveFailures = tc.value
err := Validate(cfg)
if tc.wantErr {
assert.ErrorContains(t, err, "SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES")
return
}
assert.NoError(t, err)
})
}
}
+6 -63
View File
@@ -5,8 +5,6 @@ import (
"fmt"
"io"
"math"
"net/http"
"regexp"
"strconv"
"strings"
"time"
@@ -21,21 +19,12 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config"
)
// tikaMajorVersion matches the major version in the tika server version string, e.g. "Apache Tika 4.2.0".
var tikaMajorVersion = regexp.MustCompile(`(\d+)\.\d+`)
// Tika 4.x renamed the X-TIKA:content metadata key to tk:content. We accept both
// so that tika 3.x and 4.x servers can be used.
var tikaContentKeys = []string{"tk:content", "X-TIKA:content"}
// Tika is used to extract content from a resource,
// it uses apache tika to retrieve all the data.
type Tika struct {
*Basic
Retriever
tika *tika.Client
tikaURL string
languagePath string
ContentExtractionSizeLimit uint64
CleanStopWords bool
}
@@ -57,9 +46,7 @@ func NewTikaExtractor(gatewaySelector pool.Selectable[gateway.GatewayAPIClient],
return &Tika{
Basic: basic,
Retriever: newCS3Retriever(gatewaySelector, logger, cfg.Extractor.CS3AllowInsecure),
tika: tk,
tikaURL: strings.TrimSuffix(cfg.Extractor.Tika.TikaURL, "/"),
languagePath: tikaLanguagePath(tkv),
tika: tika.NewClient(nil, cfg.Extractor.Tika.TikaURL),
ContentExtractionSizeLimit: cfg.ContentExtractionSizeLimit,
CleanStopWords: cfg.Extractor.Tika.CleanStopWords,
}, nil
@@ -109,11 +96,8 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
doc.Title = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Title, title))
}
for _, key := range tikaContentKeys {
if content, err := getFirstValue(meta, key); err == nil {
doc.Content = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Content, content))
break
}
if content, err := getFirstValue(meta, "X-TIKA:content"); err == nil {
doc.Content = strings.TrimSpace(fmt.Sprintf("%s %s", doc.Content, content))
}
doc.Location = t.getLocation(meta)
@@ -125,48 +109,13 @@ func (t Tika) Extract(ctx context.Context, ri *provider.ResourceInfo) (Document,
}
}
if langCode, _ := t.detectLanguage(ctx, doc.Content); langCode != "" && t.CleanStopWords {
if langCode, _ := t.tika.LanguageString(ctx, doc.Content); langCode != "" && t.CleanStopWords {
doc.Content = CleanString(doc.Content, langCode)
}
return doc, nil
}
// tikaLanguagePath returns the language detection endpoint of the tika server with the given
// version. Tika 4.x replaced /language/string with /language, which go-tika doesn't know about.
func tikaLanguagePath(version string) string {
if m := tikaMajorVersion.FindStringSubmatch(version); m != nil {
if major, err := strconv.Atoi(m[1]); err == nil && major >= 4 {
return "/language"
}
}
return "/language/string"
}
// detectLanguage returns the language code tika detects for the given text.
func (t Tika) detectLanguage(ctx context.Context, text string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, t.tikaURL+t.languagePath, strings.NewReader(text))
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("tika language detection failed: %s", resp.Status)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}
func (t Tika) getImage(meta map[string][]string) *libregraph.Image {
var image *libregraph.Image
initImage := func() {
@@ -200,20 +149,14 @@ func (t Tika) getLocation(meta map[string][]string) *libregraph.GeoCoordinates {
}
}
// Tika 4.x reports the altitude as geo:alt, tika 3.x as "GPS:GPS Altitude"
// which is returned as "227.4 metres" - extract the numeric portion
for _, key := range []string{"geo:alt", "GPS:GPS Altitude"} {
v, err := getFirstValue(meta, key)
if err != nil {
continue
}
// GPS Altitude is returned as "227.4 metres" - extract the numeric portion
if v, err := getFirstValue(meta, "GPS:GPS Altitude"); err == nil {
// Parse altitude value - remove " metres" suffix if present
altStr := strings.TrimSuffix(v, " metres")
altStr = strings.TrimSuffix(altStr, " m")
if alt, err := strconv.ParseFloat(strings.TrimSpace(altStr), 64); err == nil {
initLocation()
location.SetAltitude(alt)
break
}
}
+2 -75
View File
@@ -28,7 +28,6 @@ var _ = Describe("Tika", func() {
fullResponse string
language string
version string
tika4 bool
srv *httptest.Server
tika *content.Tika
)
@@ -36,46 +35,26 @@ var _ = Describe("Tika", func() {
BeforeEach(func() {
body = ""
language = ""
version = "Apache Tika 3.2.2"
tika4 = false
version = ""
fullResponse = ""
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
out := ""
switch req.URL.Path {
case "/version":
out = version
// tika 3.x serves /language/string, tika 4.x only /language
case "/language/string":
if tika4 {
w.WriteHeader(http.StatusNotFound)
return
}
out = language
case "/language":
if !tika4 {
w.WriteHeader(http.StatusNotFound)
return
}
out = language
case "/rmeta/text":
// tika 4.x renamed X-TIKA:content to tk:content
contentKey := "X-TIKA:content"
if tika4 {
contentKey = "tk:content"
}
if fullResponse != "" {
out = fullResponse
} else {
out = fmt.Sprintf(`[{"%s":"%s"}]`, contentKey, body)
out = fmt.Sprintf(`[{"X-TIKA:content":"%s"}]`, body)
}
}
_, _ = w.Write([]byte(out))
}))
})
JustBeforeEach(func() {
cfg := conf.DefaultConfig()
cfg.Extractor.Tika.TikaURL = srv.URL
cfg.Extractor.Tika.CleanStopWords = true
@@ -184,28 +163,6 @@ var _ = Describe("Tika", func() {
Expect(location.Longitude).To(Equal(libregraph.PtrFloat64(11.103870357204285)))
})
It("adds the altitude reported by tika 4.x as geo:alt", func() {
fullResponse = `[{"geo:lat": "43.467157", "geo:long": "11.885395", "geo:alt": "100"}]`
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Location).ToNot(BeNil())
Expect(doc.Location.Altitude).To(Equal(libregraph.PtrFloat64(100)))
})
It("adds the altitude reported by tika 3.x as GPS:GPS Altitude", func() {
fullResponse = `[{"geo:lat": "43.467157", "geo:long": "11.885395", "GPS:GPS Altitude": "227.4 metres"}]`
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Location).ToNot(BeNil())
Expect(doc.Location.Altitude).To(Equal(libregraph.PtrFloat64(227.4)))
})
It("adds image content", func() {
fullResponse = `[
{
@@ -321,36 +278,6 @@ var _ = Describe("Tika", func() {
Expect(doc.Content).To(Equal("body test stop words!!!"))
})
Context("with tika 4.x", func() {
BeforeEach(func() {
tika4 = true
version = "Apache Tika 4.2.0"
})
It("adds content", func() {
body = "any body"
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Content).To(Equal(body))
})
It("removes stop words", func() {
body = "body to test stop words!!! against almost everyone"
language = "en"
doc, err := tika.Extract(context.TODO(), &provider.ResourceInfo{
Type: provider.ResourceType_RESOURCE_TYPE_FILE,
Size: 1,
})
Expect(err).ToNot(HaveOccurred())
Expect(doc.Content).To(Equal("body test stop words!!!"))
})
})
It("keeps stop words", func() {
body = "body to test stop words!!! against almost everyone"
language = "en"
@@ -1,9 +0,0 @@
package search
import "time"
// SetExtractionRetryDelay shortens the delay between extraction retries for a
// test.
func (s *Service) SetExtractionRetryDelay(d time.Duration) {
s.extractionRetryDelay = d
}
+9 -25
View File
@@ -23,17 +23,6 @@ import (
var scopeRegex = regexp.MustCompile(`scope:\s*([^" "\n\r]*)`)
var vaultRegex = regexp.MustCompile(`vault:\s*(\S+)`)
// errResourceNotFound is returned by statResource when Stat answers
// CODE_NOT_FOUND: the resource was deleted or moved since it was listed. The
// gateway also answers NOT_FOUND when it cannot reach the storage provider, so
// a run of them can mean an outage (see IndexSpace).
var errResourceNotFound = errors.New("resource not found")
// errPathNotResolved is returned by ResolveReference when GetPath answers with
// a non-OK status. When the status is CODE_NOT_FOUND, the error also matches
// errResourceNotFound.
var errPathNotResolved = errors.New("could not resolve the resource's path")
// ResolveReference makes sure the path is relative to the space root
func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider.ResourceInfo, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.Reference, error) {
if ref.GetResourceId().GetOpaqueId() == ref.GetResourceId().GetSpaceId() {
@@ -48,16 +37,9 @@ func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider
gpRes, err := gatewayClient.GetPath(ctx, &provider.GetPathRequest{
ResourceId: ri.GetId(),
})
if err != nil {
if err != nil || gpRes.GetStatus().GetCode() != rpc.Code_CODE_OK {
return nil, err
}
if code := gpRes.GetStatus().GetCode(); code != rpc.Code_CODE_OK {
if code == rpc.Code_CODE_NOT_FOUND {
// Deleted since the Stat, like a Stat that answers NOT_FOUND.
return nil, fmt.Errorf("%w: %w: %s", errPathNotResolved, errResourceNotFound, gpRes.GetStatus().GetMessage())
}
return nil, fmt.Errorf("%w: %s %s", errPathNotResolved, code, gpRes.GetStatus().GetMessage())
}
return &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: ref.GetResourceId().GetStorageId(),
@@ -98,7 +80,7 @@ func getAuthContext(ctx context.Context, serviceAccountID string, gatewaySelecto
return utils.GetServiceUserContextWithContext(ctx, gatewayClient, serviceAccountID, secret)
}
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.StatResponse, error) {
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient], logger log.Logger) (*provider.StatResponse, error) {
gatewayClient, err := gatewaySelector.Next()
if err != nil {
return nil, err
@@ -106,17 +88,19 @@ func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector
res, err := gatewayClient.Stat(ctx, &provider.StatRequest{Ref: ref})
if err != nil {
logger.Error().Err(err).Msg("failed to stat the moved resource")
return nil, err
}
switch code := res.GetStatus().GetCode(); code {
switch res.GetStatus().GetCode() {
case rpc.Code_CODE_OK:
return res, nil
case rpc.Code_CODE_NOT_FOUND:
// Moved or deleted in the meantime, or a backend the gateway could
// not reach: the gateway answers NOT_FOUND for both.
return nil, errResourceNotFound
// Resource was moved or deleted in the meantime. ignore.
return nil, err
default:
return nil, fmt.Errorf("stat failed: %s %s", code, res.GetStatus().GetMessage())
err := errors.New("failed to stat the moved resource")
logger.Error().Interface("res", res).Msg(err.Error())
return nil, err
}
}
+27 -145
View File
@@ -24,7 +24,6 @@ import (
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/tags"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/rs/zerolog"
"golang.org/x/sync/errgroup"
"google.golang.org/protobuf/types/known/fieldmaskpb"
@@ -76,12 +75,6 @@ type Service struct {
serviceAccountID string
serviceAccountSecret string
// maxConsecutiveFailures aborts an IndexSpace walk after this many
// consecutive extraction failures. 0 disables the abort.
maxConsecutiveFailures int
// extractionRetryDelay is the pause between extraction retries in IndexSpace.
extractionRetryDelay time.Duration
}
var errSkipSpace error
@@ -96,13 +89,6 @@ func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng e
serviceAccountID: cfg.ServiceAccount.ServiceAccountID,
serviceAccountSecret: cfg.ServiceAccount.ServiceAccountSecret,
maxConsecutiveFailures: cfg.Extractor.MaxConsecutiveFailures,
extractionRetryDelay: _extractionRetryDelay,
}
if s.maxConsecutiveFailures == 0 {
s.logger.Warn().Msg("SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES is 0: a space reindex never aborts, even when the content extractor is down")
}
return s
@@ -469,15 +455,11 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
return res, nil
}
// Retry and outage constants for IndexSpace.
// Retry constants for IndexSpace extraction failure handling.
const (
_extractionRetries = 5 // max retry attempts per file
_extractionRetryDelay = 1 * time.Second // default delay between retries
// A walk in which at least _missingMinCount files were not found, and they
// are more than half of the files that needed work, fails at the end: the
// gateway answers NOT_FOUND when it cannot reach the storage provider, and
// that must not report the space as indexed.
_missingMinCount = 5
_extractionRetryDelay = 1 * time.Second // delay between retries
_consecutiveAbort = 5 // abort walk after this many consecutive file failures
)
// IndexSpace (re)indexes all resources of a given space.
@@ -498,14 +480,7 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
}
rootID.OpaqueId = rootID.SpaceId
// failures counts extraction failures in a row. A file that was indexed or
// was already indexed and unchanged resets it; a file that is not found
// (deleted since it was listed) neither counts nor resets it.
var (
failures int
indexedCount, unchangedCount, failedCount int
missingCount int
)
failures := 0
w := walker.NewWalker(s.gatewaySelector)
err = w.Walk(ownerCtx, &rootID, func(wd string, info *provider.ResourceInfo, err error) error {
@@ -518,22 +493,17 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
return nil
}
// A cancelled or timed-out walk must stop with an error, not carry on
// with failing lookups.
if err := ownerCtx.Err(); err != nil {
return fmt.Errorf("index walk stopped: %w", err)
}
relPath := utils.MakeRelativePath(filepath.Join(wd, info.Path))
if slices.Contains(_skipPathDirs, relPath) {
s.logger.Info().Str("path", relPath).Msg("skipping directory from being indexed")
return filepath.SkipDir
}
if slices.Contains(_skipPathNames, relPath) {
return nil // the space root itself is never indexed
}
s.logger.Debug().Str("path", relPath).Msg("Walking tree")
ref := &provider.Reference{
Path: relPath,
ResourceId: &rootID,
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
// Skip nodes still in postprocessing — their blob isn't in the
// blobstore yet. Their own UploadReady will re-trigger IndexSpace.
if utils.ReadPlainFromOpaque(info.Opaque, "status") == "processing" {
@@ -553,72 +523,32 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
// With O(1) DocID lookups the cost is negligible.
return nil
}
s.logger.Debug().Str("path", relPath).Msg("element hasn't changed. Skipping.")
unchangedCount++
failures = 0
s.logger.Debug().Str("path", ref.Path).Msg("element hasn't changed. Skipping.")
return nil
}
}
// Resolve the node by its path. A stale node fails a Stat by path but
// the ID the walker listed still finds it. So retry by ID only after
// a not-found: a healthy file costs no extra GetPath call.
ref := &provider.Reference{Path: relPath, ResourceId: &rootID}
err = s.upsertItem(ownerCtx, ref, _extractionRetries)
if errors.Is(err, errResourceNotFound) && info.GetId() != nil {
s.logger.Debug().Str("path", relPath).Msg("resource not found by path, retrying by ID")
err = s.upsertItem(ownerCtx, &provider.Reference{ResourceId: info.GetId()}, _extractionRetries)
}
if err != nil {
if errors.Is(err, errResourceNotFound) {
missingCount++
s.logger.Debug().Err(err).Str("path", relPath).Msg("skipping resource that no longer exists")
return nil
}
if err := s.upsertItem(ownerCtx, ref, _extractionRetries); err != nil {
failures++
failedCount++
s.logger.Warn().Err(err).
Int("failures", failures).
Str("path", relPath).
Str("path", ref.Path).
Msg("extraction failed after retries")
if s.maxConsecutiveFailures > 0 && failures >= s.maxConsecutiveFailures {
if failures >= _consecutiveAbort {
return fmt.Errorf("aborting index walk: %d consecutive extraction failures, last error: %w", failures, err)
}
return nil
}
indexedCount++
failures = 0
return nil
})
// The context check comes first: a walk cut short reports that, whatever
// the last file's error was.
if ctxErr := ownerCtx.Err(); ctxErr != nil {
return fmt.Errorf("index walk stopped: %w", ctxErr)
}
level := zerolog.InfoLevel
if failedCount > 0 || missingCount > 0 {
level = zerolog.WarnLevel
}
s.logger.WithLevel(level).Str("space", spaceID.GetOpaqueId()).
Int("indexed", indexedCount).
Int("unchanged", unchangedCount).
Int("failed", failedCount).
Int("not_found", missingCount).
Msg("index walk finished")
if err != nil {
return err
}
if attempted := indexedCount + failedCount + missingCount; missingCount >= _missingMinCount && missingCount*2 > attempted {
return fmt.Errorf("index walk incomplete: %d of %d files were not found, which suggests the storage provider was unreachable", missingCount, attempted)
}
logDocCount(s.engine, s.logger)
return nil
@@ -634,12 +564,7 @@ func (s *Service) TrashItem(_ context.Context, rID *provider.ResourceId) {
// UpsertItem indexes or stores Resource data fields.
func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
err := s.upsertItem(ctx, ref, 0)
switch {
case err == nil:
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Msg("resource to upsert no longer exists")
default:
if err := s.upsertItem(ctx, ref, 0); err != nil {
s.logger.Error().Err(err).Msg("failed to upsert resource")
}
}
@@ -647,9 +572,9 @@ func (s *Service) UpsertItem(ctx context.Context, ref *provider.Reference) {
// upsertItem is the core extraction-and-index method. When retries > 0,
// a failed extraction is retried up to that many times with a fixed delay.
func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retries int) error {
ctx2, stat, path, err := s.resolve(ctx, ref)
if err != nil {
return fmt.Errorf("could not resolve resource info for %s: %w", refString(ref), err)
ctx2, stat, path := s.resInfo(ctx, ref)
if ctx2 == nil || stat == nil || path == "" {
return fmt.Errorf("could not resolve resource info for %s", ref.GetPath())
}
if slices.Contains(_skipPathNames, path) || slices.Contains(_skipPathDirs, path) {
@@ -667,6 +592,7 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
resourceID := storagespace.FormatResourceID(stat.Info.Id)
var doc content.Document
var err error
for attempt := range retries + 1 {
doc, err = s.extractor.Extract(ctx2, stat.Info)
if err == nil {
@@ -675,19 +601,13 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
if attempt < retries {
s.logger.Debug().Err(err).
Int("attempt", attempt+1).
Str("path", path).
Str("path", ref.Path).
Msg("extraction attempt failed, retrying")
t := time.NewTimer(s.extractionRetryDelay)
select {
case <-ctx.Done():
t.Stop()
return fmt.Errorf("extraction for %s stopped: %w", path, ctx.Err())
case <-t.C:
}
time.Sleep(_extractionRetryDelay)
}
}
if err != nil {
return fmt.Errorf("extraction failed for %s: %w", path, err)
return fmt.Errorf("extraction failed for %s: %w", ref.Path, err)
}
r := engine.Resource{
@@ -709,7 +629,7 @@ func (s *Service) upsertItem(ctx context.Context, ref *provider.Reference, retri
}
if err = s.engine.Upsert(r.ID, r); err != nil {
return fmt.Errorf("index upsert for %s: %w", path, err)
return fmt.Errorf("index upsert for %s: %w", ref.Path, err)
}
logDocCount(s.engine, s.logger)
@@ -875,59 +795,21 @@ func (s *Service) MoveItem(ctx context.Context, ref *provider.Reference) {
}
}
// resInfo is resolve for the event handlers (UpdateTags, RestoreItem, MoveItem).
// It logs a failure once and returns nils, except when only the path could not
// be resolved: then it still returns the Stat result with an empty path, as
// before, so UpdateTags (which needs only the Stat result) still works.
func (s *Service) resInfo(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string) {
ctx2, stat, path, err := s.resolve(ctx, ref)
switch {
case err == nil:
return ctx2, stat, path
case errors.Is(err, errPathNotResolved):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("could not resolve the resource's path")
return ctx2, stat, ""
case errors.Is(err, errResourceNotFound):
s.logger.Debug().Err(err).Str("ref", refString(ref)).Msg("resource no longer exists")
default:
s.logger.Warn().Err(err).Str("ref", refString(ref)).Msg("could not resolve resource info")
}
return nil, nil, ""
}
// resolve returns the auth context, Stat response and space-relative path of
// ref. Stat CODE_NOT_FOUND is errResourceNotFound and a non-OK GetPath is
// errPathNotResolved (with the Stat result still returned); every other
// failure (auth, gateway, transport, deadline) is returned as its own error.
func (s *Service) resolve(ctx context.Context, ref *provider.Reference) (context.Context, *provider.StatResponse, string, error) {
ownerCtx, err := getAuthContext(ctx, s.serviceAccountID, s.gatewaySelector, s.serviceAccountSecret, s.logger)
if err != nil {
return nil, nil, "", fmt.Errorf("auth context: %w", err)
return nil, nil, ""
}
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector)
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector, s.logger)
if err != nil {
return nil, nil, "", err
return nil, nil, ""
}
r, err := ResolveReference(ownerCtx, ref, statRes.GetInfo(), s.gatewaySelector)
if err != nil {
if errors.Is(err, errPathNotResolved) {
return ownerCtx, statRes, "", err
}
return nil, nil, "", fmt.Errorf("get path: %w", err)
}
if r.GetPath() == "" {
return ownerCtx, statRes, "", errPathNotResolved
return nil, nil, ""
}
return ownerCtx, statRes, r.GetPath(), nil
}
// refString describes ref for logs and errors: its path, or its resource ID.
func refString(ref *provider.Reference) string {
if p := ref.GetPath(); p != "" {
return p
}
return storagespace.FormatResourceID(ref.GetResourceId())
return ownerCtx, statRes, r.GetPath()
}
+5 -321
View File
@@ -9,7 +9,6 @@ import (
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"
collaborationv1beta1 "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typesv1beta1 "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
@@ -27,7 +26,6 @@ import (
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
@@ -173,7 +171,7 @@ var _ = Describe("Searchprovider", func() {
indexClient.On("Lookup", mock.Anything).Return(nil, engine.ErrResourceNotFound)
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(sreq *sprovider.StatRequest) bool {
return sreq.Ref.ResourceId.StorageId == "storageid" &&
(sreq.Ref.ResourceId.OpaqueId == "spaceid" || sreq.Ref.ResourceId.OpaqueId == ri.Id.OpaqueId) &&
sreq.Ref.ResourceId.OpaqueId == "spaceid" &&
sreq.Ref.ResourceId.SpaceId == "spaceid"
})).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
@@ -181,7 +179,6 @@ var _ = Describe("Searchprovider", func() {
}, nil)
err := s.IndexSpace(context.Background(), &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"})
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", 1)
})
It("walks the space skipping .space directory", func() {
@@ -259,21 +256,11 @@ var _ = Describe("Searchprovider", func() {
}
}
// Build ID-to-fileInfo and ID-to-path maps for O(1) Stat and GetPath dispatch.
fileInfoByID := make(map[string]*sprovider.ResourceInfo, numDirs)
filePathByID := make(map[string]string, numDirs)
// Build path-to-fileInfo map for O(1) Stat dispatch.
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numDirs)
for dirID, fi := range fileInfoByDir {
fileInfoByID[fi.Id.OpaqueId] = fi
filePathByID[fi.Id.OpaqueId] = "/" + dirID + "/" + fi.Path
fileInfoByPath["./"+dirID+"/"+fi.Path] = fi
}
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return fileInfoByID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: filePathByID[req.GetResourceId().GetOpaqueId()]}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
// Single Stat mock dispatching via map — avoids 10k separate matchers.
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
@@ -284,7 +271,7 @@ var _ = Describe("Searchprovider", func() {
Info: rootInfo,
}
}
if fi, ok := fileInfoByID[sreq.Ref.GetResourceId().GetOpaqueId()]; ok {
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: fi,
@@ -395,280 +382,6 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("IndexSpace abort threshold", func() {
// A root container listing numFiles files. Stat by ID answers per the
// missing/statBroken sets, Stat by path per staleByPath; Lookup finds only
// the files in indexed, so every other file is attempted.
const numFiles = 6
var (
rootInfo *sprovider.ResourceInfo
fileInfos []*sprovider.ResourceInfo
missing map[string]bool // Stat answers NOT_FOUND
statBroken map[string]bool // Stat answers with an internal error
staleByPath map[string]bool // Stat by path answers NOT_FOUND, Stat by ID works
pathMissing map[string]bool // GetPath answers NOT_FOUND
pathBroken map[string]bool // GetPath answers with an internal error
indexed map[string]bool // already indexed and unchanged
newService = func(maxConsecutiveFailures int) *search.Service {
cfg := &config.Config{}
cfg.Extractor.MaxConsecutiveFailures = maxConsecutiveFailures
s := search.NewService(gatewaySelector, indexClient, extractor, logger, cfg)
s.SetExtractionRetryDelay(time.Millisecond)
return s
}
spaceID = &sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}
)
BeforeEach(func() {
missing = map[string]bool{}
statBroken = map[string]bool{}
staleByPath = map[string]bool{}
pathMissing = map[string]bool{}
pathBroken = map[string]bool{}
indexed = map[string]bool{}
gatewayClient.On("GetUserByClaim", mock.Anything, mock.Anything).Return(&userv1beta1.GetUserByClaimResponse{
Status: status.NewOK(context.Background()),
User: user,
}, nil)
rootInfo = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_CONTAINER,
Path: ".",
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
fileInfos = make([]*sprovider.ResourceInfo, numFiles)
byID := map[string]*sprovider.ResourceInfo{}
for i := range fileInfos {
fileInfos[i] = &sprovider.ResourceInfo{
Id: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: fmt.Sprintf("file-%d", i)},
ParentId: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
Path: fmt.Sprintf("file-%d.pdf", i),
Size: 1024,
Mtime: &typesv1beta1.Timestamp{Seconds: 5000},
}
byID[fileInfos[i].Id.OpaqueId] = fileInfos[i]
}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(
func(_ context.Context, sreq *sprovider.StatRequest, _ ...grpc.CallOption) *sprovider.StatResponse {
id := sreq.GetRef().GetResourceId().GetOpaqueId()
if p := sreq.GetRef().GetPath(); p != "" && p != "." {
// By path, relative to the space root.
for _, fi := range fileInfos {
if "./"+fi.Path == p && !staleByPath[fi.Id.OpaqueId] {
id = fi.Id.OpaqueId
break
}
id = ""
}
}
switch {
case id == "spaceid":
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: rootInfo}
case statBroken[id]:
return &sprovider.StatResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
case missing[id] || byID[id] == nil:
return &sprovider.StatResponse{Status: status.NewNotFound(context.Background(), id)}
}
return &sprovider.StatResponse{Status: status.NewOK(context.Background()), Info: byID[id]}
},
func(_ context.Context, _ *sprovider.StatRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return byID[req.GetResourceId().GetOpaqueId()] != nil
})).Return(
func(_ context.Context, req *sprovider.GetPathRequest, _ ...grpc.CallOption) *sprovider.GetPathResponse {
id := req.GetResourceId().GetOpaqueId()
switch {
case pathMissing[id]:
return &sprovider.GetPathResponse{Status: status.NewNotFound(context.Background(), id)}
case pathBroken[id]:
return &sprovider.GetPathResponse{Status: status.NewInternal(context.Background(), "storage unavailable")}
}
return &sprovider.GetPathResponse{Status: status.NewOK(context.Background()), Path: "/" + byID[id].Path}
},
func(_ context.Context, _ *sprovider.GetPathRequest, _ ...grpc.CallOption) error { return nil },
)
gatewayClient.On("ListContainer", mock.Anything, mock.Anything).Return(&sprovider.ListContainerResponse{
Status: status.NewOK(context.Background()),
Infos: fileInfos,
}, nil)
indexClient.On("Lookup", mock.Anything).Return(
func(id string) *engine.Resource {
if indexed[id] {
return &engine.Resource{ID: id, Extracted: true, Document: content.Document{Mtime: time.Unix(6000, 0).UTC().Format(time.RFC3339Nano)}}
}
return nil
},
func(id string) error {
if indexed[id] {
return nil
}
return engine.ErrResourceNotFound
},
)
indexClient.On("Upsert", mock.Anything, mock.Anything).Return(nil)
})
It("does not count a file that no longer exists towards the abort threshold", func() {
missing["file-0"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a file deleted since it was listed is skipped, never counted")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("keeps the failure count across a file that no longer exists", func() {
// Only file-0 and file-2 fail extraction. file-1 is gone between them.
// It neither counts nor resets the counter, so a threshold of 2
// aborts at file-2, before the healthy file-3 could reset it.
missing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.MatchedBy(func(ri *sprovider.ResourceInfo) bool {
return ri.GetId().GetOpaqueId() == "file-0" || ri.GetId().GetOpaqueId() == "file-2"
}), mock.Anything).Return(content.Document{}, errors.New("extractor down"))
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
})
It("fails the walk when most files are not found, as in a storage provider outage", func() {
// The gateway answers NOT_FOUND when it cannot reach the provider.
for _, fi := range fileInfos {
missing[fi.Id.OpaqueId] = true
}
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "an outage must not report the space as indexed")
Expect(err.Error()).To(ContainSubstring(fmt.Sprintf("index walk incomplete: %d of %d files were not found", numFiles, numFiles)))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("indexes a stale node that Stat cannot find by its path but can by its ID", func() {
staleByPath["file-1"] = true
var extracted []string
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
extracted = append(extracted, args.Get(1).(*sprovider.ResourceInfo).GetId().GetOpaqueId())
}).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
Expect(extracted).To(ConsistOf("file-0", "file-1", "file-2", "file-3", "file-4", "file-5"))
gatewayClient.AssertNumberOfCalls(GinkgoT(), "GetPath", 1) // only the stale node needs the ID fallback
})
It("does not count a file that is gone between the Stat and the GetPath", func() {
staleByPath["file-1"] = true // forces the lookup by ID, which calls GetPath
pathMissing["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "a vanished file is not an extraction failure")
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles-1)
})
It("counts a GetPath failure other than not-found", func() {
staleByPath["file-1"] = true
pathBroken["file-1"] = true
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(1).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage failure must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 1 consecutive extraction failures"))
})
It("resolves healthy files by path, without a GetPath call", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, nil)
err := newService(5).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred())
indexClient.AssertNumberOfCalls(GinkgoT(), "Upsert", numFiles)
gatewayClient.AssertNotCalled(GinkgoT(), "GetPath", mock.Anything, mock.Anything)
})
It("aborts after the configured number of consecutive extraction failures", func() {
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("extractor down"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
indexClient.AssertNotCalled(GinkgoT(), "Upsert", mock.Anything, mock.Anything)
})
It("never aborts when the threshold is 0", func() {
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
}).Return(content.Document{}, errors.New("extractor down"))
err := newService(0).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "with the abort disabled the walk finishes despite failures")
Expect(int(extractCalls.Load())).To(Equal(numFiles*6), "every file was attempted, each with all retries")
})
It("counts a Stat failure other than not-found towards the abort threshold", func() {
for _, fi := range fileInfos {
statBroken[fi.Id.OpaqueId] = true
}
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).Should(HaveOccurred(), "a storage or auth error must not look like a deleted file")
Expect(err.Error()).To(ContainSubstring("aborting index walk: 2 consecutive extraction failures"))
extractor.AssertNotCalled(GinkgoT(), "Extract", mock.Anything, mock.Anything, mock.Anything)
})
It("stops with an error when the walk's context ends, instead of skipping the rest", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel() // e.g. the index command's request timeout fires during the walk
}).Return(content.Document{}, nil)
err := newService(0).IndexSpace(ctx, spaceID)
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1), "no file after the cancellation was attempted")
})
It("stops retrying a failed extraction as soon as the context ends", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var extractCalls atomic.Int32
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Run(func(_ mock.Arguments) {
extractCalls.Add(1)
cancel()
}).Return(content.Document{}, errors.New("extractor down"))
s := newService(0)
s.SetExtractionRetryDelay(time.Hour)
done := make(chan error, 1)
go func() { done <- s.IndexSpace(ctx, spaceID) }()
var err error
Eventually(done, 5*time.Second).Should(Receive(&err), "the retry wait must end with the context, not after an hour")
Expect(err).Should(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("index walk stopped"))
Expect(int(extractCalls.Load())).To(Equal(1))
})
It("resets the counter on an already indexed, unchanged file", func() {
// Failing files 0, 2 and 4 are each followed by an indexed one.
for i := 1; i < numFiles; i += 2 {
indexed[storagespace.FormatResourceID(fileInfos[i].Id)] = true
}
extractor.On("Extract", mock.Anything, mock.Anything, mock.Anything).Return(content.Document{}, errors.New("cannot extract"))
err := newService(2).IndexSpace(context.Background(), spaceID)
Expect(err).ShouldNot(HaveOccurred(), "failures separated by a healthy file are not consecutive")
})
})
Describe("UpdateTags", func() {
BeforeEach(func() {
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
@@ -717,35 +430,6 @@ var _ = Describe("Searchprovider", func() {
})
})
Describe("UpdateTags when GetPath fails", func() {
for name, getPathStatus := range map[string]func() *rpcv1beta1.Status{
"with an internal error": func() *rpcv1beta1.Status { return status.NewInternal(context.Background(), "no path") },
"with not found": func() *rpcv1beta1.Status { return status.NewNotFound(context.Background(), "no path") },
} {
It("still updates the tags from the Stat result, GetPath answering "+name, func() {
noPathID := &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "nopath"}
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: &sprovider.ResourceInfo{
Id: noPathID,
Type: sprovider.ResourceType_RESOURCE_TYPE_FILE,
ArbitraryMetadata: &sprovider.ArbitraryMetadata{
Metadata: map[string]string{"tags": "important"},
},
},
}, nil)
gatewayClient.On("GetPath", mock.Anything, mock.MatchedBy(func(req *sprovider.GetPathRequest) bool {
return req.GetResourceId().GetOpaqueId() == "nopath"
})).Return(&sprovider.GetPathResponse{Status: getPathStatus()}, nil)
indexClient.On("Update", "storageid$spaceid!nopath", mock.Anything).Return(nil)
s.UpdateTags(context.Background(), &sprovider.Reference{ResourceId: noPathID})
indexClient.AssertCalled(GinkgoT(), "Update", "storageid$spaceid!nopath", mock.Anything)
})
}
})
Describe("Search", func() {
It("fails when an empty query is given", func() {
res, err := s.Search(ctx, &searchsvc.SearchRequest{
+41
View File
@@ -21,6 +21,7 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/l10n"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/roles"
"github.com/owncloud/ocis/v2/ocis-pkg/vault"
ehmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/eventhistory/v0"
ehsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
@@ -207,6 +208,9 @@ func (ul *UserlogService) processEvent(event events.Event) {
// II) filter users who want to receive the event
users = ul.filter.execute(ctx, event, executant, users)
if isVaultEvent(event) {
users = ul.filterVaultUsers(ctx, gwc, users)
}
// III) store the eventID for each user
for _, id := range users {
@@ -224,6 +228,43 @@ func (ul *UserlogService) processEvent(event events.Event) {
}
}
// isVaultEvent reports whether the event is about a share or a space membership in the vault.
func isVaultEvent(event events.Event) bool {
switch e := event.Event.(type) {
case events.ShareCreated:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.ShareRemoved:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.ShareExpired:
return vault.IsVaultStorage(e.ItemID.GetStorageId())
case events.SpaceShared:
return vault.IsVaultSpace(e.ID.GetOpaqueId())
case events.SpaceUnshared:
return vault.IsVaultSpace(e.ID.GetOpaqueId())
case events.SpaceMembershipExpired:
return vault.IsVaultSpace(e.SpaceID.GetOpaqueId())
default:
return false
}
}
// filterVaultUsers keeps only the users who hold the VaultMode permission.
func (ul *UserlogService) filterVaultUsers(ctx context.Context, gwc gateway.GatewayAPIClient, users []string) []string {
ids := make([]*user.UserId, 0, len(users))
for _, u := range users {
ids = append(ids, &user.UserId{OpaqueId: u})
}
allowed := vault.FilterVaultModeUsers(ctx, gwc, ids, func(id *user.UserId, err error) {
ul.log.Error().Err(err).Str("userId", id.GetOpaqueId()).Msg("could not check the vault permission, user skipped")
})
filtered := make([]string, 0, len(allowed))
for _, id := range allowed {
filtered = append(filtered, id.GetOpaqueId())
}
return filtered
}
// GetEvents allows retrieving events from the eventhistory by userid
func (ul *UserlogService) GetEvents(ctx context.Context, userid string) ([]*ehmsg.Event, error) {
ctx, span := ul.tracer.Start(ctx, "GetEvents")
+182
View File
@@ -0,0 +1,182 @@
package service_test
import (
"context"
"encoding/json"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
group "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/go-chi/chi/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/store"
"github.com/owncloud/reva/v2/pkg/utils"
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
"github.com/stretchr/testify/mock"
"go-micro.dev/v4/client"
microstore "go-micro.dev/v4/store"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
"github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0/mocks"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/userlog/pkg/config"
"github.com/owncloud/ocis/v2/services/userlog/pkg/service"
)
var _ = Describe("UserlogService vault events", func() {
const (
member = "member"
outsider = "outsider"
)
var (
bus testBus
sto microstore.Store
gatewayClient *cs3mocks.GatewayAPIClient
checkedUsers chan string
vaultResourceID = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: "spaceid",
OpaqueId: "itemid",
}
regularResourceID = &provider.ResourceId{
StorageId: "storageid",
SpaceId: "spaceid",
OpaqueId: "itemid",
}
vaultSpaceID = &provider.StorageSpaceId{
OpaqueId: storagespace.FormatResourceID(&provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: "vaultspaceid",
OpaqueId: "vaultspaceid",
}),
}
vaultGroup = &group.GroupId{OpaqueId: "vaultgroup"}
)
BeforeEach(func() {
sto = store.Create()
bus = testBus(make(chan events.Event))
checkedUsers = make(chan string, 10)
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
gatewayClient = &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}}, nil)
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(&group.GetGroupResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Group: &group.Group{Members: []*user.UserId{{OpaqueId: member}, {OpaqueId: outsider}}},
}, nil)
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(func(_ context.Context, r *permissions.CheckPermissionRequest, _ ...grpc.CallOption) (*permissions.CheckPermissionResponse, error) {
id := r.GetSubjectRef().GetUserId().GetOpaqueId()
checkedUsers <- id
code := rpc.Code_CODE_PERMISSION_DENIED
if id == member {
code = rpc.Code_CODE_OK
}
return &permissions.CheckPermissionResponse{Status: &rpc.Status{Code: code}}, nil
})
vc := &settingssvc.MockValueService{}
vc.GetValueByUniqueIdentifiersFunc = func(ctx context.Context, req *settingssvc.GetValueByUniqueIdentifiersRequest, opts ...client.CallOption) (*settingssvc.GetValueResponse, error) {
return &settingssvc.GetValueResponse{
Value: &settingsmsg.ValueWithIdentifier{
Value: &settingsmsg.Value{
Value: &settingsmsg.Value_CollectionValue{
CollectionValue: &settingsmsg.CollectionValue{
Values: []*settingsmsg.CollectionOption{
{
Key: "in-app",
Option: &settingsmsg.CollectionOption_BoolValue{BoolValue: true},
},
},
},
},
},
},
}, nil
}
_, err := service.NewUserlogService(
service.Config(&config.Config{MaxConcurrency: 5, DisableSSE: true}),
service.Stream(bus),
service.Store(sto),
service.Logger(log.NewLogger()),
service.Mux(chi.NewMux()),
service.GatewaySelector(gatewaySelector),
service.HistoryClient(&mocks.EventHistoryService{}),
service.ValueClient(vc),
service.RegisteredEvents([]events.Unmarshaller{
events.ShareCreated{},
events.SpaceShared{},
}),
service.TraceProvider(trace.NewNoopTracerProvider()),
)
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
close(bus)
})
storedEvents := func(userID string) []string {
recs, err := sto.Read(userID)
if err != nil {
return nil
}
var ids []string
Expect(json.Unmarshal(recs[0].Value, &ids)).To(Succeed())
return ids
}
DescribeTable("stores the event only for group members with the vault mode permission",
func(ev interface{}) {
id := bus.publish(ev)
Eventually(func() []string { return storedEvents(member) }, time.Second).Should(ConsistOf(id))
Consistently(func() []string { return storedEvents(outsider) }, 200*time.Millisecond).Should(BeEmpty())
},
Entry("Share Created", events.ShareCreated{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ItemID: vaultResourceID,
}),
Entry("Added to Space", events.SpaceShared{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ID: vaultSpaceID,
}),
)
It("does not check the vault mode permission for a regular resource", func() {
id := bus.publish(events.ShareCreated{
Executant: &user.UserId{OpaqueId: "sharer"},
GranteeGroupID: vaultGroup,
ItemID: regularResourceID,
})
Eventually(func() []string { return storedEvents(member) }, time.Second).Should(ConsistOf(id))
Eventually(func() []string { return storedEvents(outsider) }, time.Second).Should(ConsistOf(id))
Expect(checkedUsers).To(BeEmpty())
})
})
+1
View File
@@ -503,6 +503,7 @@ default:
- SpacesContext:
- SharingNgContext:
- OCSContext:
- NotificationContext:
cliCommands:
paths:
+101 -23
View File
@@ -1191,11 +1191,12 @@ Feature: vault
| vaultFile.txt | File Editor |
Scenario: try to send share invitation for a resource in vault to a group
Scenario: send share invitation for a resource in vault to a group
Given these groups have been created:
| groupname |
| vault-group |
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 been set up in oCIS
And user "Brian" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
@@ -1207,28 +1208,105 @@ Feature: vault
| shareType | group |
| permissionsRole | Viewer |
| storage | vault |
Then the HTTP status code should be "403"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["error"],
"properties": {
"error": {
"type": "object",
"required": ["code", "message"],
"properties": {
"code": {
"const": "accessDenied"
},
"message": {
"const": "grantee is not allowed to access vault resources"
}
}
}
}
}
"""
Then the HTTP status code should be "200"
And user "Brian" should have a share in vault "vaultFile.txt" synced
And user "Brian" should have the following resource shares:
| resource | permissionsRole | sharer | space | storage |
| vaultFile.txt | Viewer | Alice | Personal | vault |
Scenario Outline: only group members with the vault mode permission get a notification and access for a vault share
Given these users have been created with default attributes:
| username |
| Brian |
| Carol |
And the administrator has assigned the role "<vault-role>" to user "Brian" using the Graph API
And the administrator has assigned the role "<no-vault-role>" to user "Carol" using the Graph API
And these groups have been created:
| groupname |
| vault-group |
And user "Brian" has been added to group "vault-group"
And user "Carol" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
And user "Brian" has been set up in oCIS
And user "Carol" has been set up in oCIS
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "vaultFile.txt" in vault
And we save it into "FILEID"
When user "Alice" sends the following resource share invitation using the Graph API:
| resource | vaultFile.txt |
| space | Personal |
| sharee | vault-group |
| shareType | group |
| permissionsRole | Viewer |
| storage | vault |
Then the HTTP status code should be "200"
And user "Brian" should have a share in vault "vaultFile.txt" synced
# Check Brian first. The userlog service filters all group members before it stores the
# notification for one of them, so the check for Carol cannot run too early.
And user "Brian" should get a notification with subject "Resource shared" and message:
| message |
| Alice Hansen shared vaultFile.txt with you |
And user "Carol" should not have any notification
When user "Brian" sends HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "200"
And the downloaded content should be "some content"
When user "Carol" tries to send HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "403" or "404"
And for user "Carol" the space "Shares" should not contain these entries:
| vaultFile.txt |
Examples:
| vault-role | no-vault-role |
| Space Admin | User Light |
| Admin | User |
Scenario Outline: only group members with the vault mode permission get a notification and access for a vault space membership
Given these users have been created with default attributes:
| username |
| Brian |
| Carol |
And the administrator has assigned the role "<vault-role>" to user "Brian" using the Graph API
And the administrator has assigned the role "<no-vault-role>" to user "Carol" using the Graph API
And these groups have been created:
| groupname |
| vault-group |
And user "Brian" has been added to group "vault-group"
And user "Carol" has been added to group "vault-group"
And user "Alice" has been set up in oCIS
And user "Brian" has been set up in oCIS
And user "Carol" has been set up in oCIS
And user "Alice" has created a space "new-space" in vault with the default quota using the Graph API
And user "Alice" has uploaded a file inside space "new-space" with content "some content" to "vaultFile.txt" in vault
And we save it into "FILEID"
When user "Alice" sends the following space share invitation using root endpoint of the Graph API:
| space | new-space |
| sharee | vault-group |
| shareType | group |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "200"
# Check Brian first. The userlog service filters all group members before it stores the
# notification for one of them, so the check for Carol cannot run too early.
And user "Brian" should get a notification with subject "Space shared" and message:
| message |
| Alice Hansen added you to Space new-space |
And user "Carol" should not have any notification
And for user "Brian" the space "new-space" in vault should contain these entries:
| vaultFile.txt |
When user "Brian" sends HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "200"
And the downloaded content should be "some content"
When user "Carol" tries to send HTTP method "GET" to URL "/dav/spaces/<<FILEID>>"
Then the HTTP status code should be "403" or "404"
When user "Carol" lists all available spaces via the Graph API
Then the HTTP status code should be "200"
And the json response should not contain a space with name "new-space"
Examples:
| permissions-role | vault-role | no-vault-role |
| Manager | Space Admin | User Light |
| Manager | Admin | User |
| Space Viewer | Space Admin | User Light |
| Space Editor | Admin | User |
Scenario Outline: server sets a default 30-day expiration when a user share is created without one
+2 -20
View File
@@ -135,32 +135,13 @@ def main() -> int:
subprocess.run(["pnpm", "exec", "playwright", "install", "--with-deps", "chromium"],
cwd=web_dir, check=True)
vault_storage_needed = (
os.environ.get("VAULT_STORAGE_NEEDED", "").lower() == "true"
or os.environ.get("VAULT_MODE", "").lower() == "true"
)
if os.environ.get("K8S", "").lower() == "true":
# oCIS is already running as a Helm-deployed k8s cluster (see
# .github/workflows/k8s.yml) -- unlike the flow below, there's no local
# binary to build, init, or start. Just confirm it's up and point
# Playwright straight at it.
ocis_url = os.environ["TEST_SERVER_URL"]
if vault_storage_needed:
wait_for(
lambda: subprocess.run(
["curl", "-sf", "http://localhost:19205/readyz"], capture_output=True
).returncode == 0,
120,
"ocis proxy",
)
else:
keycloak_enabled = os.environ.get("KEYCLOAK", "").lower() == "true"
wait_for(
lambda: ocis_healthy(ocis_url, use_basic_auth=not keycloak_enabled),
120,
"ocis",
)
wait_for(lambda: ocis_healthy(ocis_url), 120, "ocis")
print("ocis ready.")
playwright_env = {
@@ -191,6 +172,7 @@ def main() -> int:
oidc_iframe_needed = os.environ.get("OIDC_IFRAME_NEEDED", "").lower() == "true"
collaboration_needed = os.environ.get("COLLABORATION_NEEDED", "").lower() == "true"
federated_needed = os.environ.get("FEDERATED_NEEDED", "").lower() == "true"
vault_storage_needed = os.environ.get("VAULT_STORAGE_NEEDED", "").lower() == "true"
# MFA mode runs ocis behind keycloak with TOTP enforced
keycloak_needed = keycloak_needed or mfa_needed or vault_storage_needed
+1 -1
View File
@@ -485,7 +485,7 @@ def main() -> int:
if cfg["tikaNeeded"]:
print("Starting tika...")
run(["docker", "run", "-d", "--name", "tika", "--network", "host",
os.environ.get("TIKA_IMAGE") or "apache/tika:3.2.2.0-full"])
"apache/tika:3.2.2.0-full"])
wait_for(tika_healthy, 120, "tika")
print("tika ready.")
@@ -63,6 +63,10 @@ type config struct {
UserGroupsCacheSize int `mapstructure:"usergroups_cache_size"`
ScopeExpansionCacheSize int `mapstructure:"scope_expansion_cache_size"`
MFAEnabled bool `mapstructure:"mfa_enabled"`
// VaultModeRequired denies access to users who do not hold the VaultMode permission.
VaultModeRequired bool `mapstructure:"vault_mode_required"`
VaultModeCacheSize int `mapstructure:"vault_mode_cache_size"`
VaultModeCacheSeconds int `mapstructure:"vault_mode_cache_seconds"`
}
func parseConfig(m map[string]interface{}) (*config, error) {
@@ -71,6 +75,13 @@ func parseConfig(m map[string]interface{}) (*config, error) {
err = errors.Wrap(err, "auth: error decoding conf")
return nil, err
}
if c.VaultModeCacheSize == 0 {
c.VaultModeCacheSize = 5000
}
if c.VaultModeCacheSeconds == 0 {
c.VaultModeCacheSeconds = 30
}
initVaultModeCache(c.VaultModeCacheSize, time.Duration(c.VaultModeCacheSeconds)*time.Second)
return c, nil
}
@@ -163,6 +174,16 @@ func NewUnary(m map[string]interface{}, unprotected []string, tp trace.TracerPro
return mfaResponse(ctx, req, info)
}
}
if conf.VaultModeRequired && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
allowed, err := hasVaultMode(ctx, u, conf.GatewayAddr)
if err != nil {
log.Error().Err(err).Str("user_id", u.Id.OpaqueId).Msg("could not check the vault mode permission")
}
if !allowed {
log.Debug().Str("user_id", u.Id.OpaqueId).Msg("vault mode permission is required")
return denyResponse(ctx, req, info, vaultModeRequiredMsg)
}
}
span.SetAttributes(semconv.EnduserIDKey.String(u.Id.OpaqueId))
@@ -182,6 +203,7 @@ func NewStream(m map[string]interface{}, unprotected []string, tp trace.TracerPr
if conf.TokenManager == "" {
conf.TokenManager = "jwt"
}
conf.GatewayAddr = sharedconf.GetGatewaySVC(conf.GatewayAddr)
if conf.UserGroupsCacheSize == 0 {
conf.UserGroupsCacheSize = 10000
@@ -260,6 +282,16 @@ func NewStream(m map[string]interface{}, unprotected []string, tp trace.TracerPr
return status.Errorf(codes.PermissionDenied, "MFA required to access vault storage")
}
}
if conf.VaultModeRequired && u.Id.Type != userpb.UserType_USER_TYPE_SERVICE {
allowed, err := hasVaultMode(ctx, u, conf.GatewayAddr)
if err != nil {
log.Error().Err(err).Str("user_id", u.Id.OpaqueId).Msg("could not check the vault mode permission")
}
if !allowed {
log.Debug().Str("user_id", u.Id.OpaqueId).Msg("vault mode permission is required")
return status.Errorf(codes.PermissionDenied, vaultModeRequiredMsg)
}
}
wrapped := newWrappedServerStream(ctx, ss)
span.SetAttributes(semconv.EnduserIDKey.String(u.Id.OpaqueId))
+7 -3
View File
@@ -12,7 +12,11 @@ import (
)
func mfaResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (interface{}, error) {
const msg = "MFA required to access vault storage"
return denyResponse(ctx, req, info, "MFA required to access vault storage")
}
// denyResponse returns a PERMISSION_DENIED response of the type that matches the request.
func denyResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, msg string) (interface{}, error) {
switch req.(type) {
case *provider.StatRequest:
return &provider.StatResponse{Status: rstatus.NewPermissionDenied(ctx, nil, msg)}, nil
@@ -67,7 +71,7 @@ func mfaResponse(ctx context.Context, req interface{}, info *grpc.UnaryServerInf
case *provider.DeleteStorageSpaceRequest:
return &provider.DeleteStorageSpaceResponse{Status: rstatus.NewPermissionDenied(ctx, nil, msg)}, nil
default:
log.Debug().Str("method", info.FullMethod).Msg("mfa: blocking unknown request type")
return nil, grpcstatus.Errorf(codes.PermissionDenied, "mfa: %s: %T", msg, req)
log.Debug().Str("method", info.FullMethod).Msg("auth: blocking unknown request type")
return nil, grpcstatus.Errorf(codes.PermissionDenied, "auth: %s: %T", msg, req)
}
}
@@ -0,0 +1,75 @@
package auth
import (
"context"
"sync"
"time"
"github.com/bluele/gcache"
gatewayv1beta1 "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
permissions "github.com/cs3org/go-cs3apis/cs3/permissions/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/reva/v2/pkg/permission"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/pkg/errors"
)
const vaultModeRequiredMsg = "vault mode permission required to access vault storage"
var (
vaultModeCache gcache.Cache
vaultModeCacheTTL time.Duration
vaultModeCacheOnce sync.Once
// getGatewayClient is a variable, so that tests can replace the gateway client.
getGatewayClient = func(addr string) (gatewayv1beta1.GatewayAPIClient, error) {
return pool.GetGatewayServiceClient(addr)
}
)
// initVaultModeCache creates the cache for the VaultMode answers. Only the first call has an effect.
func initVaultModeCache(size int, ttl time.Duration) {
vaultModeCacheOnce.Do(func() {
vaultModeCache = gcache.New(size).LRU().Build()
vaultModeCacheTTL = ttl
})
}
// hasVaultMode reports whether the user holds the VaultMode permission.
// The vault storage provider uses it to deny access to users who cannot use vault mode,
// for example group members who received a vault share. A non-nil error means undetermined,
// so the caller must deny the request. Only definitive answers are cached.
func hasVaultMode(ctx context.Context, u *userpb.User, gatewayAddr string) (bool, error) {
id := u.GetId().GetOpaqueId()
if v, err := vaultModeCache.Get(id); err == nil {
return v.(bool), nil
}
client, err := getGatewayClient(gatewayAddr)
if err != nil {
return false, err
}
res, err := client.CheckPermission(ctx, &permissions.CheckPermissionRequest{
SubjectRef: &permissions.SubjectReference{
Spec: &permissions.SubjectReference_UserId{UserId: u.GetId()},
},
Permission: permission.VaultMode,
})
if err != nil {
return false, errors.Wrap(err, "auth: error calling CheckPermission")
}
var allowed bool
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
allowed = true
case rpc.Code_CODE_PERMISSION_DENIED:
allowed = false
default:
return false, errors.Errorf("auth: vault permission check returned status %q: %s", code, res.GetStatus().GetMessage())
}
_ = vaultModeCache.SetWithExpire(id, allowed, vaultModeCacheTTL)
return allowed, nil
}
@@ -78,6 +78,13 @@ func (s *svc) CreateShare(ctx context.Context, req *collaboration.CreateShareReq
// granteeMayAccessVault reports whether the grantee may be granted access to a vault resource.
// A non-nil error means undetermined, never denied, so callers must fail closed.
func (s *svc) granteeMayAccessVault(ctx context.Context, g *provider.Grantee) (bool, error) {
// Groups are allowed without a VaultMode check. Role assignments belong to single accounts,
// and group membership can change after the share exists. The notification services filter
// the group members by VaultMode instead, and every member still needs MFA to open the vault.
if g.GetType() == provider.GranteeType_GRANTEE_TYPE_GROUP {
return g.GetGroupId().GetOpaqueId() != "", nil
}
ref := vaultPermissionSubject(g)
if ref == nil {
return false, nil
@@ -93,7 +100,8 @@ func (s *svc) granteeMayAccessVault(ctx context.Context, g *provider.Grantee) (b
return vaultPermissionGranted(res.GetStatus())
}
// vaultPermissionSubject returns the subject to check VaultMode for, or nil for grantees that can never hold it, like groups.
// vaultPermissionSubject returns the subject to check VaultMode for, or nil for grantees that cannot hold it.
// Groups cannot hold it, because role assignments belong to single accounts.
func vaultPermissionSubject(g *provider.Grantee) *permissions.SubjectReference {
if g.GetType() != provider.GranteeType_GRANTEE_TYPE_USER {
return nil
+1 -1
View File
@@ -1321,7 +1321,7 @@ github.com/orcaman/concurrent-map
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
## explicit; go 1.18
github.com/owncloud/libre-graph-api-go
# github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
# github.com/owncloud/reva/v2 v2.0.0-20261028142447-7ce5132a4574
## explicit; go 1.26.0
github.com/owncloud/reva/v2/cmd/revad/internal/grace
github.com/owncloud/reva/v2/cmd/revad/runtime
@@ -105,6 +105,23 @@
/>
</div>
</div>
<div id="vault-group-notice-status" role="status">
<div
v-if="showVaultGroupNotice"
class="oc-flex oc-flex-middle oc-gap-s oc-background-muted oc-rounded oc-p-s oc-mb-s oc-text-small"
data-testid="vault-group-notice"
>
<oc-icon name="information" size="small" aria-hidden="true" />
<span
v-text="
$pgettext(
'Notice shown when sharing a resource inside the vault with a group',
'Group members without vault access will not receive a notification and cannot access the share.'
)
"
/>
</div>
</div>
<div class="oc-flex oc-flex-between oc-flex-middle oc-mb-l oc-mt-s">
<role-dropdown
mode="create"
@@ -199,7 +216,7 @@ import {
} from '@ownclouders/web-pkg'
import { computed, inject, ref, unref, watch, onMounted, nextTick, Ref, useTemplateRef } from 'vue'
import { Resource, SpaceResource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { DateTime } from 'luxon'
import { OcDrop } from '@ownclouders/design-system/components'
import { useTask } from 'vue-concurrency'
@@ -207,6 +224,7 @@ import { useGettext } from 'vue3-gettext'
import { isProjectSpaceResource } from '@ownclouders/web-client'
import { Group } from '@ownclouders/web-client/graph/generated'
import ExpirationDateIndicator from '../../ExpirationDateIndicator.vue'
import { isVaultResource as isVaultResourceHelper } from '../../../../../helpers/resource/vault'
type AccountType = {
prefix: string
@@ -317,15 +335,17 @@ const accountTypes: AccountType[] = [
]
const saveButtonText = computed(() => saveButtonLabel || $gettext('Share'))
// A resource lives in the vault if its storage provider is the vault one. Space resources carry
// the full drive id in storageId, plain resources only the provider id, hence the split.
const isVaultResource = computed(() => {
const storageId = unref(resource)?.storageId
if (!unref(capabilityRefs.vaultEnabled) || typeof storageId !== 'string') {
return false
}
return storageId.split('$')[0] === VAULT_STORAGE_PROVIDER_ID
})
const isVaultResource = computed(() =>
isVaultResourceHelper(unref(resource), unref(capabilityRefs.vaultEnabled))
)
// group members without vault access are filtered out by the server when it sends the share
// notifications, and they can't open the resource either
const showVaultGroupNotice = computed(
() =>
unref(isVaultResource) &&
unref(selectedCollaborators).some(({ shareType }) => shareType === ShareTypes.group.value)
)
// no local fallback: the default lives only in the server's vault config
const vaultDefaultExpirationDays = capabilityRefs.vaultDefaultShareExpirationDays
@@ -356,9 +376,9 @@ const fetchRecipientsTask = useTask(function* (signal, query: string) {
)
let groupData: Group[]
if (!unref(isExternalShareRoleType) && !unref(isVaultResource)) {
// groups are only available for internal shares, and never for vault resources: the
// vault permission is assigned per account, so a group can never hold it
if (!unref(isExternalShareRoleType)) {
// groups are only available for internal shares. For vault resources the server checks
// the vault permission of each group member when it sends the share notifications
groupData = yield* call(
client.groups.listGroups({ orderBy: ['displayName'], search: `"${query}"` }, { signal })
)
@@ -110,6 +110,7 @@ import {
} from '@ownclouders/web-pkg'
import { isLocationSharesActive } from '@ownclouders/web-pkg'
import { textUtils } from '../../../helpers/textUtils'
import { isVaultResource } from '../../../helpers/resource/vault'
import { isShareSpaceResource, ShareTypes } from '@ownclouders/web-client'
import InviteCollaboratorForm from './Collaborators/InviteCollaborator/InviteCollaboratorForm.vue'
import CollaboratorListItem from './Collaborators/ListItem.vue'
@@ -144,7 +145,11 @@ const { getSpaceMembers } = useSpacesStore()
const configStore = useConfigStore()
const { options: configOptions } = storeToRefs(configStore)
const { shareInviteCollaboratorHelp, shareInviteCollaboratorHelpCern } = useContextualHelpers()
const {
shareInviteCollaboratorHelp,
shareInviteCollaboratorHelpCern,
shareInviteCollaboratorHelpVault
} = useContextualHelpers()
const sharesStore = useSharesStore()
const { addShare, deleteShare } = sharesStore
@@ -203,14 +208,17 @@ const collaborators = computed(() => {
const inviteCollaboratorHelp = computed(() => {
const cernFeatures = configOptions.value.cernFeatures
const mergedHelp = { ...unref(shareInviteCollaboratorHelp) }
if (cernFeatures) {
const mergedHelp = { ...unref(shareInviteCollaboratorHelp) }
mergedHelp.list = [...unref(shareInviteCollaboratorHelpCern).list, ...mergedHelp.list]
return mergedHelp
}
return unref(shareInviteCollaboratorHelp)
if (isVaultResource(unref(resource), capabilityStore.vaultEnabled)) {
mergedHelp.list = [...mergedHelp.list, ...unref(shareInviteCollaboratorHelpVault).list]
}
return mergedHelp
})
const helpersEnabled = computed(() => {
@@ -63,6 +63,20 @@ export const useContextualHelpers = () => {
})
)
const shareInviteCollaboratorHelpVault = computed<ContextualHelperData>(() =>
filterContextHelper({
title: '',
list: [
{ text: $gettext('Groups in the vault'), headline: true },
{
text: $gettext(
'If you share with a group, only group members with vault access will receive a notification and can access the share.'
)
}
]
})
)
const shareSpaceAddMemberHelp = computed<ContextualHelperData>(() =>
filterContextHelper({
title: $gettext('Add members to this Space'),
@@ -134,6 +148,7 @@ export const useContextualHelpers = () => {
return {
shareInviteCollaboratorHelp,
shareInviteCollaboratorHelpCern,
shareInviteCollaboratorHelpVault,
shareSpaceAddMemberHelp,
shareViaLinkHelp,
shareViaIndirectLinkHelp,
@@ -0,0 +1,11 @@
import { Resource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
// A resource lives in the vault if its storage provider is the vault one. Space resources carry
// the full drive id in storageId, plain resources only the provider id, hence the split.
export const isVaultResource = (resource: Resource, vaultEnabled: boolean): boolean => {
const storageId = resource?.storageId
if (!vaultEnabled || typeof storageId !== 'string') {
return false
}
return storageId.split('$')[0] === VAULT_STORAGE_PROVIDER_ID
}
@@ -10,7 +10,12 @@ import {
} from '@ownclouders/web-test-helpers'
import { Resource, SpaceResource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { useSharesStore } from '@ownclouders/web-pkg'
import { CollaboratorAutoCompleteItem, CollaboratorShare, ShareRole } from '@ownclouders/web-client'
import {
CollaboratorAutoCompleteItem,
CollaboratorShare,
ShareRole,
ShareTypes
} from '@ownclouders/web-client'
import { Group, User } from '@ownclouders/web-client/graph/generated'
import { OcButton } from '@ownclouders/design-system/components'
import RoleDropdown from '../../../../../../../src/components/SideBar/Shares/Collaborators/RoleDropdown.vue'
@@ -122,7 +127,7 @@ describe('InviteCollaboratorForm', () => {
vault: { enabled: true, vault_storage_provider: '' }
}
it('only asks for users that may access the vault, and for no groups at all', async () => {
it('asks for users that may access the vault, and for groups', async () => {
const { wrapper, mocks } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
@@ -133,7 +138,7 @@ describe('InviteCollaboratorForm', () => {
expect.objectContaining({ filter: 'vaultEligible eq true' }),
expect.anything()
)
expect(mocks.$clientService.graphAuthenticated.groups.listGroups).not.toHaveBeenCalled()
expect(mocks.$clientService.graphAuthenticated.groups.listGroups).toHaveBeenCalled()
})
it('recognizes a vault space resource, which carries the full drive id', async () => {
const { wrapper, mocks } = getWrapper({
@@ -179,6 +184,49 @@ describe('InviteCollaboratorForm', () => {
)
})
})
describe('vault group notice', () => {
const vaultCapabilities = {
files_sharing: { federation: { incoming: true, outgoing: true } },
vault: { enabled: true, vault_storage_provider: '' }
}
it('shows when a group is selected for a vault resource', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.group.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeTruthy()
})
it('does not show when only users are selected', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: VAULT_STORAGE_PROVIDER_ID })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.user.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeFalsy()
})
it('does not show for a group outside the vault', async () => {
const { wrapper } = getWrapper({
capabilities: vaultCapabilities,
resource: mock<Resource>({ ...folderMock, storageId: 'some-other-provider' })
})
wrapper.vm.selectedCollaborators = [
mock<CollaboratorAutoCompleteItem>({ shareType: ShareTypes.group.value })
]
await wrapper.vm.$nextTick()
expect(wrapper.find('[data-testid="vault-group-notice"]').exists()).toBeFalsy()
})
})
describe('vault default expiration notice', () => {
const vaultCapabilities = {
files_sharing: { federation: { incoming: true, outgoing: true } },
@@ -1,6 +1,6 @@
import FileShares from '../../../../../src/components/SideBar/Shares/FileShares.vue'
import { mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client'
import { Resource, VAULT_STORAGE_PROVIDER_ID } from '@ownclouders/web-client'
import { SpaceResource } from '@ownclouders/web-client'
import { v4 as uuidV4 } from 'uuid'
import { CollaboratorShare, ShareRole, ShareTypes } from '@ownclouders/web-client'
@@ -53,6 +53,35 @@ describe('FileShares', () => {
})
})
describe('invite collaborator help', () => {
const hasVaultGroupHint = (wrapper: VueWrapper<any, any>) =>
wrapper.vm.inviteCollaboratorHelp.list.some(
({ text }: { text: string }) => text === 'Groups in the vault'
)
it('explains group shares for a vault resource', () => {
const { wrapper } = getWrapper({
vaultEnabled: true,
resource: mock<Resource>({
isReceivedShare: () => false,
canShare: () => true,
storageId: VAULT_STORAGE_PROVIDER_ID
})
})
expect(hasVaultGroupHint(wrapper)).toBeTruthy()
})
it('does not explain group shares for a resource outside the vault', () => {
const { wrapper } = getWrapper({
vaultEnabled: true,
resource: mock<Resource>({
isReceivedShare: () => false,
canShare: () => true,
storageId: 'some-other-provider'
})
})
expect(hasVaultGroupHint(wrapper)).toBeFalsy()
})
})
describe('collaborators list', () => {
let collaborators: CollaboratorShare[]
beforeEach(() => {
@@ -169,7 +198,8 @@ function getWrapper({
spaceMembers = [],
user = undefined,
ancestorMetaData = {},
canShare = true
canShare = true,
vaultEnabled = false
}: {
mountType?: typeof mount
resource?: Resource
@@ -179,11 +209,13 @@ function getWrapper({
user?: User
ancestorMetaData?: AncestorMetaData
canShare?: boolean
vaultEnabled?: boolean
} = {}) {
vi.mocked(useCanShare).mockReturnValue({ canShare: () => canShare })
const capabilities = {
files_sharing: { deny_access: false }
files_sharing: { deny_access: false },
vault: { enabled: vaultEnabled }
} satisfies Partial<CapabilityStore['capabilities']>
if (spaceMembers.length) {