Compare commits

..
Author SHA1 Message Date
owncloud-translations-bot[bot] d280aa9312 chore: update translations from transifex 2026-11-01 02:32:50 +00:00
5455511f19 fix(search): don't abort a reindex on unresolvable files; make the abort threshold configurable (#13034)
* fix(search): don't abort a reindex on unresolvable files; make the abort threshold configurable

IndexSpace gave up after 5 consecutive failed files, meant to detect a dead
extractor. Two things made it fire on healthy systems: a file the walker
listed but that could not be stat'ed by path counted as an extraction
failure although the extractor was never called, and because already-indexed
files are skipped without resetting the counter, five problem files anywhere
in walk order looked consecutive on a mostly-indexed space. The walk then
aborted at the same point every run and nothing after it was ever indexed.

Unresolvable files are now logged and skipped without counting. The threshold
is SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES (default 5, unchanged); 0 never
aborts.

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

* fix(search): skip only not-found files in the index walk; count every other resolve failure

Review follow-up for #13034:
- resolve() returns why a lookup failed. Only Stat CODE_NOT_FOUND (deleted,
  moved, or a stale node) is skipped without counting; auth, gateway,
  transport and deadline failures count towards the abort threshold again.
- A cancelled or timed-out walk now stops with an error instead of treating
  every remaining file as unresolvable and reporting success.
- An already-indexed, unchanged file resets the consecutive-failure counter
  (root cause 2 of #13033, which the first version described but did not fix).
- Consistent logging of resolve failures in UpsertItem, UpdateTags,
  RestoreItem and MoveItem (debug for not-found, warn/error otherwise).
- SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES rejects negative values.
- Doc comment of FullDefaultConfig restored; changelog in past tense.
- Tests: exact attempt count, a short retry delay in tests (no 25 s of real
  sleep), and new cases for a Stat internal error, a cancelled walk and a
  healthy file between two failures. Each new case fails without its fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpoeSoKYEdgQcWjEzTVKpT
Signed-off-by: Paul Faure <paul@faure.ca>

* fix(search): introduction version 9.0.0; changelog lists the PR first

Per review: SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES is introduced in
9.0.0 (mmattel), and the changelog entry lists the pull request before the
issue, as changelog/TEMPLATE does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpoeSoKYEdgQcWjEzTVKpT
Signed-off-by: Paul Faure <paul@faure.ca>

* fix(search): resolve walked files by ID; fail a walk that finds most files missing

Review follow-up for the index walk:

- Resolve each walked file by the ID the walker listed, not by its path,
  so a stale node that a Stat by path cannot find is still indexed.
- Count files that Stat does not find. The gateway also answers NOT_FOUND
  when it cannot reach a storage provider, so a walk in which at least 5
  files, and more than half of the files that needed work, were not found
  now ends with an error instead of reporting the space as indexed.
- Log one summary per walk (indexed, unchanged, failed, not found); the
  per-file not-found line is now Debug.
- statResource returns errResourceNotFound and ResolveReference returns
  errPathNotResolved instead of (nil, nil); each failure is logged once,
  by the caller.
- resInfo keeps returning the Stat result when only GetPath fails, as on
  master, so UpdateTags still updates the tags.
- Extraction retry waits end when the context does; the retry delay is a
  Service field instead of a package variable.
- One context check per callback plus one after the walk.
- Warn at startup when SEARCH_EXTRACTOR_MAX_CONSECUTIVE_FAILURES is 0;
  tests for Validate and the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X4GrG4iaNhDcvodMocGafF
Signed-off-by: Paul Faure <paul@faure.ca>

* fix(search): resolve walked files by path, fall back to the ID

The walker resolved every file by the ID it listed.
This added one GetPath call to each file that needs work.
It also changed the resolve path of healthy files for a rare edge case.

Resolve each file by its path again, as before.
Retry by ID only when Stat by path returns not found.
A stale node is still indexed.
A healthy file costs no extra GetPath call.

Add a test that a healthy file makes no GetPath call.
Check that the stale node makes exactly one GetPath call.
Update the changelog entry.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(search): treat a GetPath not-found like a Stat not-found

A file can vanish between the Stat and the GetPath of a walk.
GetPath then answers NOT_FOUND.
ResolveReference returned errPathNotResolved only.
IndexSpace counted this as an extraction failure.
Five such files could abort the walk.

Now the error matches errPathNotResolved and errResourceNotFound.
IndexSpace counts the file as not found.
The outage check at the end of the walk includes it.
resInfo still returns the Stat result, so UpdateTags works as before.

Add tests for a GetPath not-found and for another GetPath failure.
Update the changelog entry.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* test(search): pin the counter rule and the tag update on GetPath not-found

Test that a file that no longer exists neither counts nor resets the
failure counter. The test fails if a missing file resets the counter.

Run the UpdateTags test with a GetPath answer of NOT_FOUND too.
The test fails if resInfo checks errResourceNotFound before
errPathNotResolved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Roman Perekhod <2403905@gmail.com>
2026-10-30 18:45:42 +00:00
7d9b63b856 ci: add zizmor workflow audit (#13232)
* ci: add zizmor workflow audit

Runs zizmor over this repository's workflows and Dependabot config on
every pull request, on pushes to the default branch and weekly, through
owncloud/reusable-workflows' zizmor.yml. Any finding fails the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Thomas Müller <323649642+oc-tmueller@users.noreply.github.com>

* fix(ci): resolve zizmor findings

- excessive-permissions: workflows without a permissions block ran
  with the repository default, which is read/write. They now default
  to contents: read; only create-github-release gets contents: write,
  for softprops/action-gh-release. audit-release only GETs the
  published release, which read covers.
- cache-poisoning: the release workflow's setup-node steps opt out of
  package-manager caching, so a tag build cannot restore a cache that a
  branch build wrote.
- artipacked: checkouts do not persist credentials. No job runs a git
  operation after checkout.
- dependabot-cooldown: every ecosystem waits 7 days, as github-actions
  already does.
- ref-version-mismatch: setup-php's tag is 2.40.0, without the v.
- self-repository: local reusable workflows and actions are called as
  $/... instead of ./... .
- Suppressed inline, with the reason on the line: the unpinned
  `npm install -g yarn npx` in the release workflow (pre-existing, left
  to the maintainers), the version-pinned gherlint install, and the
  softprops release step, which CI cannot exercise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Thomas Müller <323649642+oc-tmueller@users.noreply.github.com>

* fix(ci): undo two zizmor auto-fix slips, keep scheduled runs

- zizmor's template-injection auto-fix read `${{ }}` inside a shell
  comment in determine-release-type as an expansion: it added an env
  entry reading that job's own output, which is always empty, and
  rewrote the comment to describe something no longer true. The entry
  is gone and the comment describes the env indirection the later jobs
  now use, with the version check as a second safeguard.
- Only pull request runs of the zizmor audit cancel each other now; a
  push to master and the weekly run share a ref.

The previous commit's message is incomplete: it lists a self-repository
change this repository did not need, and omits the auto-fixed
template-injection findings (expressions in run: moved to env: in
release.yml, release-npm-packages.yml and acceptance-tests.yml) and the
cache-poisoning fix also turning off setup-go's cache in the release
jobs, so a tag build cannot restore a cache a branch build wrote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Thomas Müller <323649642+oc-tmueller@users.noreply.github.com>

---------

Signed-off-by: Thomas Müller <323649642+oc-tmueller@users.noreply.github.com>
Co-authored-by: Thomas Müller <323649642+oc-tmueller@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:55:39 +01:00
Firas Frikha 913e9b83bf fix(graph): [OCISDEV-1601] let teachers of other schools receive vault shares before their first login (#13273)
* fix(graph): [OCISDEV-1601] let teachers of other schools receive vault shares before their first login

* chore: [OCISDEV-1601] add changelog entry

* fix(graph): [OCISDEV-1601] harden the guest vault role assignment

* docs(graph): [OCISDEV-1601] shorten the description of the guest role mapping

* fix(graph): [OCISDEV-1601] read the userClass with a separate backend method

* fix(graph): [OCISDEV-1601] assign the guest vault role around the share creation

* docs(graph): [OCISDEV-1601] describe that only the guest role mapping is used

* docs(graph): [OCISDEV-1601] document how graph applies the guest role mapping

* refactor: [OCISDEV-1601] share the guest role mapping between proxy and graph

* refactor(graph): [OCISDEV-1601] fix the linter findings of the guest vault role

* fix(graph): [OCISDEV-1601] keep the guest vault role once the share exists
2026-10-30 11:44:40 +01:00
Kavita gautam 15dacf5295 [tests-only][full-ci][k8s] test: Run e2e vault-storage on K8s deployment (#13088)
* test: run e2e vault-storage on K8s deployment

Signed-off-by: Kavita Gautam <kavita@jankaritech.com>

* test: add suite specific external services and proxy readyz

Signed-off-by: Kavita Gautam <kavita@jankaritech.com>

* test: directly specifying the readyz url

Signed-off-by: Kavita Gautam <kavita@jankaritech.com>

---------

Signed-off-by: Kavita Gautam <kavita@jankaritech.com>
2026-10-30 14:18:46 +05:45
LarsJurgensen ef9b4f7fc9 chore(deps): [OCISDEV-1392] bump reva (#13272) 2026-10-29 13:18:22 +01:00
Matteo 633837b3e1 revert(web): restore go redirect link in help menus (#13254)
* revert(web): restore go redirect link in help menus

Reverts the hard-coded documentation URLs from #13241. The help menus link to doc.owncloud.com/go?to=webui-users-sharing again, so the target can be maintained by the docs redirect instead of in web.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>

* chore: remove changelog of reverted help menu link fix

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>

---------

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-29 11:52:26 +01:00
Michal Klos 6b28863fa5 fix(graph): [OCISDEV-1542] LDAP user search: make email, surname configurable (#13219)
Signed-off-by: Michal Klos <michal.klos@kiteworks.com>
2026-10-29 09:48:00 +00:00
Roman PerekhodandClaude Sonnet 5.5 579249bd1e ci: ignore CVE-2026-116587 for go-jose/v3 in the Trivy scan (#13267)
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 09:38:41 +01:00
Pujitha PaladuguandPujitha Paladugu f6df02372c fix(deployments): pass SMTP password and authentication in ocis_full example (#13222)
Motivation: the ocis_full example defines SMTP_PASSWORD and SMTP_AUTHENTICATION
in .env but the ocis service did not forward them, so an SMTP server requiring
authentication could not be configured through this example.

Approach: add NOTIFICATIONS_SMTP_PASSWORD and NOTIFICATIONS_SMTP_AUTHENTICATION
to the ocis environment block next to the other NOTIFICATIONS_SMTP_* entries,
document accepted authentication values in .env, and add a changelog entry.
An empty SMTP_AUTHENTICATION is treated as 'auto' by the notifications service,
so existing setups that leave it unset behave as before.

Validation: parsed ocis.yml with python yaml and confirmed both variables are
present in the ocis environment. I could not run docker compose or an
authenticated SMTP server here (docker is not installed), so end-to-end mail
delivery was not exercised; I checked the variable names against the env tags
in services/notifications/pkg/config/config.go and the empty-value handling in
services/notifications/pkg/channels/channels.go.

Report: https://github.com/owncloud/ocis/issues/11757

Assisted-by: claude-sonnet-5-5 (via Claude Code)

Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
Co-authored-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
2026-10-28 17:51:10 +01:00
Firas Frikha 9469149f39 fix(deps): bump go-jose/v4 to v4.1.6 for CVE-2026-116587 (#13256)
* fix(deps): bump go-jose/v4 to v4.1.6 for CVE-2026-116587

* fix(deps): bump golang.org/x/net to v0.62.0 for GO-2026-6860 and GO-2026-6866
2026-10-28 10:08:47 +01:00
Roman PerekhodandClaude Opus 5.5 4680d9d905 fix(proxy): [OCISDEV-1464] fix the role assignment of multi-instance guests (#13250)
* fix(proxy): [OCISDEV-1464] fail on an unknown multi-instance guest role

The OIDC role assigner did not check that OCIS_MULTI_INSTANCE_GUEST_ROLE
exists. When the guest role name is wrong, the role name has no role id.
The proxy then sent AssignRoleToUser with an empty RoleId on each request.

The role assigner now returns an "unknown role" error and does not change
the role assignment. A test covers a guest that no guest role mapping
matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(proxy): [OCISDEV-1464] check the guest role mapping more strictly

GuestRoleMapping now trims the spaces around the claim value and the
role name. The env var parser trims list elements, but the yaml parser
does not. Before this change, the yaml entry "spaceadmin: user-light-vault"
gave the role name " user-light-vault", and each matching guest login
failed with "unknown role".

GuestRoleMapping now also rejects a mapping when
OCIS_MULTI_INSTANCE_GUEST_ROLE is empty. The role assigner applies the
mapping only to users that get the guest role. Without a guest role, the
proxy ignored the mapping and gave guests a member role.

gofmt also fixes the indent of a TODO comment in the same file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(proxy): [OCISDEV-1464] log why the guest role mapping does not apply

mapGuestRole dropped the extractRoles error without a log line. When
PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM had a wrong claim name, each guest kept
the guest role, and the admin could not find the cause.

mapGuestRole now writes a debug log line with the claim name and the
error. A guest without a roles claim is valid, and the role assigner runs
on each request, so the log level is debug and not warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(proxy): [OCISDEV-1464] tell that guest claim values are regexes

The guest role mapping uses the same claim matcher as the role mapping.
A claim value is an exact string or a regular expression that must match
the full claim value. The description of
OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING did not tell this. An admin who
writes 'school.admin' also matches the claim 'schoolXadmin', and that
guest can get a role with more permissions.

The description now tells that claim values are regexes. It also tells
the admin to escape regex metacharacters in an exact string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(proxy): [OCISDEV-1464] read the roles again for an unknown guest role

The OIDC role assigner checks the guest role and the mapped guest role
against a role cache with a 5 minute TTL. A role that an admin created
after the last cache read was unknown. For up to 5 minutes, each request
of a matching guest failed with "unknown role" and HTTP 500.

The new function guestRoleName reads the roles again one time when the
role is unknown. It reads the roles again only when the cache is older
than 30 seconds. Thus a role that does not exist causes a maximum of one
ListRoles request in 30 seconds, and not one request for each guest
request. The check for an unknown guest role moves into guestRoleName.

roleNamesToRoleIDs now has a maxAge parameter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: [OCISDEV-1464] add the changelog for the guest role mapping fixes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:44:32 +01:00
Matteo 64b18f5432 fix(web): [OCISDEV-1581] fix copy link in EPUB library book details (#13239)
Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-28 08:23:08 +01:00
Michal Klos a065ed0962 fix(graph): [OCISDEV-1519] include OCM federated users in vault-eligible sharee search (#13135) 2026-10-27 13:44:45 +00:00
Matteo 887145f143 fix(web): [OCISDEV-1583] restore trash items with the same name without conflicts (#13238)
* fix(web): [OCISDEV-1583] restore trash items with the same name without conflicts

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-27 13:28:08 +01:00
Matteo 1986da8657 fix(web): [OCISDEV-1589] fix broken Read more link in help menus (#13241)
Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-27 13:27:34 +01:00
Roman Perekhod 36a034fa83 feat: [OCISDEV-1586] added the vault support to the ocis_multi (#13243)
Added the vault support to the ocis_multi deployment exaple
2026-10-27 09:57:36 +01:00
Firas Frikha dd6fa31ac9 feat: [OCISDEV-1464] Assign multi-instance guests a role based on their claims (#13231) 2026-10-27 07:50:55 +00:00
Gaurav Soni cdaba15e35 fix(web): [OCISDEV-1183] stop logging OAuth tokens to the browser console (#13233)
* fix(web): [OCISDEV-1183] stop logging OAuth tokens to the browser console

On every login and silent token renewal, the web client wrote the user's raw
access and refresh tokens to the browser console via console.debug. The
userLoaded handler now logs a static message without any token or user data.

Signed-off-by: Gaurav Soni <sonigaurav119@gmail.com>

* docs: [OCISDEV-1183] add PR link to changelog

Signed-off-by: Gaurav Soni <sonigaurav119@gmail.com>

---------

Signed-off-by: Gaurav Soni <sonigaurav119@gmail.com>
2026-10-26 15:54:06 +00:00
Gaurav Soni efe85baed9 fix(web): [OCISDEV-1187] disable confirm in link password dialog when empty (#13218)
The link "Add password" / "Edit password" dialog could be confirmed, by
button or Enter, while the field was still empty, which removed the
password from the link. Confirm now starts disabled, and Enter only
confirms when the password policy is fulfilled, same as the button.

Signed-off-by: Gaurav Soni <sonigaurav119@gmail.com>
2026-10-26 14:24:14 +01:00
Matteo 486fa4811c chore: bump zod to 4.6.7 and happy-dom to 21.0.4 (#13227)
happy-dom 21 serializes var() fallbacks with a space after the comma,
so adjust the tag colour style assertions accordingly.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-26 11:40:32 +01:00
Lukas Hirt bacd899092 test: [OCISDEV-1558] wait for account page content before running a11y checks (#13161) 2026-10-25 12:16:22 +01:00
Matteo 6c1dfdc38c fix(web): [OCISDEV-1579] show a definitive no-permission message for inaccessible space trash (#13217) 2026-10-25 03:14:26 +01:00
owncloud-translations-bot[bot] 390614e9d0 chore: update translations from transifex (#13212)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-23 16:56:50 +00:00
Matteo 45e2b94b5e chore: bump dompurify to version 3.4.17 (#13216)
Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-23 09:30:08 +02:00
Gaurav Soni e609fefa8c feat(web): [OCISDEV-1417] make "Shared by" sortable in Shared with me (#13213)
The "Shared by" column in Shared with me could not be sorted. It now sorts
A to Z (Z to A on a second click) by all sharers' names in alphabetical
order, the same rule as "Shared with", so items shared by several people
stay in a stable place while the avatars keep their current order. Sorting
by "Shared with" also no longer reorders that column's avatars.

Signed-off-by: Gaurav Soni <sonigaurav119@gmail.com>
2026-10-22 11:31:47 +02:00
Matteo 2d8841f490 chore(web): bump vite to 7.3.7 and markdown-it to 14.3.3 (#13206)
Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-21 10:45:18 +02:00
Roman PerekhodandClaude Sonnet 5.5 00567fa575 feat: [full-ci] [OCISDEV-1563] remove the owncloudsql driver (#13191)
Remove the deprecated owncloudsql driver configuration from the storage-users,
auth-basic, users, groups and sharing services and from the migrate command.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 09:53:26 +02:00
owncloud-translations-bot[bot] 4f7de832a8 chore: update translations from transifex (#13196)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-21 07:06:16 +00:00
Matteo 46684067e9 fix(collaboration): [OCISDEV-1550] fix closing a shared document from the office editor (#13198)
Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-10-21 08:19:05 +02:00
330 changed files with 9890 additions and 8195 deletions

No files matched your search

+8
View File
@@ -7,6 +7,8 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -21,6 +23,8 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -35,6 +39,8 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
@@ -51,6 +57,8 @@ updates:
day: sunday
time: '22:00'
timezone: Etc/UTC
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
minor-and-patch:
+41 -8
View File
@@ -4,6 +4,9 @@ on:
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
detect-changes:
name: detect-changes
@@ -15,6 +18,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check if changes are docs-only
id: check
@@ -57,6 +61,8 @@ 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
@@ -69,7 +75,7 @@ jobs:
- name: Enable pnpm
run: corepack enable && corepack prepare pnpm@10.33.3 --activate
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -82,6 +88,7 @@ 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.
@@ -230,8 +237,10 @@ jobs:
- apiVault
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -314,8 +323,10 @@ 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 # v2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -362,8 +373,10 @@ jobs:
- apiGraphUser,apiGraph,apiGraphGroup
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -418,8 +431,10 @@ jobs:
- "coreApiWebdavMove1,coreApiWebdavPreviews,coreApiWebdavUpload,coreApiWebdavUploadTUS"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: "8.4"
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -534,6 +549,8 @@ 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.
@@ -704,6 +721,8 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -729,6 +748,8 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -754,6 +775,8 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -779,6 +802,8 @@ jobs:
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install libvips runtime
run: |
@@ -804,6 +829,8 @@ 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
@@ -837,6 +864,8 @@ 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
@@ -870,6 +899,8 @@ 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
@@ -883,14 +914,14 @@ jobs:
merge-multiple: true
- name: Convert coverage counters to profile
run: go tool covdata textfmt -i=${{ env.GOCOVERDIR }} -o=coverage.out
run: go tool covdata textfmt -i=${GOCOVERDIR} -o=coverage.out
- name: Publish coverage summary
run: |
{
echo "## Acceptance test coverage"
echo '```'
go tool covdata percent -i=${{ env.GOCOVERDIR }}
go tool covdata percent -i=${GOCOVERDIR}
echo '```'
echo
echo "<details>"
@@ -911,10 +942,12 @@ 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,6 +4,9 @@ on:
push:
branches: [master, stable-*]
permissions:
contents: read
jobs:
license-check:
runs-on: ubuntu-latest
@@ -11,6 +14,8 @@ 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,6 +5,9 @@ on:
schedule:
- cron: "0 1 * * *"
permissions:
contents: read
jobs:
test:
name: ${{ matrix.example }}
@@ -37,6 +40,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: owncloud/ocis
persist-credentials: false
- name: Prepare hosts entry
run: |
+134 -32
View File
@@ -18,6 +18,9 @@ env:
OCIS_WRAPPER_URL: http://localhost:5200
K8S: true
permissions:
contents: read
jobs:
api-tests:
name: ${{ matrix.suite }}-k8s
@@ -80,9 +83,11 @@ 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 # v2.40.0
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: ${{ env.PHP_VERSION }}
extensions: curl, xml, mbstring, zip, ldap, gd
@@ -488,13 +493,15 @@ 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
@@ -541,6 +548,8 @@ 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: |
@@ -552,6 +561,83 @@ 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 \
@@ -627,6 +713,15 @@ 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
@@ -662,41 +757,48 @@ jobs:
return 1
}
echo "Creating test file in oCIS..."
if [[ "${{ matrix.suite }}" == "vault-storage" ]]; then
retry "proxy readyz" curl -sf http://localhost:19205/readyz || exit 1
else
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
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
- 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' }}
+14 -5
View File
@@ -27,6 +27,8 @@ 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
@@ -44,7 +46,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
@@ -58,29 +60,36 @@ 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 }}
+44 -15
View File
@@ -18,6 +18,9 @@ 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
@@ -31,6 +34,7 @@ jobs:
with:
fetch-depth: 0
fetch-tags: true
persist-credentials: false
- id: info
env:
@@ -53,18 +57,17 @@ 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 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.
# `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.
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
@@ -81,14 +84,18 @@ 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 }}
- run: npm install --silent -g yarn npx --force
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v4
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
with:
version: ${{ env.PNPM_VERSION }}
- run: pnpm config set store-dir ./.pnpm-store && make ci-node-generate
@@ -99,8 +106,10 @@ 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
@@ -120,6 +129,8 @@ 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
@@ -127,12 +138,15 @@ 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 }}
@@ -144,6 +158,8 @@ 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
@@ -158,6 +174,8 @@ 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
@@ -165,10 +183,12 @@ 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
- run: npm install --silent -g yarn npx "pnpm@$PNPM_VERSION" --force
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
# 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.
@@ -190,16 +210,20 @@ 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
@@ -208,6 +232,8 @@ 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:
@@ -228,7 +254,7 @@ jobs:
name: changelog
path: .
- uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
with: # zizmor: ignore[superfluous-actions] the publish path only runs on a real release, CI cannot exercise a rewrite
tag_name: v${{ needs.determine-release-type.outputs.version }}
name: v${{ needs.determine-release-type.outputs.version }}
body_path: CHANGELOG.md
@@ -248,6 +274,8 @@ 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
@@ -262,9 +290,10 @@ 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,6 +5,9 @@ on:
push:
branches: [master, stable-*]
permissions:
contents: read
jobs:
detect-web-changes:
name: detect-web-changes
@@ -18,6 +21,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Check if web/ changed
id: check
@@ -70,6 +74,7 @@ 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
+3 -1
View File
@@ -19,7 +19,9 @@ jobs:
container: golang:1.25-alpine
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run CI Reporter
working-directory: tools/ci-reporter
+30
View File
@@ -0,0 +1,30 @@
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
View File
@@ -4,3 +4,4 @@
CVE-2026-32284 # github.com/shamaton/msgpack/v2 v2.4.0 — no fix available upstream
vendor/github.com/crewjam/saml/xmlenc/fuzz.go # test RSA key used in fuzz corpus, not a real secret
CVE-2026-116587 # github.com/go-jose/go-jose/v3 v3.0.5 — no v3 fix exists, only a transitive dependency of libregraph/lico, which parses JWKs only from local files and from configured OIDC authorities; go-jose/v4 is fixed
@@ -0,0 +1,10 @@
Bugfix: Fix closing a shared document from the office editor
Closing a document or using "Open file location" in the office editor failed
with a private link error for users who had a single file shared with them.
The editor linked to the folder containing the file, which belongs to the
sharer and is not accessible to the sharee. The folder link is now only
provided if the user can access the folder, otherwise closing the editor
leads back to oCIS.
https://github.com/owncloud/ocis/pull/13198
@@ -0,0 +1,11 @@
Bugfix: fixed copy link failing in the EPUB library book details
Clicking "Copy link" in the details of a book in the EPUB library showed
a "The link could not be copied" error whenever the book had been found
through the server-side search, because those search results carry no
link to the file.
The link is now built from the id of the file when the search result does
not provide one, so copying the link works for all books.
https://github.com/owncloud/ocis/pull/13239
@@ -0,0 +1,7 @@
Bugfix: Disable confirm in the link password dialog until a password is entered
The "Add password" / "Edit password" dialog for links could be confirmed with
an empty field, which removed the password from the link. The confirm button
is now disabled until a valid password is entered.
https://github.com/owncloud/ocis/pull/13218
@@ -0,0 +1,16 @@
Bugfix: Stop logging OAuth tokens to the browser console
On every login and every silent token renewal, the web client wrote the
signed-in user's raw OAuth `access_token` and `refresh_token` to the browser
console via a `console.debug` call in the `userLoaded` handler of the auth
service. Anyone with access to that browser's console or log buffer - a
malicious or over-permissioned browser extension, a shared or kiosk terminal,
a screen share or recording, or a session-replay tool that captures console
output - could read and reuse those live credentials. The production build
does not strip `console.debug`, so this shipped in the deployed bundle, not
just local dev.
The debug line now confirms that a new user was loaded without logging the
token, profile, or any other user field.
https://github.com/owncloud/ocis/pull/13233
@@ -0,0 +1,9 @@
Bugfix: Pass SMTP password and authentication to ocis in the ocis_full example
The `ocis_full` deployment example defined `SMTP_PASSWORD` and
`SMTP_AUTHENTICATION` in its `.env` file but did not forward them to the `ocis`
container, so an SMTP server requiring authentication could not be configured.
`NOTIFICATIONS_SMTP_PASSWORD` and `NOTIFICATIONS_SMTP_AUTHENTICATION` are now
passed through.
https://github.com/owncloud/ocis/issues/11757
@@ -0,0 +1,14 @@
Bugfix: Restore multiple trash items with the same name
Restoring several deleted files with the same name at once showed a conflict
dialog claiming the file already exists, even when it didn't. Choosing to
replace it then showed both a success and a failure notification, because
all files were restored to the same location at the same time and only one
of them could succeed.
Trash items that only collide with each other are now restored side by side
with unique names, without asking. When they collide with an existing file
and the user chooses to replace it, only one of them replaces the file and
the others are restored with unique names.
https://github.com/owncloud/ocis/pull/13238
@@ -0,0 +1,9 @@
Bugfix: Clarify the message for a trash the user may not access
When a member of a space was not allowed to list the space's deleted files, the
trash view said the user "may not" have the permission, even though the server
had clearly denied access. The view now states that the user does not have
permission to view the deleted files. Other failures to load the trash show a
generic error message instead of a guess about permissions.
https://github.com/owncloud/ocis/pull/13217
@@ -0,0 +1,17 @@
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
@@ -0,0 +1,9 @@
Change: Remove the owncloudsql driver
We removed the deprecated `owncloudsql` driver from oCIS.
The services `storage-users`, `auth-basic`, `users`, `groups`, and `sharing` no
longer accept the value `owncloudsql` for their driver. The related
configuration sections and environment variables are removed.
https://github.com/owncloud/ocis/pull/13191
@@ -0,0 +1,8 @@
Enhancement: Make the user search attributes configurable
Which attributes user search matches against is now configurable via
`GRAPH_LDAP_USER_SEARCH_ATTRIBUTES`, defaulting to name, display name and
e-mail. Deployments that need stricter matching (e.g. for data protection)
can restrict it to name, surname and username, excluding e-mail.
https://github.com/owncloud/ocis/pull/13219
@@ -0,0 +1,17 @@
Enhancement: Pick the role of multi-instance guests from their claims
In a multi-instance setup every guest got the same role,
`OCIS_MULTI_INSTANCE_GUEST_ROLE`, no matter what their roles claim said. A
teacher invited to another instance could therefore not be given access to
vault (Safe) resources there without giving it to every other guest as well.
The new `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` setting takes a list of
`claimvalue:rolename` pairs, for example `spaceadmin:user-light-vault`. A guest whose
`PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM` claim matches a pair gets that role instead
of the guest role, guests without a match keep `OCIS_MULTI_INSTANCE_GUEST_ROLE`.
A pair that points to a role which does not exist fails the login of the
matching guests. The proxy does not start if the setting is malformed or used
without the `oidc` role assignment driver. The setting is empty by default,
which keeps the previous behaviour.
https://github.com/owncloud/ocis/pull/13231
@@ -0,0 +1,14 @@
Enhancement: Sort "Shared with me" by "Shared by"
The "Shared by" column in "Shared with me" can now be sorted. Items are ordered
by the alphabetised display names of all the people who shared them, joined
into one key, so an item shared by several people is placed consistently
regardless of which avatar happens to display first. Clicking the column
header again reverses the order. The order of the avatars shown in the
column and the sidebar is unaffected.
Sorting by "Shared with" no longer reorders the avatars in that column. They
used to stay sorted alphabetically after switching to another sort, until the
page was reloaded.
https://github.com/owncloud/ocis/pull/13213
@@ -0,0 +1,19 @@
Bugfix: Fix the role assignment of multi-instance guests
The proxy now rejects an unknown multi-instance guest role. Before this
fix, the proxy assigned an empty role id when
`OCIS_MULTI_INSTANCE_GUEST_ROLE` named a role that does not exist.
The proxy now trims the spaces in the pairs of
`OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING`. The proxy does not start when the
mapping is set and `OCIS_MULTI_INSTANCE_GUEST_ROLE` is empty.
When a guest role is not in the role cache, the proxy reads the roles again.
Thus a new role works before the cache time ends. The proxy reads the roles
a maximum of one time in 30 seconds.
The proxy writes a debug log line when the roles claim of a guest is missing.
The description of `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` now tells that
a claim value is a regular expression.
https://github.com/owncloud/ocis/pull/13250
@@ -0,0 +1,31 @@
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
@@ -0,0 +1,7 @@
Security: Bump go-jose and golang.org/x/net dependencies
We've bumped go-jose/v4 to v4.1.6 to fix CVE-2026-116587, a denial of service
when parsing JWKs that contain RSA keys, and golang.org/x/net to v0.62.0 to
fix GO-2026-6860 and GO-2026-6866 in its html package.
https://github.com/owncloud/ocis/pull/13256
@@ -0,0 +1,8 @@
Security: Ignore CVE-2026-116587 for go-jose/v3 in the Trivy scan
The indirect dependency go-jose/v3 has no fix for CVE-2026-116587. It comes
from libregraph/lico. Lico reads JWKs only from local files and from
configured OIDC authorities. We've fixed go-jose/v4 and we ignore the go-jose/v3
finding in the Trivy scan.
https://github.com/owncloud/ocis/pull/13267
+1
View File
@@ -123,6 +123,7 @@ SMTP_USERNAME=
# Password for the SMTP host to connect to.
SMTP_PASSWORD=
# Authentication method for the SMTP communication.
# Possible values are 'login', 'plain', 'crammd5', 'none' or 'auto'. Defaults to 'auto' if unset.
SMTP_AUTHENTICATION=
# Allow insecure connections to the SMTP server. Defaults to false.
SMTP_INSECURE=
+2
View File
@@ -43,6 +43,8 @@ services:
NOTIFICATIONS_SMTP_PORT: "${SMTP_PORT}"
NOTIFICATIONS_SMTP_SENDER: "${SMTP_SENDER:-oCIS notifications <notifications@${OCIS_DOMAIN:-ocis.owncloud.test}>}"
NOTIFICATIONS_SMTP_USERNAME: "${SMTP_USERNAME}"
NOTIFICATIONS_SMTP_PASSWORD: "${SMTP_PASSWORD}"
NOTIFICATIONS_SMTP_AUTHENTICATION: "${SMTP_AUTHENTICATION}"
NOTIFICATIONS_SMTP_INSECURE: "${SMTP_INSECURE}"
# make the registry available to the app provider containers
MICRO_REGISTRY_ADDRESS: 127.0.0.1:9233
+16
View File
@@ -38,3 +38,19 @@ In this example, the admin user (configured in `config/ldap/ldif/20_users.ldif`
**Security Note:** Master-ID grants member status only (not admin privileges). Regular users require specific instance IDs for access control.
## Vault Mode
You can enable the vault storage on both instances. The file `vault-storage.yml` adds one extra `storage-users` service to each instance: `storage-users-vault` for `ocis` and `storage-users-vault-ocm` for `ocis-ocm`. It also enables MFA and vault mode on both `ocis` and `ocis-ocm`.
To start the deployment with the vault, add the file `vault-storage.yml` to the compose command:
```bash
docker compose -f docker-compose.yml -f vault-storage.yml up -d
```
Alternatively, set the `COMPOSE_FILE` environment variable:
```bash
COMPOSE_FILE=docker-compose.yml:vault-storage.yml docker compose up -d
```
@@ -18,7 +18,7 @@ gidNumber: 30000
homeDirectory: /home/einstein
ownCloudUUID: 4c510ada-c86b-4815-8820-42cdf82c3d51
owncloudMemberOf: ec730a6c-1b63-4b45-b83b-9e2311afdf85
ownCloudRole: ocisUser
ownCloudRole: ocisSpaceAdmin
userPassword:: e1NTSEF9TXJEcXpFNGdKbXZxbVRVTGhvWEZ1VzJBbkV3NWFLK3J3WTIvbHc9PQ==
dn: uid=marie,ou=users,dc=owncloud,dc=com
@@ -0,0 +1,79 @@
services:
ocis:
environment:
OCIS_MFA_ENABLED: true
NATS_NATS_HOST: 0.0.0.0
SETTINGS_GRPC_ADDR: ocis:9191
OCIS_ENABLE_VAULT_MODE: true
ocis-ocm:
environment:
OCIS_MFA_ENABLED: true
SETTINGS_GRPC_ADDR: ocis-ocm:9191
OCIS_ENABLE_VAULT_MODE: true
storage-users-vault:
image: ${OCIS_DOCKER_IMAGE:-owncloud/ocis}:${OCIS_DOCKER_TAG:-latest}
networks:
ocis-net:
depends_on:
ocis:
condition: service_started
command: ["storage-users", "server"]
environment:
OCIS_LOG_LEVEL: ${LOG_LEVEL:-info}
OCIS_LOG_COLOR: "${LOG_PRETTY:-false}"
OCIS_LOG_PRETTY: "${LOG_PRETTY:-false}"
OCIS_GATEWAY_GRPC_ADDR: ocis:9142
OCIS_EVENTS_ENDPOINT: ocis:9233
OCIS_CACHE_STORE_NODES: ocis:9233
MICRO_REGISTRY_ADDRESS: ocis:9233
# configure vault mode for the storage users service
STORAGE_USERS_ENABLE_VAULT_MODE: true
STORAGE_USERS_SERVICE_NAME: storage-users-vault
STORAGE_USERS_GRPC_ADDR: storage-users-vault:9285
STORAGE_USERS_HTTP_ADDR: storage-users-vault:9286
STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault:9286/data
STORAGE_USERS_DEBUG_ADDR: storage-users-vault:9287
STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault
STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs
volumes:
# use the same volumes as the ocis service
- ${OCIS_CONFIG_DIR:-ocis-config}:/etc/ocis
- ${OCIS_DATA_DIR:-ocis-data}:/var/lib/ocis
logging:
driver: ${LOG_DRIVER:-local}
restart: always
storage-users-vault-ocm:
image: ${OCIS_DOCKER_IMAGE:-owncloud/ocis}:${OCIS_DOCKER_TAG:-latest}
networks:
ocis-net:
depends_on:
ocis-ocm:
condition: service_started
command: ["storage-users", "server"]
environment:
OCIS_LOG_LEVEL: ${LOG_LEVEL:-info}
OCIS_LOG_COLOR: "${LOG_PRETTY:-false}"
OCIS_LOG_PRETTY: "${LOG_PRETTY:-false}"
OCIS_GATEWAY_GRPC_ADDR: ocis-ocm:9142
OCIS_EVENTS_ENDPOINT: ocis-ocm:9233
OCIS_CACHE_STORE_NODES: ocis-ocm:9233
MICRO_REGISTRY_ADDRESS: ocis-ocm:9233
# configure vault mode for the storage users service
STORAGE_USERS_ENABLE_VAULT_MODE: true
STORAGE_USERS_SERVICE_NAME: storage-users-vault
STORAGE_USERS_GRPC_ADDR: storage-users-vault-ocm:9285
STORAGE_USERS_HTTP_ADDR: storage-users-vault-ocm:9286
STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault-ocm:9286/data
STORAGE_USERS_DEBUG_ADDR: storage-users-vault-ocm:9287
STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault
STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs
volumes:
# use the same volumes as the ocis-ocm service
- ${OCIS_OCM_CONFIG_DIR:-ocis-ocm-config}:/etc/ocis
- ${OCIS_OCM_DATA_DIR:-ocis-ocm-data}:/var/lib/ocis
logging:
driver: ${LOG_DRIVER:-local}
restart: always
+8 -8
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-20261012083840-8b649a4c3899
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.25.0
@@ -97,14 +97,14 @@ require (
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0
go.opentelemetry.io/otel/sdk v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
golang.org/x/crypto v0.57.0
golang.org/x/crypto v0.58.0
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba
golang.org/x/image v0.46.0
golang.org/x/net v0.60.0
golang.org/x/net v0.62.0
golang.org/x/oauth2 v0.37.0
golang.org/x/sync v0.24.0
golang.org/x/term v0.46.0
golang.org/x/text v0.42.0
golang.org/x/term v0.47.0
golang.org/x/text v0.43.0
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
google.golang.org/grpc v1.86.0-dev
google.golang.org/protobuf v1.36.12
@@ -191,7 +191,7 @@ require (
github.com/go-git/go-billy/v5 v5.9.0 // indirect
github.com/go-git/go-git/v5 v5.19.2 // indirect
github.com/go-jose/go-jose/v3 v3.0.5 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/go-logr/logr v1.4.4 // indirect
@@ -341,9 +341,9 @@ require (
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/time v0.16.0 // indirect
golang.org/x/tools v0.50.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/genproto v0.0.0-20260622175928-b703f567277d // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
+18 -16
View File
@@ -306,8 +306,8 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2
github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=
github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
@@ -736,8 +736,10 @@ 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-20261012083840-8b649a4c3899 h1:IMu076AtnFEdabpBbowcGDYOeFLtm9ycNY1Z43YPYZU=
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
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/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=
@@ -1018,8 +1020,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -1102,8 +1104,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -1191,8 +1193,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -1200,8 +1202,8 @@ golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -1213,8 +1215,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1267,8 +1269,8 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210112230658-8b4aab62c064/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+48
View File
@@ -0,0 +1,48 @@
// 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
@@ -0,0 +1,61 @@
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))
})
}
}
-9
View File
@@ -501,15 +501,6 @@ func revaShareConfig(cfg *sharing.Config) map[string]interface{} {
"enable_expired_shares_cleanup": cfg.UserSharingDrivers.SQL.EnableExpiredSharesCleanup,
"janitor_run_interval": cfg.UserSharingDrivers.SQL.JanitorRunInterval,
},
"owncloudsql": map[string]interface{}{
"gateway_addr": cfg.Reva.Address,
"storage_mount_id": cfg.UserSharingDrivers.OwnCloudSQL.UserStorageMountID,
"db_username": cfg.UserSharingDrivers.OwnCloudSQL.DBUsername,
"db_password": cfg.UserSharingDrivers.OwnCloudSQL.DBPassword,
"db_host": cfg.UserSharingDrivers.OwnCloudSQL.DBHost,
"db_port": cfg.UserSharingDrivers.OwnCloudSQL.DBPort,
"db_name": cfg.UserSharingDrivers.OwnCloudSQL.DBName,
},
"cs3": map[string]interface{}{
"gateway_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
"provider_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
+2 -15
View File
@@ -52,9 +52,8 @@ type GRPCConfig struct {
}
type AuthProviders struct {
LDAP LDAPProvider `yaml:"ldap"`
OwnCloudSQL OwnCloudSQLProvider `yaml:"owncloudsql"`
JSON JSONProvider `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
LDAP LDAPProvider `yaml:"ldap"`
JSON JSONProvider `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
}
type JSONProvider struct {
@@ -110,15 +109,3 @@ type LDAPGroupSchema struct {
Groupname string `yaml:"group_name" env:"OCIS_LDAP_GROUP_SCHEMA_GROUPNAME;AUTH_BASIC_LDAP_GROUP_SCHEMA_GROUPNAME" desc:"LDAP Attribute to use for the name of groups." introductionVersion:"pre5.0"`
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;AUTH_BASIC_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
}
type OwnCloudSQLProvider struct {
DBUsername string `yaml:"db_username" env:"AUTH_BASIC_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
DBPassword string `yaml:"db_password" env:"AUTH_BASIC_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
DBHost string `yaml:"db_host" env:"AUTH_BASIC_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
DBPort int `yaml:"db_port" env:"AUTH_BASIC_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
DBName string `yaml:"db_name" env:"AUTH_BASIC_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
IDP string `yaml:"idp" env:"AUTH_BASIC_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
Nobody int64 `yaml:"nobody" env:"AUTH_BASIC_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
JoinUsername bool `yaml:"join_username" env:"AUTH_BASIC_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames" introductionVersion:"pre5.0"`
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"AUTH_BASIC_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user ID's." introductionVersion:"pre5.0"`
}
@@ -76,16 +76,6 @@ func DefaultConfig() *config.Config {
},
},
JSON: config.JSONProvider{},
OwnCloudSQL: config.OwnCloudSQLProvider{
DBUsername: "owncloud",
DBHost: "mysql",
DBPort: 3306,
DBName: "owncloud",
IDP: "https://localhost:9200",
Nobody: 90,
JoinUsername: false,
JoinOwnCloudUUID: false,
},
},
}
}
@@ -30,17 +30,6 @@ func AuthBasicConfigFromStruct(cfg *config.Config) map[string]interface{} {
"users": cfg.AuthProviders.JSON.File,
},
"ldap": ldapConfigFromString(cfg.AuthProviders.LDAP),
"owncloudsql": map[string]interface{}{
"dbusername": cfg.AuthProviders.OwnCloudSQL.DBUsername,
"dbpassword": cfg.AuthProviders.OwnCloudSQL.DBPassword,
"dbhost": cfg.AuthProviders.OwnCloudSQL.DBHost,
"dbport": cfg.AuthProviders.OwnCloudSQL.DBPort,
"dbname": cfg.AuthProviders.OwnCloudSQL.DBName,
"idp": cfg.AuthProviders.OwnCloudSQL.IDP,
"nobody": cfg.AuthProviders.OwnCloudSQL.Nobody,
"join_username": cfg.AuthProviders.OwnCloudSQL.JoinUsername,
"join_ownclouduuid": cfg.AuthProviders.OwnCloudSQL.JoinOwnCloudUUID,
},
},
},
},
@@ -1241,8 +1241,17 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
privateLinkURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetId()))
parentFolderURL := &url.URL{}
*parentFolderURL = *ocisURL
breadcrumbFolderURL := ""
if !isPublicShare {
parentFolderURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetParentId()))
// the parent folder isn't always accessible, e.g. for a file shared directly with
// the user. Only link to it if it is, closing falls back to the oCIS URL otherwise.
parentStatRes, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
Ref: &providerv1beta1.Reference{ResourceId: statRes.GetInfo().GetParentId()},
})
if err == nil && parentStatRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_OK {
parentFolderURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetParentId()))
breadcrumbFolderURL = parentFolderURL.String()
}
} else {
if scopes, ok := ctxpkg.ContextGetScopes(ctx); ok {
publicShare := &link.PublicShare{}
@@ -1254,6 +1263,7 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
} else {
logger.Error().Err(err).Msg("CheckFileInfo: error getting scopes from the context")
}
breadcrumbFolderURL = parentFolderURL.String()
}
// BreadcrumbBrandURL points at the space's root resource, exposing an internal
// space/resource id; for public shares an anonymous user has no other way to reach
@@ -1297,11 +1307,11 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
fileinfo.KeyBreadcrumbDocName: path.Base(statRes.GetInfo().GetPath()),
// to get the folder we actually need to do a GetPath() request
fileinfo.KeyBreadcrumbFolderName: breadcrumbFolderName,
fileinfo.KeyBreadcrumbFolderURL: parentFolderURL.String(),
fileinfo.KeyBreadcrumbFolderURL: breadcrumbFolderURL,
fileinfo.KeyBreadcrumbBrandName: statRes.GetInfo().GetSpace().GetName(),
fileinfo.KeyBreadcrumbBrandURL: breadcrumbBrandURL,
// the WOPI client should navigate here when the editor is closed; the folder
// containing the file is the same target used for the breadcrumb folder link
// containing the file if the user can access it, the oCIS URL otherwise
fileinfo.KeyCloseURL: parentFolderURL.String(),
fileinfo.KeyHostViewURL: createHostUrl("view", ocisURL, f.cfg.App.Name, statRes.GetInfo()),
@@ -1713,6 +1713,17 @@ var _ = Describe("FileConnector", func() {
})
Describe("CheckFileInfo", func() {
var parentStatRes *providerv1beta1.StatResponse
BeforeEach(func() {
// CheckFileInfo stats the parent folder to check whether the user can access it
parentStatRes = &providerv1beta1.StatResponse{Status: status.NewOK(context.Background())}
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(req *providerv1beta1.StatRequest) bool {
return req.GetRef().GetResourceId().GetOpaqueId() != wopiCtx.FileReference.GetResourceId().GetOpaqueId()
})).Maybe().Return(func(context.Context, *providerv1beta1.StatRequest, ...grpc.CallOption) (*providerv1beta1.StatResponse, error) {
return parentStatRes, nil
})
})
It("No valid context", func() {
gatewaySelector.EXPECT().Next().Unset()
ctx := context.Background()
@@ -3396,6 +3407,64 @@ var _ = Describe("FileConnector", func() {
Expect(collaboraResponse.BreadcrumbFolderURL).To(Equal("https://ocis.example.prv/f/storageid$spaceid%21documentsid"))
})
It("Collabora CheckFileInfo omits the folder link if the parent folder isn't accessible", func() {
// e.g. a file shared directly with the user, its parent folder belongs to the sharer
parentStatRes = &providerv1beta1.StatResponse{Status: status.NewNotFound(context.Background(), "not found")}
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
u := &userv1beta1.User{
Id: &userv1beta1.UserId{
Idp: "customIdp",
OpaqueId: "admin",
},
DisplayName: "Pet Shaft",
}
ctx = ctxpkg.ContextSetUser(ctx, u)
gatewayClient.On("Stat", mock.Anything, mock.Anything).Times(1).Return(&providerv1beta1.StatResponse{
Status: status.NewOK(ctx),
Info: &providerv1beta1.ResourceInfo{
Owner: &userv1beta1.UserId{
Idp: "customIdp",
OpaqueId: "aabbcc",
Type: userv1beta1.UserType_USER_TYPE_PRIMARY,
},
Size: uint64(998877),
Mtime: &typesv1beta1.Timestamp{Seconds: uint64(16273849)},
Path: "/personal/user/Documents/report.docx",
Id: &providerv1beta1.ResourceId{
StorageId: "storageid",
OpaqueId: "fileid",
SpaceId: "spaceid",
},
ParentId: &providerv1beta1.ResourceId{
StorageId: "storageid",
OpaqueId: "documentsid",
SpaceId: "spaceid",
},
Space: &providerv1beta1.StorageSpace{
Name: "Personal",
Root: &providerv1beta1.ResourceId{
StorageId: "storageid",
OpaqueId: "rootid",
SpaceId: "spaceid",
},
},
},
}, nil)
cfg.App.Name = "Collabora"
cfg.App.Product = "Collabora"
response, err := fc.CheckFileInfo(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(response.Status).To(Equal(200))
collaboraResponse := response.Body.(*fileinfo.Collabora)
Expect(collaboraResponse.BreadcrumbFolderURL).To(BeEmpty())
Expect(collaboraResponse.CloseURL).To(Equal("https://ocis.example.prv"))
})
It("Collabora CheckFileInfo breadcrumb folder name falls back to the space name for a file at the space root", func() {
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
u := &userv1beta1.User{
+22 -18
View File
@@ -84,20 +84,23 @@ type LDAP struct {
PoolSize int `yaml:"pool_size" env:"OCIS_LDAP_POOL_SIZE;GRAPH_LDAP_POOL_SIZE" desc:"Maximum number of concurrently open LDAP connections when 'OCIS_LDAP_POOL_ENABLED' is 'true'. Defaults to 5 when unset or <= 0." introductionVersion:"8.2.0"`
PoolCheckoutTimeout time.Duration `yaml:"pool_checkout_timeout" env:"OCIS_LDAP_POOL_CHECKOUT_TIMEOUT;GRAPH_LDAP_POOL_CHECKOUT_TIMEOUT" desc:"Maximum time to wait for a pooled LDAP connection to become available once the pool is exhausted. Defaults to 30s when unset or <= 0. See the Environment Variable Types description for more details." introductionVersion:"8.2.0"`
UserBaseDN string `yaml:"user_base_dn" env:"OCIS_LDAP_USER_BASE_DN;GRAPH_LDAP_USER_BASE_DN" desc:"Search base DN for looking up LDAP users." introductionVersion:"pre5.0"`
UserSearchScope string `yaml:"user_search_scope" env:"OCIS_LDAP_USER_SCOPE;GRAPH_LDAP_USER_SCOPE" desc:"LDAP search scope to use when looking up users. Supported scopes are 'base', 'one' and 'sub'." introductionVersion:"pre5.0"`
UserFilter string `yaml:"user_filter" env:"OCIS_LDAP_USER_FILTER;GRAPH_LDAP_USER_FILTER" desc:"LDAP filter to add to the default filters for user search like '(objectclass=ownCloud)'." introductionVersion:"pre5.0"`
UserObjectClass string `yaml:"user_objectclass" env:"OCIS_LDAP_USER_OBJECTCLASS;GRAPH_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
UserEmailAttribute string `yaml:"user_mail_attribute" env:"OCIS_LDAP_USER_SCHEMA_MAIL;GRAPH_LDAP_USER_EMAIL_ATTRIBUTE" desc:"LDAP Attribute to use for the email address of users." introductionVersion:"pre5.0"`
UserDisplayNameAttribute string `yaml:"user_displayname_attribute" env:"OCIS_LDAP_USER_SCHEMA_DISPLAYNAME;GRAPH_LDAP_USER_DISPLAYNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the display name of users." introductionVersion:"pre5.0"`
UserNameAttribute string `yaml:"user_name_attribute" env:"OCIS_LDAP_USER_SCHEMA_USERNAME;GRAPH_LDAP_USER_NAME_ATTRIBUTE" desc:"LDAP Attribute to use for username of users." introductionVersion:"pre5.0"`
UserIDAttribute string `yaml:"user_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_ID;GRAPH_LDAP_USER_UID_ATTRIBUTE" desc:"LDAP Attribute to use as the unique ID for users. This should be a stable globally unique ID like a UUID." introductionVersion:"pre5.0"`
UserIDIsOctetString bool `yaml:"user_id_is_octet_string" env:"OCIS_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING;GRAPH_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING" desc:"Set this to true if the defined 'ID' attribute for users is of the 'OCTETSTRING' syntax. This is required when using the 'objectGUID' attribute of Active Directory for the user ID's." introductionVersion:"pre5.0"`
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;GRAPH_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
UserEnabledAttribute string `yaml:"user_enabled_attribute" env:"OCIS_LDAP_USER_ENABLED_ATTRIBUTE;GRAPH_USER_ENABLED_ATTRIBUTE" desc:"LDAP Attribute to use as a flag telling if the user is enabled or disabled." introductionVersion:"pre5.0"`
ExternalIDAttribute string `yaml:"external_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID;GRAPH_LDAP_EXTERNAL_ID_ATTRIBUTE" desc:"LDAP attribute that references the external ID of users during the provisioning process. The final ID is provided by an external identity provider. If it is not set, a default attribute will be used instead." introductionVersion:"8.0.0"`
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;GRAPH_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Supported options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed. Default is 'attribute'." introductionVersion:"pre5.0"`
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;GRAPH_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
UserBaseDN string `yaml:"user_base_dn" env:"OCIS_LDAP_USER_BASE_DN;GRAPH_LDAP_USER_BASE_DN" desc:"Search base DN for looking up LDAP users." introductionVersion:"pre5.0"`
UserSearchScope string `yaml:"user_search_scope" env:"OCIS_LDAP_USER_SCOPE;GRAPH_LDAP_USER_SCOPE" desc:"LDAP search scope to use when looking up users. Supported scopes are 'base', 'one' and 'sub'." introductionVersion:"pre5.0"`
UserFilter string `yaml:"user_filter" env:"OCIS_LDAP_USER_FILTER;GRAPH_LDAP_USER_FILTER" desc:"LDAP filter to add to the default filters for user search like '(objectclass=ownCloud)'." introductionVersion:"pre5.0"`
UserObjectClass string `yaml:"user_objectclass" env:"OCIS_LDAP_USER_OBJECTCLASS;GRAPH_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
UserAdditionalObjectClasses []string `yaml:"user_additional_objectclasses" env:"OCIS_LDAP_USER_ADDITIONAL_OBJECTCLASSES;GRAPH_LDAP_USER_ADDITIONAL_OBJECTCLASSES" desc:"Additional object classes to set when creating new users (e.g. to allow a custom surname attribute). The default classes 'inetOrgPerson', 'organizationalPerson', 'person', 'top' and 'ownCloudUser' are always included." introductionVersion:"9.0.0"`
UserEmailAttribute string `yaml:"user_mail_attribute" env:"OCIS_LDAP_USER_SCHEMA_MAIL;GRAPH_LDAP_USER_EMAIL_ATTRIBUTE" desc:"LDAP Attribute to use for the email address of users." introductionVersion:"pre5.0"`
UserDisplayNameAttribute string `yaml:"user_displayname_attribute" env:"OCIS_LDAP_USER_SCHEMA_DISPLAYNAME;GRAPH_LDAP_USER_DISPLAYNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the display name of users." introductionVersion:"pre5.0"`
UserNameAttribute string `yaml:"user_name_attribute" env:"OCIS_LDAP_USER_SCHEMA_USERNAME;GRAPH_LDAP_USER_NAME_ATTRIBUTE" desc:"LDAP Attribute to use for username of users." introductionVersion:"pre5.0"`
UserSurnameAttribute string `yaml:"user_surname_attribute" env:"OCIS_LDAP_USER_SCHEMA_SURNAME;GRAPH_LDAP_USER_SURNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the surname of users." introductionVersion:"9.0.0"`
UserSearchAttributes []string `yaml:"user_search_attributes" env:"GRAPH_LDAP_USER_SEARCH_ATTRIBUTES" desc:"The user attributes to match against when searching for users via the Graph API. Does not affect the legacy OCS sharees search, which always matches on username, display name, and mail. Accepts the logical names 'onPremisesSamAccountName', 'displayName', 'surname', 'mail' (case-insensitive), or any other LDAP attribute name directly." introductionVersion:"9.0.0"`
UserIDAttribute string `yaml:"user_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_ID;GRAPH_LDAP_USER_UID_ATTRIBUTE" desc:"LDAP Attribute to use as the unique ID for users. This should be a stable globally unique ID like a UUID." introductionVersion:"pre5.0"`
UserIDIsOctetString bool `yaml:"user_id_is_octet_string" env:"OCIS_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING;GRAPH_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING" desc:"Set this to true if the defined 'ID' attribute for users is of the 'OCTETSTRING' syntax. This is required when using the 'objectGUID' attribute of Active Directory for the user ID's." introductionVersion:"pre5.0"`
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;GRAPH_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
UserEnabledAttribute string `yaml:"user_enabled_attribute" env:"OCIS_LDAP_USER_ENABLED_ATTRIBUTE;GRAPH_USER_ENABLED_ATTRIBUTE" desc:"LDAP Attribute to use as a flag telling if the user is enabled or disabled." introductionVersion:"pre5.0"`
ExternalIDAttribute string `yaml:"external_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID;GRAPH_LDAP_EXTERNAL_ID_ATTRIBUTE" desc:"LDAP attribute that references the external ID of users during the provisioning process. The final ID is provided by an external identity provider. If it is not set, a default attribute will be used instead." introductionVersion:"8.0.0"`
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;GRAPH_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Supported options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed. Default is 'attribute'." introductionVersion:"pre5.0"`
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;GRAPH_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
GroupBaseDN string `yaml:"group_base_dn" env:"OCIS_LDAP_GROUP_BASE_DN;GRAPH_LDAP_GROUP_BASE_DN" desc:"Search base DN for looking up LDAP groups." introductionVersion:"pre5.0"`
GroupCreateBaseDN string `yaml:"group_create_base_dn" env:"GRAPH_LDAP_GROUP_CREATE_BASE_DN" desc:"Parent DN under which new groups are created. This DN needs to be subordinate to the 'GRAPH_LDAP_GROUP_BASE_DN'. This setting is only relevant when 'GRAPH_LDAP_SERVER_WRITE_ENABLED' is 'true'. It defaults to the value of 'GRAPH_LDAP_GROUP_BASE_DN'. All groups outside of this subtree are treated as readonly groups and cannot be updated." introductionVersion:"pre5.0"`
@@ -199,8 +202,9 @@ 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"`
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"`
}
@@ -104,6 +104,8 @@ func DefaultConfig() *config.Config {
UserEmailAttribute: "mail",
UserDisplayNameAttribute: "displayName",
UserNameAttribute: "uid",
UserSurnameAttribute: "sn",
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
// FIXME: switch this to some more widely available attribute by default
// ideally this needs to be constant for the lifetime of a users
UserIDAttribute: "ownCloudUUID",
+2
View File
@@ -41,6 +41,8 @@ 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,6 +81,11 @@ 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)
+134 -44
View File
@@ -27,7 +27,6 @@ import (
const (
givenNameAttribute = "givenname"
surNameAttribute = "sn"
identitiesAttribute = "oCExternalIdentity"
lastSignAttribute = "oCLastSignInTimestamp"
ldapDateFormat = "20060102150405Z0700"
@@ -61,12 +60,14 @@ type LDAP struct {
retryBaseDelay time.Duration
retryMaxDelay time.Duration
userBaseDN string
userFilter string
userObjectClass string
userIDisOctetString bool
userScope int
userAttributeMap userAttributeMap
userBaseDN string
userFilter string
userObjectClass string
userAdditionalObjectClasses []string
userIDisOctetString bool
userScope int
userAttributeMap userAttributeMap
userSearchFilterTemplate string
disableUserMechanism DisableUserMechanismType
localUserDisableGroupDN string
@@ -144,9 +145,24 @@ func ParseDisableMechanismType(disableMechanism string) (DisableUserMechanismTyp
}
func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, instanceID string, masterID string) (*LDAP, error) {
if config.UserDisplayNameAttribute == "" || config.UserIDAttribute == "" ||
config.UserEmailAttribute == "" || config.UserNameAttribute == "" {
return nil, errors.New("invalid user attribute mappings")
requiredUserAttrs := map[string]string{
"UserDisplayNameAttribute": config.UserDisplayNameAttribute,
"UserIDAttribute": config.UserIDAttribute,
"UserEmailAttribute": config.UserEmailAttribute,
"UserNameAttribute": config.UserNameAttribute,
"UserSurnameAttribute": config.UserSurnameAttribute,
}
for name, value := range requiredUserAttrs {
if value == "" {
return nil, fmt.Errorf("invalid user attribute mappings: %s must not be empty", name)
}
}
// Normalize to the canonical "sn" spelling (LDAP attribute names are case-insensitive,
// and "surname" is its RFC 4519 schema alias) so downstream code can do a plain string
// compare instead of re-checking case/alias on every use.
surnameAttribute := config.UserSurnameAttribute
if strings.EqualFold(surnameAttribute, "sn") || strings.EqualFold(surnameAttribute, "surname") {
surnameAttribute = "sn"
}
uam := userAttributeMap{
displayName: config.UserDisplayNameAttribute,
@@ -155,7 +171,7 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
userName: config.UserNameAttribute,
accountEnabled: config.UserEnabledAttribute,
givenName: givenNameAttribute,
surname: surNameAttribute,
surname: surnameAttribute,
userType: config.UserTypeAttribute,
identities: identitiesAttribute,
lastSignIn: lastSignAttribute,
@@ -163,6 +179,10 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
userMemberAttribute: config.UserMemberAttribute,
userGuestAttribute: config.UserGuestAttribute,
}
userSearchFilterTemplate, searchAttrErr := userSearchFilterTemplateFor(uam, config.UserSearchAttributes)
if searchAttrErr != nil {
return nil, fmt.Errorf("error configuring user search attributes: %w", searchAttrErr)
}
if config.GroupNameAttribute == "" || config.GroupIDAttribute == "" {
return nil, errors.New("invalid group attribute mappings")
@@ -234,9 +254,11 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
userBaseDN: config.UserBaseDN,
userFilter: config.UserFilter,
userObjectClass: config.UserObjectClass,
userAdditionalObjectClasses: config.UserAdditionalObjectClasses,
userIDisOctetString: config.UserIDIsOctetString,
userScope: userScope,
userAttributeMap: uam,
userSearchFilterTemplate: userSearchFilterTemplate,
groupBaseDN: config.GroupBaseDN,
groupCreateBaseDN: config.GroupCreateBaseDN,
groupFilter: config.GroupFilter,
@@ -423,6 +445,15 @@ func (i *LDAP) UpdateUser(ctx context.Context, nameOrID string, user libregraph.
}
}
// person's mandatory "sn" is a separate attribute from the configured one above;
// keep it in sync like CreateUser does.
if sn := user.GetSurname(); sn != "" && i.mirrorSurnameIntoSN() {
if e.GetEqualFoldAttributeValue("sn") != sn {
mr.Replace("sn", []string{sn})
updateNeeded = true
}
}
if user.PasswordProfile != nil && user.PasswordProfile.GetPassword() != "" {
if i.usePwModifyExOp {
if err := i.updateUserPassword(ctx, e.DN, user.PasswordProfile.GetPassword()); err != nil {
@@ -525,6 +556,47 @@ func (i *LDAP) AddUser(ctx context.Context, id string, instanceID string) (libre
return *u, nil
}
// %[1]s is reused by every clause so userSearchFilter fills them all with one Sprintf arg.
// Excluding mail from the configured names keeps search from revealing which address is whose.
func userSearchFilterTemplateFor(uam userAttributeMap, logicalNames []string) (string, error) {
if len(logicalNames) == 0 {
return "", errors.New("at least one user search attribute must be configured")
}
var b strings.Builder
b.WriteString("(|")
for _, name := range logicalNames {
var attr string
switch {
case strings.EqualFold(name, "onPremisesSamAccountName"):
attr = uam.userName
case strings.EqualFold(name, "displayName"):
attr = uam.displayName
case strings.EqualFold(name, "surname"):
attr = uam.surname
case strings.EqualFold(name, "mail"):
attr = uam.mail
default:
// Not one of the known logical names; treat it as a literal LDAP attribute
// name so admins can search on attributes graph has no logical name for (e.g. "uid").
attr = name
}
b.WriteString("(")
// attr is admin-configured, not user input, but a literal '%' would still corrupt the
// Sprintf template below
b.WriteString(strings.ReplaceAll(attr, "%", "%%"))
b.WriteString("=*%[1]s*)")
}
b.WriteString(")")
return b.String(), nil
}
func (i *LDAP) userSearchFilter(term string) string {
if term == "" || i.userSearchFilterTemplate == "" {
return ""
}
return fmt.Sprintf(i.userSearchFilterTemplate, ldap.EscapeFilter(term))
}
func (i *LDAP) getUserByDN(dn, searchTerm string) (*ldap.Entry, error) {
baseFilter := fmt.Sprintf("(objectClass=%s)", i.userObjectClass)
@@ -532,16 +604,7 @@ func (i *LDAP) getUserByDN(dn, searchTerm string) (*ldap.Entry, error) {
if i.userFilter != "" {
userFilter = fmt.Sprintf("(%s)", i.userFilter)
}
searchFilter := ""
if searchTerm != "" {
searchTerm = ldap.EscapeFilter(searchTerm)
searchFilter = fmt.Sprintf(
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
i.userAttributeMap.userName, searchTerm,
i.userAttributeMap.mail, searchTerm,
i.userAttributeMap.displayName, searchTerm,
)
}
searchFilter := i.userSearchFilter(searchTerm)
filter := baseFilter
if userFilter != "" || searchFilter != "" {
@@ -752,6 +815,33 @@ 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 {
@@ -805,16 +895,7 @@ func (i *LDAP) FilterUsers(ctx context.Context, oreq *godata.GoDataRequest, filt
return nil, err
}
var userFilter string
if search != "" {
search = ldap.EscapeFilter(search)
userFilter = fmt.Sprintf(
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
i.userAttributeMap.userName, search,
i.userAttributeMap.mail, search,
i.userAttributeMap.displayName, search,
)
}
userFilter := i.userSearchFilter(search)
userFilter = fmt.Sprintf("(&%s(objectClass=%s)%s%s)", i.userFilter, i.userObjectClass, queryFilter, userFilter)
searchRequest := ldap.NewSearchRequest(
i.userBaseDN, i.userScope, ldap.NeverDerefAliases, 0, 0, false,
@@ -1152,7 +1233,7 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
i.userAttributeMap.displayName: {user.GetDisplayName()},
i.userAttributeMap.userName: {user.GetOnPremisesSamAccountName()},
i.userAttributeMap.mail: {user.GetMail()},
"objectClass": {"inetOrgPerson", "organizationalPerson", "person", "top", "ownCloudUser"},
"objectClass": append([]string{"inetOrgPerson", "organizationalPerson", "person", "top", "ownCloudUser"}, i.userAdditionalObjectClasses...),
"cn": {user.GetOnPremisesSamAccountName()},
i.userAttributeMap.userType: {user.GetUserType()},
}
@@ -1180,7 +1261,7 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
}
}
// inetOrgPerson requires "sn" to be set. Set it to the Username if
// inetOrgPerson/person require "sn" to be set. Set it to the Username if
// Surname is not set in the Request
var sn string
if user.Surname != nil && *user.Surname != "" {
@@ -1189,6 +1270,10 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
sn = user.OnPremisesSamAccountName
}
attrs[i.userAttributeMap.surname] = []string{sn}
if i.mirrorSurnameIntoSN() {
// person's mandatory "sn" is a separate attribute from the configured one above
attrs["sn"] = []string{sn}
}
// When we get a givenName, we set the attribute.
if givenName := user.GetGivenName(); givenName != "" {
@@ -1218,6 +1303,12 @@ func (i *LDAP) identityToLDAPAttrValue(identity libregraph.ObjectIdentity) (stri
return identityStr, nil
}
// mirrorSurnameIntoSN reports whether the configured surname attribute is not itself
// "sn", meaning person's mandatory "sn" must be kept in sync as a separate attribute.
func (i *LDAP) mirrorSurnameIntoSN() bool {
return i.userAttributeMap.surname != "sn"
}
func (i *LDAP) getUserAttrTypesForSearch() []string {
return []string{
i.userAttributeMap.displayName,
@@ -1237,7 +1328,12 @@ func (i *LDAP) getUserAttrTypesForSearch() []string {
}
func (i *LDAP) getUserAttrTypes() []string {
return append(i.getUserAttrTypesForSearch(), "cn", "userPassword", "objectClass")
types := append(i.getUserAttrTypesForSearch(), "cn", "objectClass")
if i.mirrorSurnameIntoSN() {
// userToLDAPAttrValues also mirrors surname into the literal "sn" person requires
types = append(types, "sn")
}
return types
}
func (i *LDAP) getUserLDAPDN(user libregraph.User) string {
@@ -1262,6 +1358,9 @@ func (i *LDAP) userToAddRequest(user libregraph.User) (*ldap.AddRequest, error)
ar.Attribute(attrType, values)
}
}
if values, ok := attrMap["userPassword"]; ok {
ar.Attribute("userPassword", values)
}
return ar, nil
}
@@ -1408,16 +1507,7 @@ func (i *LDAP) expandLDAPAttributeEntriesByUsername(ctx context.Context, e *ldap
logger.Debug().Str("backend", "ldap").Msg("ExpandLDAPAttributeEntries")
result := []*ldap.Entry{}
searchFilter := ""
if searchTerm != "" {
searchTerm = ldap.EscapeFilter(searchTerm)
searchFilter = fmt.Sprintf(
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
i.userAttributeMap.userName, searchTerm,
i.userAttributeMap.mail, searchTerm,
i.userAttributeMap.displayName, searchTerm,
)
}
searchFilter := i.userSearchFilter(searchTerm)
for _, entryUid := range e.GetEqualFoldAttributeValues(attribute) {
if entryUid == "" {
@@ -24,6 +24,8 @@ var eduConfig = config.LDAP{
UserIDAttribute: "entryUUID",
UserEmailAttribute: "mail",
UserNameAttribute: "uid",
UserSurnameAttribute: "sn",
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
UserEnabledAttribute: "userEnabledAttribute",
ExternalIDAttribute: "externalID",
DisableUserMechanism: "attribute",
@@ -317,6 +317,48 @@ func TestGetGroupsSearch(t *testing.T) {
t.Errorf("Expected zero length user slice")
}
}
func TestGetGroupMembersSearch_MemberUid(t *testing.T) {
memberUidConfig := lconfig
memberUidConfig.GroupMemberAttribute = "memberuid"
req, err := godata.ParseRequest(context.Background(), "",
url.Values{
"$search": []string{`"term"`},
},
)
if err != nil {
t.Errorf("Expected success got '%s'", err.Error())
}
group := ldap.NewEntry("cn=group", map[string][]string{
"cn": {"group"},
"entryuuid": {"abcd-defg"},
"memberuid": {"user"},
})
lm := &mocks.Client{}
lm.On("Search", mock.MatchedBy(
func(r *ldap.SearchRequest) bool {
return r.Filter == "(&(objectClass=groupOfNames)(|(cn=group)(entryUUID=group)))"
})).
Return(&ldap.SearchResult{Entries: []*ldap.Entry{group}}, nil)
lm.On("Search", mock.MatchedBy(
func(r *ldap.SearchRequest) bool {
return r.Filter == "(&(objectClass=inetOrgPerson)(&(|(uid=*term*)(displayname=*term*)(mail=*term*))(uid=user)))"
})).
Return(&ldap.SearchResult{}, nil)
b, _ := getMockedBackend(lm, memberUidConfig, &logger)
members, err := b.GetGroupMembers(context.Background(), "group", req)
if err != nil {
t.Errorf("Expected success, got '%s'", err.Error())
} else if len(members) != 0 {
t.Errorf("Expected zero length member slice")
}
lm.AssertExpectations(t)
}
func TestUpdateGroupName(t *testing.T) {
groupDn := "cn=TheGroup,ou=groups,dc=owncloud,dc=com"
@@ -18,6 +18,8 @@ var instanceMapperConfig = config.LDAP{
UserIDAttribute: "entryUUID",
UserEmailAttribute: "mail",
UserNameAttribute: "uid",
UserSurnameAttribute: "sn",
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
GroupBaseDN: "ou=groups,dc=test",
GroupObjectClass: "groupOfNames",
@@ -21,6 +21,7 @@ import (
"github.com/libregraph/idm/server/handler/boltdb"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
connldap "github.com/owncloud/reva/v2/pkg/utils/ldap"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
@@ -44,15 +45,28 @@ func init() {
idmConfig.UseServerUUID = false // boltdb does not auto-generate entryUUID; client must supply it
}
// restrictedSearchConfig narrows idmConfig's search attributes to name/surname/username.
func restrictedSearchConfig() config.LDAP {
cfg := idmConfig
cfg.UserSearchAttributes = []string{"onPremisesSamAccountName", "displayName", "surname"}
return cfg
}
// idmEntry builds a gldap.Entry matching idmConfig attribute names.
func idmEntry(uid, uuid string) *gldap.Entry {
func idmEntry(uid, uuid, mail string) *gldap.Entry {
return idmEntryWithSurname(uid, uuid, mail, uid)
}
// idmEntryWithSurname is idmEntry with an explicit surname, for tests that need it to
// differ from the uid (e.g. to isolate surname-only search matches).
func idmEntryWithSurname(uid, uuid, mail, surname string) *gldap.Entry {
dn := fmt.Sprintf("uid=%s,%s", uid, idmConfig.UserBaseDN)
return gldap.NewEntry(dn, map[string][]string{
idmConfig.UserNameAttribute: {uid},
idmConfig.UserDisplayNameAttribute: {"Display " + uid},
idmConfig.UserEmailAttribute: {uid + "@example.com"},
idmConfig.UserEmailAttribute: {mail},
idmConfig.UserIDAttribute: {uuid},
"sn": {uid},
"sn": {surname},
"givenname": {uid},
idmConfig.UserEnabledAttribute: {"TRUE"},
idmConfig.UserTypeAttribute: {"Member"},
@@ -102,6 +116,11 @@ func seedIDMDB(t *testing.T, dbfile string, entries ...*gldap.Entry) {
// newIDMBackend starts the libregraph/idm boltdb LDAP server and returns a wired LDAP identity backend.
func newIDMBackend(t *testing.T, entries ...*gldap.Entry) *LDAP {
t.Helper()
return newIDMBackendWithConfig(t, idmConfig, entries...)
}
func newIDMBackendWithConfig(t *testing.T, cfg config.LDAP, entries ...*gldap.Entry) *LDAP {
t.Helper()
dbfile := filepath.Join(t.TempDir(), "idm.db")
seedIDMDB(t, dbfile, entries...)
@@ -142,7 +161,7 @@ func newIDMBackend(t *testing.T, entries ...*gldap.Entry) *LDAP {
})
conn.SetLogger(&lgr.Logger)
backend, err := NewLDAPBackend(conn, idmConfig, &lgr, "", "")
backend, err := NewLDAPBackend(conn, cfg, &lgr, "", "")
require.NoError(t, err)
return backend
}
@@ -156,7 +175,7 @@ func odataReq(t *testing.T) *godata.GoDataRequest {
func TestIntegrationGetUser_HappyPath(t *testing.T) {
b := newIDMBackend(t,
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001"),
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com"),
)
user, err := b.GetUser(context.Background(), "alice", odataReq(t))
@@ -168,8 +187,8 @@ func TestIntegrationGetUser_HappyPath(t *testing.T) {
func TestIntegrationGetUsers_HappyPath(t *testing.T) {
b := newIDMBackend(t,
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001"),
idmEntry("bob", "bbbbbbbb-0000-0000-0000-000000000002"),
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com"),
idmEntry("bob", "bbbbbbbb-0000-0000-0000-000000000002", "bob@example.com"),
)
users, err := b.GetUsers(context.Background(), odataReq(t))
@@ -183,6 +202,74 @@ func TestIntegrationGetUsers_HappyPath(t *testing.T) {
assert.True(t, names["bob"])
}
func TestIntegrationGetUsers_SearchDoesNotMatchEmail(t *testing.T) {
// Gunda's mail contains "klaus" but her name, surname, and user-id don't.
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), gunda)
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
require.NoError(t, err)
users, err := b.GetUsers(context.Background(), req)
require.NoError(t, err)
assert.Empty(t, users, "a search config excluding mail must not match the mail attribute")
}
func TestIntegrationGetUsers_SearchMatchesEmailByDefault(t *testing.T) {
// same fixture as TestIntegrationGetUsers_SearchDoesNotMatchEmail, default config instead:
// existing deployments must keep matching by mail unless they opt into the narrower attribute list.
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
b := newIDMBackend(t, gunda)
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
require.NoError(t, err)
users, err := b.GetUsers(context.Background(), req)
require.NoError(t, err)
require.Len(t, users, 1, "the default config must still match the mail attribute")
assert.Equal(t, "ruetten", users[0].GetOnPremisesSamAccountName())
}
func TestIntegrationGetUsers_SearchMatchesAllowedAttributes(t *testing.T) {
// alice matches via userName/displayName (idmEntry default); carol only via surname.
alice := idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com")
carol := idmEntryWithSurname("carol", "eeeeeeee-0000-0000-0000-000000000005", "carol@example.com", "Winterbourne")
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), alice, carol)
aliceReq, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"alice"`}})
require.NoError(t, err)
aliceUsers, err := b.GetUsers(context.Background(), aliceReq)
require.NoError(t, err)
require.Len(t, aliceUsers, 1, "search must still match userName/displayName")
assert.Equal(t, "alice", aliceUsers[0].GetOnPremisesSamAccountName())
carolReq, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"Winterbourne"`}})
require.NoError(t, err)
carolUsers, err := b.GetUsers(context.Background(), carolReq)
require.NoError(t, err)
require.Len(t, carolUsers, 1, "a search config including surname must match surname")
assert.Equal(t, "carol", carolUsers[0].GetOnPremisesSamAccountName())
}
func TestIntegrationGetGroupMembers_SearchDoesNotMatchEmail(t *testing.T) {
// Same as TestIntegrationGetUsers_SearchDoesNotMatchEmail, via group-member search instead.
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
group := gldap.NewEntry(fmt.Sprintf("cn=%s,%s", "teachers", idmConfig.GroupBaseDN), map[string][]string{
"cn": {"teachers"},
"entryUUID": {"dddddddd-0000-0000-0000-000000000004"},
"member": {gunda.DN},
"objectClass": {"groupOfNames"},
})
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), gunda, group)
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
require.NoError(t, err)
members, err := b.GetGroupMembers(context.Background(), "teachers", req)
require.NoError(t, err)
assert.Empty(t, members, "a search config excluding mail must not match the mail attribute")
}
func TestIntegrationCreateUser_HappyPath(t *testing.T) {
b := newIDMBackend(t) // empty — no pre-seeded users
@@ -200,8 +287,28 @@ func TestIntegrationCreateUser_HappyPath(t *testing.T) {
assert.Equal(t, "charlie@example.com", created.GetMail())
}
func TestIntegrationCreateUser_MirrorsSurnameIntoLiteralSN(t *testing.T) {
cfg := idmConfig
cfg.UserSurnameAttribute = "customSurname"
b := newIDMBackendWithConfig(t, cfg)
newUser := libregraph.NewUser("Eve", "eve")
newUser.SetSurname("Example")
_, err := b.CreateUser(context.Background(), *newUser)
require.NoError(t, err)
sr := gldap.NewSearchRequest(cfg.UserBaseDN, gldap.ScopeWholeSubtree, gldap.NeverDerefAliases, 0, 0, false,
"(uid=eve)", []string{"sn", "customSurname"}, nil)
res, err := b.conn.Search(sr)
require.NoError(t, err)
require.Len(t, res.Entries, 1)
assert.Equal(t, "Example", res.Entries[0].GetEqualFoldAttributeValue("customSurname"))
// person's objectClass requires the literal "sn" to be set regardless of configuration
assert.Equal(t, "Example", res.Entries[0].GetEqualFoldAttributeValue("sn"))
}
func TestIntegrationDeleteUser_HappyPath(t *testing.T) {
entry := idmEntry("dave", "dddddddd-0000-0000-0000-000000000004")
entry := idmEntry("dave", "dddddddd-0000-0000-0000-000000000004", "dave@example.com")
b := newIDMBackend(t, entry)
// Confirm user exists first.
+98 -13
View File
@@ -35,6 +35,8 @@ var lconfig = config.LDAP{
UserIDAttribute: "entryUUID",
UserEmailAttribute: "mail",
UserNameAttribute: "uid",
UserSurnameAttribute: "sn",
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
UserEnabledAttribute: "userEnabledAttribute",
UserTypeAttribute: "userTypeAttribute",
ExternalIDAttribute: "externalID",
@@ -119,6 +121,18 @@ func TestNewLDAPBackend(t *testing.T) {
if _, err := NewLDAPBackend(l, lconfig, &logger, "", ""); err != nil {
t.Errorf("Should fail with invalid group search scope")
}
tc = lconfig
tc.UserSearchAttributes = nil
if _, err := NewLDAPBackend(l, tc, &logger, "", ""); err == nil {
t.Error("Should fail with no user search attributes configured")
}
tc = lconfig
tc.UserSearchAttributes = []string{"notARealAttribute"}
if _, err := NewLDAPBackend(l, tc, &logger, "", ""); err != nil {
t.Errorf("Should accept an unrecognized name as a literal LDAP attribute: %v", err)
}
}
func TestCreateUser(t *testing.T) {
@@ -224,6 +238,59 @@ 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{}
@@ -327,7 +394,6 @@ func TestGetUsers(t *testing.T) {
}
func TestGetUsersSearch(t *testing.T) {
lm := &mocks.Client{}
odataReqDefault, err := godata.ParseRequest(context.Background(), "",
url.Values{
"$search": []string{"\"term\""},
@@ -337,19 +403,38 @@ func TestGetUsersSearch(t *testing.T) {
t.Errorf("Expected success got '%s'", err.Error())
}
// only match if the filter contains the search term unquoted
lm.On("Search", mock.MatchedBy(
func(req *ldap.SearchRequest) bool {
return req.Filter == "(&(objectClass=inetOrgPerson)(|(uid=*term*)(mail=*term*)(displayname=*term*)))"
})).
Return(&ldap.SearchResult{}, nil)
b, _ := getMockedBackend(lm, lconfig, &logger)
g, err := b.GetUsers(context.Background(), odataReqDefault)
if err != nil {
t.Errorf("Expected success, got '%s'", err.Error())
} else if g == nil || len(g) != 0 {
t.Errorf("Expected zero length user slice")
assertSearchFilter := func(t *testing.T, cfg config.LDAP, wantFilter string) {
lm := &mocks.Client{}
// only match if the filter contains the search term unquoted
lm.On("Search", mock.MatchedBy(
func(req *ldap.SearchRequest) bool {
return req.Filter == wantFilter
})).
Return(&ldap.SearchResult{}, nil)
b, _ := getMockedBackend(lm, cfg, &logger)
g, err := b.GetUsers(context.Background(), odataReqDefault)
if err != nil {
t.Errorf("Expected success, got '%s'", err.Error())
} else if g == nil || len(g) != 0 {
t.Errorf("Expected zero length user slice")
}
}
t.Run("default config matches userName, displayName and mail", func(t *testing.T) {
assertSearchFilter(t, lconfig, "(&(objectClass=inetOrgPerson)(|(uid=*term*)(displayname=*term*)(mail=*term*)))")
})
t.Run("a config excluding mail matches surname instead", func(t *testing.T) {
restrictedConfig := lconfig
restrictedConfig.UserSearchAttributes = []string{"onPremisesSamAccountName", "displayName", "surname"}
assertSearchFilter(t, restrictedConfig, "(&(objectClass=inetOrgPerson)(|(uid=*term*)(displayname=*term*)(sn=*term*)))")
})
t.Run("a literal '%' in a configured attribute name does not corrupt the filter", func(t *testing.T) {
percentConfig := lconfig
percentConfig.UserNameAttribute = "uid%"
assertSearchFilter(t, percentConfig, "(&(objectClass=inetOrgPerson)(|(uid%=*term*)(displayname=*term*)(mail=*term*)))")
})
}
func TestUpdateUser(t *testing.T) {
@@ -707,6 +707,72 @@ 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,6 +73,7 @@ type DriveItemPermissionsService struct {
tp trace.TracerProvider
identityBackend identity.Backend
hasExternalSharePermission externalSharePermissionChecker
createVaultShare vaultShareCreator
}
type permissionType int
@@ -88,12 +89,20 @@ 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) (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, vsc vaultShareCreator) (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{
@@ -105,6 +114,7 @@ func NewDriveItemPermissionsService(logger log.Logger, gatewaySelector pool.Sele
tp: tp,
identityBackend: be,
hasExternalSharePermission: f,
createVaultShare: c,
}, nil
}
@@ -275,8 +285,20 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
if shareExpiration != nil {
createShareRequest.GetGrant().Expiration = shareExpiration
}
createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest)
if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil {
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 {
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)
svc, err = service.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, 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)
service, err := svc.NewDriveItemPermissionsService(logger, gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil, nil)
Expect(err).ToNot(HaveOccurred())
driveItemPermissionsService = service
ctx = revactx.ContextSetUser(context.Background(), currentUser)
@@ -174,6 +174,80 @@ 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,
@@ -385,7 +459,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)
service, err := svc.NewDriveItemPermissionsService(log.NewLogger(), gatewaySelector, cache, cfg, otel.GetTracerProvider(), nil, nil, nil)
Expect(err).ToNot(HaveOccurred())
driveItemInvite.Roles = []string{unifiedrole.UnifiedRoleViewerID, unifiedrole.UnifiedRoleSecureViewerID}
@@ -1,6 +1,13 @@
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,6 +59,7 @@ type Graph struct {
identityBackend identity.Backend
identityEducationBackend identity.EducationBackend
roleService RoleService
guestRoleMapping []guestRoleMapping
permissionsService Permissions
valueService settingssvc.ValueService
specialDriveItemsCache *ttlcache.Cache[string, interface{}]
@@ -0,0 +1,204 @@
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
}
@@ -67,6 +67,8 @@ var _ = Describe("Users changing their own password", func() {
WriteEnabled: true,
UserDisplayNameAttribute: "displayName",
UserNameAttribute: "uid",
UserSurnameAttribute: "sn",
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
UserEmailAttribute: "mail",
UserIDAttribute: "ownCloudUUID",
UserSearchScope: "sub",
+13 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
"slices"
"strconv"
"time"
@@ -190,6 +191,12 @@ 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{
@@ -227,7 +234,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)
driveItemPermissionsService, err := NewDriveItemPermissionsService(options.Logger, options.GatewaySelector, identityCache, options.Config, options.TraceProvider, svc.identityBackend, svc.contextUserHasExternalSharePermission, svc.withGuestVaultRole)
if err != nil {
return svc, err
}
@@ -442,6 +449,11 @@ func setIdentityBackends(options Options, svc *Graph) error {
if options.IdentityBackend == nil {
switch options.Config.Identity.Backend {
case "cs3":
// the cs3 backend has no attribute-scoped search filter of its own; this config
// only takes effect on the ldap backend
if !slices.Contains(options.Config.Identity.LDAP.UserSearchAttributes, "mail") {
options.Logger.Warn().Msg("GRAPH_LDAP_USER_SEARCH_ATTRIBUTES excludes mail but has no effect with GRAPH_IDENTITY_BACKEND=cs3; user search may still match by mail")
}
gatewaySelector, err := pool.GatewaySelector(
options.Config.Reva.Address,
append(
@@ -282,6 +282,28 @@ func (g Graph) applyFilterVaultEligible(ctx context.Context, req *godata.GoDataR
if err != nil {
return nil, err
}
// 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() {
found = true
break
}
}
if !found {
users = append(users, preciseUser)
}
}
}
if len(users) == 0 {
return users, nil
}
@@ -315,6 +337,13 @@ 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
+458 -5
View File
@@ -13,6 +13,8 @@ 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"
@@ -20,14 +22,18 @@ 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"
@@ -35,6 +41,7 @@ import (
"github.com/owncloud/ocis/v2/services/graph/mocks"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
"github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults"
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
identitymocks "github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks"
service "github.com/owncloud/ocis/v2/services/graph/pkg/service/v0"
)
@@ -710,8 +717,7 @@ var _ = Describe("Users", func() {
}, nil)
})
// None of these reach GetPreciseUser: a filter, a non-matching search, no search at
// all, or missing permission each independently keep it from firing.
// vaultEligible is excluded here; it does reach GetPreciseUser — see "the vaultEligible filter, with a cross-instance match" below
DescribeTable("does not resolve via GetPreciseUser",
func(search string, filter string, permissionGranted bool, needsMFA bool) {
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
@@ -744,8 +750,8 @@ var _ = Describe("Users", func() {
Expect(rr.Code).To(Equal(http.StatusOK))
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
},
Entry("filter present, even though the search string also matches the cross-instance pattern",
`"student@other-instance.example.test"`, "vaultEligible eq true", true, false),
Entry("a non-vaultEligible filter is present, even though the search string also matches the cross-instance pattern",
`"student@other-instance.example.test"`, "userType eq 'Member'", true, false),
Entry("search string doesn't match the cross-instance pattern",
`"not-a-cross-instance-string"`, "", true, false),
Entry("no $search present at all",
@@ -782,6 +788,9 @@ var _ = Describe("Users", func() {
ineligible.SetId(otherUser)
identityBackend.On("GetUsers", mock.Anything, mock.Anything).
Return([]*libregraph.User{eligible, ineligible}, nil)
// no cross-instance account behind this reference; GetPreciseUser finds nothing
identityBackend.On("GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(nil, identity.ErrNotFound)
expectRoles()
expectAssignments(eligibleUser, []*settingsmsg.UserRoleAssignment{
@@ -807,7 +816,451 @@ var _ = Describe("Users", func() {
ids = append(ids, u.GetId())
}
Expect(ids).To(ConsistOf(eligibleUser))
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
})
Describe("the vaultEligible filter, with a cross-instance match", func() {
const crossInstanceUser = "cross-instance-user"
It("includes a cross-instance match that holds the vault-granting role", func() {
crossInstance := &libregraph.User{}
crossInstance.SetId(crossInstanceUser)
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
identityBackend.On("GetPreciseUser", mock.Anything, "teacher", "school5", mock.Anything).
Return(crossInstance, nil)
expectRoles()
expectAssignments(crossInstanceUser, []*settingsmsg.UserRoleAssignment{
{Id: "assignment-ID", AccountUuid: crossInstanceUser, RoleId: vaultRole},
}, nil)
r := httptest.NewRequest(http.MethodGet,
"/graph/v1.0/users?$search="+url.QueryEscape(`"teacher@school5.example.test"`)+
"&$filter="+url.QueryEscape("vaultEligible eq true"), nil)
svc.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())
Expect(res.Value).To(HaveLen(1))
Expect(res.Value[0].GetId()).To(Equal(crossInstanceUser))
})
It("excludes a cross-instance match that lacks the vault-granting role", func() {
crossInstance := &libregraph.User{}
crossInstance.SetId(crossInstanceUser)
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
identityBackend.On("GetPreciseUser", mock.Anything, "student", "school5", mock.Anything).
Return(crossInstance, nil)
expectRoles()
expectAssignments(crossInstanceUser, nil, nil)
r := httptest.NewRequest(http.MethodGet,
"/graph/v1.0/users?$search="+url.QueryEscape(`"student@school5.example.test"`)+
"&$filter="+url.QueryEscape("vaultEligible eq true"), nil)
svc.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())
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)
})
})
+2 -16
View File
@@ -21,7 +21,7 @@ type Config struct {
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"GROUPS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"GROUPS_DRIVER" desc:"The driver which should be used by the groups service. Supported values are 'ldap' and 'owncloudsql'." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"GROUPS_DRIVER" desc:"The driver which should be used by the groups service. Supported value is 'ldap'." introductionVersion:"pre5.0"`
Drivers Drivers `yaml:"drivers"`
Context context.Context `yaml:"-"`
@@ -53,8 +53,7 @@ type GRPCConfig struct {
}
type Drivers struct {
LDAP LDAPDriver `yaml:"ldap"`
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
LDAP LDAPDriver `yaml:"ldap"`
JSON JSONDriver `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
REST RESTProvider `yaml:"rest,omitempty"` // not supported by the oCIS product, therefore not part of docs
@@ -107,19 +106,6 @@ type LDAPGroupSchema struct {
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;GROUPS_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
}
type OwnCloudSQLDriver struct {
DBUsername string `yaml:"db_username" env:"GROUPS_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
DBPassword string `yaml:"db_password" env:"GROUPS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
DBHost string `yaml:"db_host" env:"GROUPS_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
DBPort int `yaml:"db_port" env:"GROUPS_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
DBName string `yaml:"db_name" env:"GROUPS_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
IDP string `yaml:"idp" env:"GROUPS_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
Nobody int64 `yaml:"nobody" env:"GROUPS_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
JoinUsername bool `yaml:"join_username" env:"GROUPS_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames." introductionVersion:"pre5.0"`
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"GROUPS_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user IDs." introductionVersion:"pre5.0"`
EnableMedialSearch bool `yaml:"enable_medial_search" env:"GROUPS_OWNCLOUDSQL_ENABLE_MEDIAL_SEARCH" desc:"Allow 'medial search' when searching for users instead of just doing a prefix search. This allows finding 'Alice' when searching for 'lic'." introductionVersion:"pre5.0"`
}
type JSONDriver struct {
File string
}
@@ -72,18 +72,6 @@ func DefaultConfig() *config.Config {
Member: "member",
},
},
OwnCloudSQL: config.OwnCloudSQLDriver{
DBUsername: "owncloud",
DBPassword: "",
DBHost: "mysql",
DBPort: 3306,
DBName: "owncloud",
IDP: "https://localhost:9200",
Nobody: 90,
JoinUsername: false,
JoinOwnCloudUUID: false,
EnableMedialSearch: false,
},
},
}
}
+6
View File
@@ -251,6 +251,11 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
rolesClient := settingssvc.NewRoleService("com.owncloud.api.settings", cfg.GrpcClient)
policiesProviderClient := policiessvc.NewPoliciesProviderService("com.owncloud.api.policies", cfg.GrpcClient)
guestRoleMapping, err := userroles.GuestRoleMapping(cfg)
if err != nil {
logger.Fatal().Err(err).Msg("Invalid guest role mapping")
}
var roleAssigner userroles.UserRoleAssigner
switch cfg.RoleAssignment.Driver {
case "default":
@@ -264,6 +269,7 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
userroles.WithLogger(logger),
userroles.WithRolesClaim(cfg.RoleAssignment.OIDCRoleMapper.RoleClaim),
userroles.WithRoleMapping(cfg.RoleAssignment.OIDCRoleMapper.RolesMap),
userroles.WithGuestRoleMapping(guestRoleMapping),
userroles.WithRevaGatewaySelector(gatewaySelector),
userroles.WithServiceAccount(cfg.ServiceAccount),
)
+7 -6
View File
@@ -259,10 +259,11 @@ type ClaimSpaceManagement 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." introductionVersion:"8.1.0"`
MemberClaim string `yaml:"member_claim" env:"OCIS_MULTI_INSTANCE_MEMBER_CLAIM" desc:"The claim name for the 'memberOf' property" introductionVersion:"8.0.0"`
GuestClaim string `yaml:"guest_claim" env:"OCIS_MULTI_INSTANCE_GUEST_CLAIM" desc:"The claim name for the 'guestOf' property" introductionVersion:"8.0.0"`
GuestRole string `yaml:"guest_role" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE" desc:"The role that should be assigned to a guest user" introductionVersion:"8.0.0"`
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." introductionVersion:"8.1.0"`
MemberClaim string `yaml:"member_claim" env:"OCIS_MULTI_INSTANCE_MEMBER_CLAIM" desc:"The claim name for the 'memberOf' property" introductionVersion:"8.0.0"`
GuestClaim string `yaml:"guest_claim" env:"OCIS_MULTI_INSTANCE_GUEST_CLAIM" desc:"The claim name for the 'guestOf' property" introductionVersion:"8.0.0"`
GuestRole string `yaml:"guest_role" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE" desc:"The role that should be assigned to a guest user" introductionVersion:"8.0.0"`
GuestRoleMapping []string `yaml:"guest_role_mapping" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING" desc:"(Optional) Mapping of PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM values to the role a guest gets instead of OCIS_MULTI_INSTANCE_GUEST_ROLE. Example: 'spaceadmin:user-light-vault'. A claim value is an exact string or a regular expression that must match the full claim value, the same as the claim_value of the role mapping. Escape regex metacharacters such as '.' in an exact string. The first match wins. Role names must not contain a colon. Only applies to the 'oidc' role assignment driver." introductionVersion:"9.0.0"`
}
+110 -16
View File
@@ -3,16 +3,18 @@ package userroles
import (
"context"
"errors"
"regexp"
"fmt"
"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"
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/utils"
"go-micro.dev/v4/metadata"
@@ -79,16 +81,9 @@ 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 {
if _, ok := claimRoles[mappingValue]; ok {
return true
}
rx, err := regexp.Compile("^(?:" + mappingValue + ")$")
if err != nil {
return false
}
m := rolemapping.NewMatcher(mappingValue)
for cr := range claimRoles {
if rx.MatchString(cr) {
if m.Matches(cr) {
return true
}
}
@@ -100,12 +95,21 @@ func matchesClaimMapping(mappingValue string, claimRoles map[string]struct{}) bo
func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *cs3user.User, claims map[string]interface{}, overwriteRole string) (*cs3user.User, error) {
userID := user.GetId().GetOpaqueId()
logger := ra.logger.SubloggerWithRequestID(ctx).With().Str("userid", userID).Logger()
roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx)
roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx, roleCacheTTL)
if err != nil {
logger.Error().Err(err).Msg("Error mapping role names to role ids")
return nil, err
}
// the account resolver passes the guest role as overwriteRole for multi-instance guests
if overwriteRole != "" {
overwriteRole, roleNamesToRoleIDs, err = ra.guestRoleName(ctx, claims, overwriteRole, roleNamesToRoleIDs)
if err != nil {
logger.Error().Err(err).Msg("Error mapping guest role")
return nil, err
}
}
roleIDFromClaim := roleNamesToRoleIDs[overwriteRole]
if overwriteRole == "" {
claimRoles, err := extractRoles(ra.rolesClaim, claims)
@@ -174,7 +178,7 @@ func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *c
return nil, err
}
// TODO: check if it's ctx or newctx
// TODO: check if it's ctx or newctx
canCreateDrives, err := utils.CheckPermission(revactx.ContextSetUser(ctx, user), "Drives.Create", client)
if err != nil {
// The permission could not be determined. Fail closed: leave the personal
@@ -205,6 +209,88 @@ 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.
func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) {
pairs := cfg.MultiInstance.GuestRoleMapping
if len(pairs) > 0 && cfg.RoleAssignment.Driver != "oidc" {
return nil, fmt.Errorf("the guest role mapping requires the 'oidc' role assignment driver, not '%s'", cfg.RoleAssignment.Driver)
}
// the role assigner only applies the mapping to users that get the guest role
if len(pairs) > 0 && cfg.MultiInstance.GuestRole == "" {
return nil, errors.New("the guest role mapping requires OCIS_MULTI_INSTANCE_GUEST_ROLE")
}
mappings := make([]config.RoleMapping, 0, len(pairs))
for _, pair := range pairs {
claimValue, roleName, err := rolemapping.ParsePair(pair)
if err != nil {
return nil, err
}
mappings = append(mappings, config.RoleMapping{ClaimValue: claimValue, RoleName: roleName})
}
return mappings, nil
}
// guestRoleName returns the role name of a multi-instance guest and the role name to role id map
// that knows this role. A role that the cached map does not know can be a new role, so
// guestRoleName reads the roles again one time. An unknown role is an error: do not assign an
// empty role id.
func (ra oidcRoleAssigner) guestRoleName(ctx context.Context, claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, map[string]string, error) {
resolve := func(roleNamesToRoleIDs map[string]string) (string, error) {
roleName := guestRole
if len(ra.guestMapping) > 0 {
var err error
if roleName, err = ra.mapGuestRole(claims, guestRole, roleNamesToRoleIDs); err != nil {
return "", err
}
}
if _, ok := roleNamesToRoleIDs[roleName]; !ok {
return "", fmt.Errorf("unknown role '%s'", roleName)
}
return roleName, nil
}
roleName, err := resolve(roleNamesToRoleIDs)
if err == nil {
return roleName, roleNamesToRoleIDs, nil
}
// the minimum age limits the reads for a role that does not exist
roleNamesToRoleIDs, rerr := ra.roleNamesToRoleIDs(ctx, roleCacheMinAge)
if rerr != nil {
return "", nil, rerr
}
roleName, err = resolve(roleNamesToRoleIDs)
if err != nil {
return "", nil, err
}
return roleName, roleNamesToRoleIDs, nil
}
// mapGuestRole returns the role of the first guest role mapping that matches a value of the
// user's roles claim, or guestRole when nothing matches. A mapping to a role that does not exist
// is an error: it can only be a misconfiguration, and falling back to guestRole could give the
// guest more permissions than the mapped role was meant to.
func (ra oidcRoleAssigner) mapGuestRole(claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, error) {
claimRoles, err := extractRoles(ra.rolesClaim, claims)
if err != nil || len(claimRoles) == 0 {
// a guest without roles claim is valid, log at debug level to help find a wrong claim name
ra.logger.Debug().Err(err).Str("claim", ra.rolesClaim).Msg("no roles in claim, the guest keeps the guest role")
return guestRole, nil
}
for _, mapping := range ra.guestMapping {
if !matchesClaimMapping(mapping.ClaimValue, claimRoles) {
continue
}
if _, ok := roleNamesToRoleIDs[mapping.RoleName]; !ok {
return "", fmt.Errorf("guest role mapping '%s' points to the unknown role '%s'", mapping.ClaimValue, mapping.RoleName)
}
return mapping.RoleName, nil
}
return guestRole, nil
}
// ApplyUserRole it looks up the user's role in the settings service and adds it
// user's opaque data
func (ra oidcRoleAssigner) ApplyUserRole(ctx context.Context, user *cs3user.User) (*cs3user.User, error) {
@@ -242,11 +328,19 @@ type roleNameToIDCache struct {
var roleNameToID roleNameToIDCache
func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]string, error) {
cacheTTL := 5 * time.Minute
const (
// roleCacheTTL is the maximum age of the cached role name to role id map
roleCacheTTL = 5 * time.Minute
// roleCacheMinAge is the age that the cached map must have before a read for an unknown role
roleCacheMinAge = 30 * time.Second
)
// roleNamesToRoleIDs returns the cached role name to role id map. When the map is older than
// maxAge, roleNamesToRoleIDs reads the roles from the settings service.
func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context, maxAge time.Duration) (map[string]string, error) {
roleNameToID.lock.RLock()
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL {
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge {
defer roleNameToID.lock.RUnlock()
return roleNameToID.roleNameToID, nil
}
@@ -258,7 +352,7 @@ func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]s
defer roleNameToID.lock.Unlock()
// check again, another goroutine might have updated while we "upgraded" the lock
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL {
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge {
return roleNameToID.roleNameToID, nil
}
@@ -3,6 +3,8 @@ package userroles
import (
"context"
"encoding/json"
"reflect"
"strings"
"testing"
"time"
@@ -270,3 +272,377 @@ func TestUpdateUserRoleAssignmentFailsClosedOnInconclusivePermission(t *testing.
return req.GetRoleId() == oldRoleID
}), mock.Anything)
}
func TestMapGuestRole(t *testing.T) {
roleIDs := map[string]string{"user-light": "user-light-id", "user-light-vault": "user-light-vault-id"}
spaceAdminMapping := []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}}
tests := []struct {
name string
mapping []config.RoleMapping
roleIDs map[string]string
claims map[string]interface{}
want string
wantErr bool
}{
{
name: "spaceadmin gets the mapped role",
mapping: spaceAdminMapping,
roleIDs: roleIDs,
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
want: "user-light-vault",
},
{
name: "spaceadmin with more claim values gets the mapped role",
mapping: spaceAdminMapping,
roleIDs: roleIDs,
claims: map[string]interface{}{"roles": []interface{}{"user", "spaceadmin"}},
want: "user-light-vault",
},
{
name: "user keeps the guest role",
mapping: spaceAdminMapping,
roleIDs: roleIDs,
claims: map[string]interface{}{"roles": []interface{}{"user"}},
want: "user-light",
},
{
name: "guest without roles claim keeps the guest role",
mapping: spaceAdminMapping,
roleIDs: roleIDs,
claims: map[string]interface{}{"sub": "someone"},
want: "user-light",
},
{
name: "mapping to an unknown role is an error",
mapping: spaceAdminMapping,
roleIDs: map[string]string{"user-light": "user-light-id"},
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
wantErr: true,
},
{
name: "unknown role of a non-matching mapping is no error",
mapping: spaceAdminMapping,
roleIDs: map[string]string{"user-light": "user-light-id"},
claims: map[string]interface{}{"roles": []interface{}{"user"}},
want: "user-light",
},
{
name: "first matching mapping wins",
mapping: []config.RoleMapping{
{ClaimValue: "spaceadmin", RoleName: "user-light-vault"},
{ClaimValue: ".*", RoleName: "user-light"},
},
roleIDs: roleIDs,
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
want: "user-light-vault",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ra := oidcRoleAssigner{Options: Options{rolesClaim: "roles", guestMapping: tt.mapping}}
got, err := ra.mapGuestRole(tt.claims, "user-light", tt.roleIDs)
if tt.wantErr {
if err == nil {
t.Fatalf("expected an error, got role %q", got)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tt.want {
t.Fatalf("got role %q, want %q", got, tt.want)
}
})
}
}
// TestUpdateUserRoleAssignmentMapsGuestRole verifies that a guest who already holds the
// guest role is moved to the role the guest role mapping picks for their claims, which is
// how guests invited before the mapping was configured get the new role on their next login.
func TestUpdateUserRoleAssignmentMapsGuestRole(t *testing.T) {
const (
guestRoleID = "user-light-id"
vaultRoleID = "user-light-vault-id"
userOpaqueID = "user-1"
)
// reset the package-global role-name cache so this test is deterministic
roleNameToID.lock.Lock()
roleNameToID.roleNameToID = nil
roleNameToID.lastRead = time.Time{}
roleNameToID.lock.Unlock()
gatewayClient := &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Token: "service-token",
}, nil)
// like the guest role, the mapped role can't create drives, so the assigner disables
// the (here non-existent) personal space
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(&permissions.CheckPermissionResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED},
}, nil)
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
}, nil)
roleService := &graphmocks.RoleService{}
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{
{Id: guestRoleID, Name: "user-light"},
{Id: vaultRoleID, Name: "user-light-vault"},
}}, nil)
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{
{Id: "guest-assignment-id", AccountUuid: userOpaqueID, RoleId: guestRoleID},
}}, nil)
roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.AssignRoleToUserResponse{Assignment: &settingsmsg.UserRoleAssignment{
Id: "vault-assignment-id",
AccountUuid: userOpaqueID,
RoleId: vaultRoleID,
}}, nil)
ra := oidcRoleAssigner{Options: Options{
logger: log.NopLogger(),
gatewaySelector: gatewaySelector,
roleService: roleService,
rolesClaim: "roles",
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
}}
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID}}
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
if _, err := ra.UpdateUserRoleAssignment(context.Background(), user, claims, "user-light"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
roleService.AssertCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == vaultRoleID
}), mock.Anything)
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
return req.GetRoleId() == guestRoleID
}), mock.Anything)
}
// TestUpdateUserRoleAssignmentFailsOnUnknownGuestRole verifies that a guest role mapping that
// points to a role which does not exist fails the role assignment instead of silently assigning
// the guest role.
func TestUpdateUserRoleAssignmentFailsOnUnknownGuestRole(t *testing.T) {
// reset the package-global role-name cache so this test is deterministic
roleNameToID.lock.Lock()
roleNameToID.roleNameToID = nil
roleNameToID.lastRead = time.Time{}
roleNameToID.lock.Unlock()
gatewayClient := &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
// listing the roles needs a service account context
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Token: "service-token",
}, nil)
roleService := &graphmocks.RoleService{}
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{{Id: "user-light-id", Name: "user-light"}}}, nil)
ra := oidcRoleAssigner{Options: Options{
logger: log.NopLogger(),
gatewaySelector: gatewaySelector,
roleService: roleService,
rolesClaim: "roles",
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
}}
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: "user-1"}}
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
_, err := ra.UpdateUserRoleAssignment(context.Background(), user, claims, "user-light")
if err == nil || !strings.Contains(err.Error(), "unknown role 'user-light-vault'") {
t.Fatalf("expected an error for the guest role mapping to an unknown role, got %v", err)
}
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
// a guest that no mapping matches gets the guest role, which must exist too
claims = map[string]interface{}{"roles": []interface{}{"user"}}
_, err = ra.UpdateUserRoleAssignment(context.Background(), user, claims, "no-such-guest-role")
if err == nil || !strings.Contains(err.Error(), "unknown role 'no-such-guest-role'") {
t.Fatalf("expected an error for an unknown guest role, got %v", err)
}
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
}
func TestGuestRoleMapping(t *testing.T) {
tests := []struct {
name string
driver string
// noGuestRole leaves OCIS_MULTI_INSTANCE_GUEST_ROLE empty
noGuestRole bool
pairs []string
want []config.RoleMapping
wantErr bool
}{
{
name: "empty",
driver: "default",
pairs: nil,
want: []config.RoleMapping{},
},
{
name: "pairs keep their order",
driver: "oidc",
pairs: []string{"spaceadmin:user-light-vault", "admin:guest-admin"},
want: []config.RoleMapping{
{ClaimValue: "spaceadmin", RoleName: "user-light-vault"},
{ClaimValue: "admin", RoleName: "guest-admin"},
},
},
{
name: "claim value may contain colons",
driver: "oidc",
pairs: []string{"urn:ocis:spaceadmin:user-light-vault"},
want: []config.RoleMapping{{ClaimValue: "urn:ocis:spaceadmin", RoleName: "user-light-vault"}},
},
{
name: "spaces around the claim value and the role name are trimmed",
driver: "oidc",
pairs: []string{" spaceadmin : user-light-vault "},
want: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
},
{name: "requires the oidc driver", driver: "default", pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true},
{name: "requires a guest role", driver: "oidc", noGuestRole: true, pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true},
{name: "missing colon", driver: "oidc", pairs: []string{"spaceadmin"}, wantErr: true},
{name: "missing claim value", driver: "oidc", pairs: []string{":user-light-vault"}, wantErr: true},
{name: "missing role name", driver: "oidc", pairs: []string{"spaceadmin:"}, wantErr: true},
{name: "blank claim value", driver: "oidc", pairs: []string{" :user-light-vault"}, wantErr: true},
{name: "blank role name", driver: "oidc", pairs: []string{"spaceadmin: "}, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
guestRole := "user-light"
if tt.noGuestRole {
guestRole = ""
}
cfg := &config.Config{
RoleAssignment: config.RoleAssignment{Driver: tt.driver},
MultiInstance: config.MultiInstanceConfig{GuestRole: guestRole, GuestRoleMapping: tt.pairs},
}
got, err := GuestRoleMapping(cfg)
if tt.wantErr {
if err == nil {
t.Fatalf("expected an error for %v", tt.pairs)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Fatalf("got %v, want %v", got, tt.want)
}
})
}
}
// TestGuestRoleNameRefreshesRoles verifies that a role which the cached role map does not know
// makes the assigner read the roles again, so a new role works before the cache TTL ends. The
// assigner reads the roles again only when the cached map is older than roleCacheMinAge.
func TestGuestRoleNameRefreshesRoles(t *testing.T) {
gatewayClient := &cs3mocks.GatewayAPIClient{}
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return gatewayClient
},
)
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
// listing the roles needs a service account context
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
Token: "service-token",
}, nil)
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
cached := map[string]string{"user-light": "user-light-id"}
tests := []struct {
name string
cacheAge time.Duration
wantRole string
wantErr bool
wantReads int
}{
{name: "an old cache is read again", cacheAge: time.Minute, wantRole: "user-light-vault", wantReads: 1},
{name: "a fresh cache is not read again", cacheAge: 0, wantErr: true, wantReads: 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
roleNameToID.lock.Lock()
roleNameToID.roleNameToID = cached
roleNameToID.lastRead = time.Now().Add(-tt.cacheAge)
roleNameToID.lock.Unlock()
roleService := &graphmocks.RoleService{}
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{
{Id: "user-light-id", Name: "user-light"},
{Id: "user-light-vault-id", Name: "user-light-vault"},
}}, nil)
ra := oidcRoleAssigner{Options: Options{
logger: log.NopLogger(),
gatewaySelector: gatewaySelector,
roleService: roleService,
rolesClaim: "roles",
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
}}
got, roleIDs, err := ra.guestRoleName(context.Background(), claims, "user-light", cached)
roleService.AssertNumberOfCalls(t, "ListRoles", tt.wantReads)
if tt.wantErr {
if err == nil || !strings.Contains(err.Error(), "unknown role 'user-light-vault'") {
t.Fatalf("expected an unknown role error, got role %q and error %v", got, err)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tt.wantRole || roleIDs[got] != "user-light-vault-id" {
t.Fatalf("got role %q with id %q, want %q", got, roleIDs[got], tt.wantRole)
}
})
}
// reset the package-global role-name cache for the other tests
roleNameToID.lock.Lock()
roleNameToID.roleNameToID = nil
roleNameToID.lastRead = time.Time{}
roleNameToID.lock.Unlock()
}
@@ -31,6 +31,7 @@ type Options struct {
roleService settingssvc.RoleService
rolesClaim string
roleMapping []config.RoleMapping
guestMapping []config.RoleMapping
serviceAccount config.ServiceAccount
logger log.Logger
}
@@ -66,6 +67,13 @@ func WithRoleMapping(roleMap []config.RoleMapping) Option {
}
}
// WithGuestRoleMapping configures the map of ocis role names to claim values for multi-instance guests
func WithGuestRoleMapping(roleMap []config.RoleMapping) Option {
return func(o *Options) {
o.guestMapping = roleMap
}
}
// WithRevaGatewaySelector set the gatewaySelector option
func WithRevaGatewaySelector(selectable pool.Selectable[gateway.GatewayAPIClient]) Option {
return func(o *Options) {
+2
View File
@@ -5,6 +5,8 @@ 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,6 +9,10 @@ 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()
@@ -46,6 +50,7 @@ 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,6 +2,7 @@ package parser
import (
"errors"
"fmt"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
@@ -44,6 +45,10 @@ 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
}
@@ -0,0 +1,44 @@
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)
})
}
}
@@ -0,0 +1,9 @@
package search
import "time"
// SetExtractionRetryDelay shortens the delay between extraction retries for a
// test.
func (s *Service) SetExtractionRetryDelay(d time.Duration) {
s.extractionRetryDelay = d
}
+25 -9
View File
@@ -23,6 +23,17 @@ 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() {
@@ -37,9 +48,16 @@ func ResolveReference(ctx context.Context, ref *provider.Reference, ri *provider
gpRes, err := gatewayClient.GetPath(ctx, &provider.GetPathRequest{
ResourceId: ri.GetId(),
})
if err != nil || gpRes.GetStatus().GetCode() != rpc.Code_CODE_OK {
if err != nil {
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(),
@@ -80,7 +98,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], logger log.Logger) (*provider.StatResponse, error) {
func statResource(ctx context.Context, ref *provider.Reference, gatewaySelector pool.Selectable[gateway.GatewayAPIClient]) (*provider.StatResponse, error) {
gatewayClient, err := gatewaySelector.Next()
if err != nil {
return nil, err
@@ -88,19 +106,17 @@ 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 res.GetStatus().GetCode() {
switch code := res.GetStatus().GetCode(); code {
case rpc.Code_CODE_OK:
return res, nil
case rpc.Code_CODE_NOT_FOUND:
// Resource was moved or deleted in the meantime. ignore.
return nil, err
// Moved or deleted in the meantime, or a backend the gateway could
// not reach: the gateway answers NOT_FOUND for both.
return nil, errResourceNotFound
default:
err := errors.New("failed to stat the moved resource")
logger.Error().Interface("res", res).Msg(err.Error())
return nil, err
return nil, fmt.Errorf("stat failed: %s %s", code, res.GetStatus().GetMessage())
}
}
+145 -27
View File
@@ -24,6 +24,7 @@ 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"
@@ -75,6 +76,12 @@ 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
@@ -89,6 +96,13 @@ 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
@@ -455,11 +469,15 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
return res, nil
}
// Retry constants for IndexSpace extraction failure handling.
// Retry and outage constants for IndexSpace.
const (
_extractionRetries = 5 // max retry attempts per file
_extractionRetryDelay = 1 * time.Second // delay between retries
_consecutiveAbort = 5 // abort walk after this many consecutive file failures
_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
)
// IndexSpace (re)indexes all resources of a given space.
@@ -480,7 +498,14 @@ func (s *Service) IndexSpace(ctx context.Context, spaceID *provider.StorageSpace
}
rootID.OpaqueId = rootID.SpaceId
failures := 0
// 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
)
w := walker.NewWalker(s.gatewaySelector)
err = w.Walk(ownerCtx, &rootID, func(wd string, info *provider.ResourceInfo, err error) error {
@@ -493,17 +518,22 @@ 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
}
ref := &provider.Reference{
Path: relPath,
ResourceId: &rootID,
if slices.Contains(_skipPathNames, relPath) {
return nil // the space root itself is never indexed
}
s.logger.Debug().Str("path", ref.Path).Msg("Walking tree")
s.logger.Debug().Str("path", relPath).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" {
@@ -523,32 +553,72 @@ 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", ref.Path).Msg("element hasn't changed. Skipping.")
s.logger.Debug().Str("path", relPath).Msg("element hasn't changed. Skipping.")
unchangedCount++
failures = 0
return nil
}
}
if err := s.upsertItem(ownerCtx, ref, _extractionRetries); err != 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
}
failures++
failedCount++
s.logger.Warn().Err(err).
Int("failures", failures).
Str("path", ref.Path).
Str("path", relPath).
Msg("extraction failed after retries")
if failures >= _consecutiveAbort {
if s.maxConsecutiveFailures > 0 && failures >= s.maxConsecutiveFailures {
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
@@ -564,7 +634,12 @@ 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) {
if err := s.upsertItem(ctx, ref, 0); err != nil {
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:
s.logger.Error().Err(err).Msg("failed to upsert resource")
}
}
@@ -572,9 +647,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 := s.resInfo(ctx, ref)
if ctx2 == nil || stat == nil || path == "" {
return fmt.Errorf("could not resolve resource info for %s", ref.GetPath())
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)
}
if slices.Contains(_skipPathNames, path) || slices.Contains(_skipPathDirs, path) {
@@ -592,7 +667,6 @@ 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 {
@@ -601,13 +675,19 @@ 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", ref.Path).
Str("path", path).
Msg("extraction attempt failed, retrying")
time.Sleep(_extractionRetryDelay)
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:
}
}
}
if err != nil {
return fmt.Errorf("extraction failed for %s: %w", ref.Path, err)
return fmt.Errorf("extraction failed for %s: %w", path, err)
}
r := engine.Resource{
@@ -629,7 +709,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", ref.Path, err)
return fmt.Errorf("index upsert for %s: %w", path, err)
}
logDocCount(s.engine, s.logger)
@@ -795,21 +875,59 @@ 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, ""
return nil, nil, "", fmt.Errorf("auth context: %w", err)
}
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector, s.logger)
statRes, err := statResource(ownerCtx, ref, s.gatewaySelector)
if err != nil {
return nil, nil, ""
return nil, nil, "", err
}
r, err := ResolveReference(ownerCtx, ref, statRes.GetInfo(), s.gatewaySelector)
if err != nil {
return nil, 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 ownerCtx, statRes, r.GetPath()
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())
}
+321 -5
View File
@@ -9,6 +9,7 @@ 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"
@@ -26,6 +27,7 @@ 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"
@@ -171,7 +173,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 == "spaceid" || sreq.Ref.ResourceId.OpaqueId == ri.Id.OpaqueId) &&
sreq.Ref.ResourceId.SpaceId == "spaceid"
})).Return(&sprovider.StatResponse{
Status: status.NewOK(context.Background()),
@@ -179,6 +181,7 @@ 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() {
@@ -256,11 +259,21 @@ var _ = Describe("Searchprovider", func() {
}
}
// Build path-to-fileInfo map for O(1) Stat dispatch.
fileInfoByPath := make(map[string]*sprovider.ResourceInfo, numDirs)
// 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)
for dirID, fi := range fileInfoByDir {
fileInfoByPath["./"+dirID+"/"+fi.Path] = fi
fileInfoByID[fi.Id.OpaqueId] = fi
filePathByID[fi.Id.OpaqueId] = "/" + dirID + "/" + fi.Path
}
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(
@@ -271,7 +284,7 @@ var _ = Describe("Searchprovider", func() {
Info: rootInfo,
}
}
if fi, ok := fileInfoByPath[sreq.Ref.Path]; ok {
if fi, ok := fileInfoByID[sreq.Ref.GetResourceId().GetOpaqueId()]; ok {
return &sprovider.StatResponse{
Status: status.NewOK(context.Background()),
Info: fi,
@@ -382,6 +395,280 @@ 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{
@@ -430,6 +717,35 @@ 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{
+4 -14
View File
@@ -21,7 +21,7 @@ type Config struct {
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"SHARING_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
UserSharingDriver string `yaml:"user_sharing_driver" env:"SHARING_USER_DRIVER" desc:"Driver to be used to persist shares. Supported values are 'jsoncs3', 'json', 'cs3' (deprecated) and 'owncloudsql'." introductionVersion:"pre5.0"`
UserSharingDriver string `yaml:"user_sharing_driver" env:"SHARING_USER_DRIVER" desc:"Driver to be used to persist shares. Supported values are 'jsoncs3', 'json' and 'cs3' (deprecated)." introductionVersion:"pre5.0"`
UserSharingDrivers UserSharingDrivers `yaml:"user_sharing_drivers"`
PublicSharingDriver string `yaml:"public_sharing_driver" env:"SHARING_PUBLIC_DRIVER" desc:"Driver to be used to persist public shares. Supported values are 'jsoncs3', 'json' and 'cs3' (deprecated)." introductionVersion:"pre5.0"`
PublicSharingDrivers PublicSharingDrivers `yaml:"public_sharing_drivers"`
@@ -62,10 +62,9 @@ type GRPCConfig struct {
}
type UserSharingDrivers struct {
JSONCS3 UserSharingJSONCS3Driver `yaml:"jsoncs3"`
JSON UserSharingJSONDriver `yaml:"json"`
CS3 UserSharingCS3Driver `yaml:"cs3"`
OwnCloudSQL UserSharingOwnCloudSQLDriver `yaml:"owncloudsql"`
JSONCS3 UserSharingJSONCS3Driver `yaml:"jsoncs3"`
JSON UserSharingJSONDriver `yaml:"json"`
CS3 UserSharingCS3Driver `yaml:"cs3"`
SQL UserSharingSQLDriver `yaml:"sql,omitempty"` // not supported by the oCIS product, therefore not part of docs
}
@@ -86,15 +85,6 @@ type UserSharingSQLDriver struct {
UserStorageMountID string `yaml:"user_storage_mount_id"`
}
type UserSharingOwnCloudSQLDriver struct {
DBUsername string `yaml:"db_username" env:"SHARING_USER_OWNCLOUDSQL_DB_USERNAME" desc:"Username for the database." introductionVersion:"pre5.0"`
DBPassword string `yaml:"db_password" env:"SHARING_USER_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database." introductionVersion:"pre5.0"`
DBHost string `yaml:"db_host" env:"SHARING_USER_OWNCLOUDSQL_DB_HOST" desc:"Hostname or IP of the database server." introductionVersion:"pre5.0"`
DBPort int `yaml:"db_port" env:"SHARING_USER_OWNCLOUDSQL_DB_PORT" desc:"Port that the database server is listening on." introductionVersion:"pre5.0"`
DBName string `yaml:"db_name" env:"SHARING_USER_OWNCLOUDSQL_DB_NAME" desc:"Name of the database to be used." introductionVersion:"pre5.0"`
UserStorageMountID string `yaml:"user_storage_mount_id" env:"SHARING_USER_OWNCLOUDSQL_USER_STORAGE_MOUNT_ID" desc:"Mount ID of the ownCloudSQL users storage for mapping ownCloud 10 shares." introductionVersion:"pre5.0"`
}
type UserSharingCS3Driver struct {
ProviderAddr string `yaml:"provider_addr" env:"SHARING_USER_CS3_PROVIDER_ADDR" desc:"GRPC address of the STORAGE-SYSTEM service." introductionVersion:"pre5.0"`
SystemUserID string `yaml:"system_user_id" env:"OCIS_SYSTEM_USER_ID;SHARING_USER_CS3_SYSTEM_USER_ID" desc:"ID of the oCIS STORAGE-SYSTEM system user. Admins need to set the ID for the STORAGE-SYSTEM system user in this config option which is then used to reference the user. Any reasonable long string is possible, preferably this would be an UUIDv4 format." introductionVersion:"pre5.0"`
@@ -49,12 +49,6 @@ func DefaultConfig() *config.Config {
SystemUserIDP: "internal",
MaxConcurrency: 1,
},
OwnCloudSQL: config.UserSharingOwnCloudSQLDriver{
DBUsername: "owncloud",
DBHost: "mysql",
DBPort: 3306,
DBName: "owncloud",
},
},
PublicSharingDriver: "jsoncs3",
PublicSharingDrivers: config.PublicSharingDrivers{
@@ -69,7 +63,6 @@ func DefaultConfig() *config.Config {
ProviderAddr: "com.owncloud.api.storage-system", // system storage
SystemUserIDP: "internal",
},
// TODO implement and add owncloudsql publicshare driver
},
Events: config.Events{
Addr: "127.0.0.1:9233",
@@ -54,15 +54,6 @@ func SharingConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string]
"enable_expired_shares_cleanup": cfg.UserSharingDrivers.SQL.EnableExpiredSharesCleanup,
"janitor_run_interval": cfg.UserSharingDrivers.SQL.JanitorRunInterval,
},
"owncloudsql": map[string]interface{}{
"gateway_addr": cfg.Reva.Address,
"storage_mount_id": cfg.UserSharingDrivers.OwnCloudSQL.UserStorageMountID,
"db_username": cfg.UserSharingDrivers.OwnCloudSQL.DBUsername,
"db_password": cfg.UserSharingDrivers.OwnCloudSQL.DBPassword,
"db_host": cfg.UserSharingDrivers.OwnCloudSQL.DBHost,
"db_port": cfg.UserSharingDrivers.OwnCloudSQL.DBPort,
"db_name": cfg.UserSharingDrivers.OwnCloudSQL.DBName,
},
"cs3": map[string]interface{}{
"gateway_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
"provider_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
+4 -21
View File
@@ -24,7 +24,7 @@ type Config struct {
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"STORAGE_USERS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
GracefulShutdownTimeout int `yaml:"graceful_shutdown_timeout" env:"STORAGE_USERS_GRACEFUL_SHUTDOWN_TIMEOUT" desc:"The number of seconds to wait for the 'storage-users' service to shutdown cleanly before exiting with an error that gets logged. Note: This setting is only applicable when running the 'storage-users' service as a standalone service. See the text description for more details." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"STORAGE_USERS_DRIVER" desc:"The storage driver which should be used by the service. Defaults to 'ocis', Supported values are: 'ocis', 's3ng' and 'owncloudsql' (deprecated). The 'ocis' driver stores all data (blob and meta data) in an POSIX compliant volume. The 's3ng' driver stores metadata in a POSIX compliant volume and uploads blobs to the s3 bucket." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"STORAGE_USERS_DRIVER" desc:"The storage driver which should be used by the service. Defaults to 'ocis', Supported values are: 'ocis' and 's3ng'. The 'ocis' driver stores all data (blob and meta data) in an POSIX compliant volume. The 's3ng' driver stores metadata in a POSIX compliant volume and uploads blobs to the s3 bucket." introductionVersion:"pre5.0"`
Drivers Drivers `yaml:"drivers"`
DataServerURL string `yaml:"data_server_url" env:"STORAGE_USERS_DATA_SERVER_URL" desc:"URL of the data server, needs to be reachable by the data gateway provided by the frontend service or the user if directly exposed." introductionVersion:"pre5.0"`
DataGatewayURL string `yaml:"data_gateway_url" env:"STORAGE_USERS_DATA_GATEWAY_URL" desc:"URL of the data gateway server" introductionVersion:"pre5.0"`
@@ -100,10 +100,9 @@ type CORS struct {
// Drivers combine all storage driver configurations
type Drivers struct {
OCIS OCISDriver `yaml:"ocis"`
S3NG S3NGDriver `yaml:"s3ng"`
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
Posix PosixDriver `yaml:"posix"`
OCIS OCISDriver `yaml:"ocis"`
S3NG S3NGDriver `yaml:"s3ng"`
Posix PosixDriver `yaml:"posix"`
S3 S3Driver `yaml:",omitempty"` // not supported by the oCIS product, therefore not part of docs
EOS EOSDriver `yaml:",omitempty"` // not supported by the oCIS product, therefore not part of docs
@@ -176,22 +175,6 @@ type S3NGDriver struct {
DisableVersioning bool `yaml:"disable_versioning" env:"OCIS_DISABLE_VERSIONING" desc:"Disables versioning of files. When set to true, new uploads with the same filename will overwrite existing files instead of creating a new version." introductionVersion:"7.0.0"`
}
// OwnCloudSQLDriver is the storage driver configuration when using 'owncloudsql' storage driver
type OwnCloudSQLDriver struct {
// Root is the absolute path to the location of the data
Root string `yaml:"root" env:"STORAGE_USERS_OWNCLOUDSQL_DATADIR" desc:"The directory where the filesystem storage will store SQL migration data. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/storage/owncloud." introductionVersion:"pre5.0"`
// ShareFolder defines the name of the folder jailing all shares
ShareFolder string `yaml:"share_folder" env:"STORAGE_USERS_OWNCLOUDSQL_SHARE_FOLDER" desc:"Name of the folder jailing all shares." introductionVersion:"pre5.0"`
UserLayout string `yaml:"user_layout" env:"STORAGE_USERS_OWNCLOUDSQL_LAYOUT" desc:"Path layout to use to navigate into a users folder in an owncloud data directory" introductionVersion:"pre5.0"`
UploadInfoDir string `yaml:"upload_info_dir" env:"STORAGE_USERS_OWNCLOUDSQL_UPLOADINFO_DIR" desc:"The directory where the filesystem will store uploads temporarily. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/storage/uploadinfo." introductionVersion:"pre5.0"`
DBUsername string `yaml:"db_username" env:"STORAGE_USERS_OWNCLOUDSQL_DB_USERNAME" desc:"Username for the database." introductionVersion:"pre5.0"`
DBPassword string `yaml:"db_password" env:"STORAGE_USERS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database." introductionVersion:"pre5.0"`
DBHost string `yaml:"db_host" env:"STORAGE_USERS_OWNCLOUDSQL_DB_HOST" desc:"Hostname or IP of the database server." introductionVersion:"pre5.0"`
DBPort int `yaml:"db_port" env:"STORAGE_USERS_OWNCLOUDSQL_DB_PORT" desc:"Port that the database server is listening on." introductionVersion:"pre5.0"`
DBName string `yaml:"db_name" env:"STORAGE_USERS_OWNCLOUDSQL_DB_NAME" desc:"Name of the database to be used." introductionVersion:"pre5.0"`
UsersProviderEndpoint string `yaml:"users_provider_endpoint" env:"STORAGE_USERS_OWNCLOUDSQL_USERS_PROVIDER_ENDPOINT" desc:"Endpoint of the users provider." introductionVersion:"pre5.0"`
}
// PosixDriver is the storage driver configuration when using 'posix' storage driver
type PosixDriver struct {
// Root is the absolute path to the location of the data
@@ -94,18 +94,6 @@ func DefaultConfig() *config.Config {
GracefulShutdownTimeout: 30,
Driver: "ocis",
Drivers: config.Drivers{
OwnCloudSQL: config.OwnCloudSQLDriver{
Root: filepath.Join(defaults.BaseDataPath(), "storage", "owncloud"),
ShareFolder: "/Shares",
UserLayout: "{{.Username}}",
UploadInfoDir: filepath.Join(defaults.BaseDataPath(), "storage", "uploadinfo"),
DBUsername: "owncloud",
DBPassword: "owncloud",
DBHost: "",
DBPort: 3306,
DBName: "owncloud",
UsersProviderEndpoint: "com.owncloud.api.users",
},
S3NG: config.S3NGDriver{
Propagator: "sync",
Root: filepath.Join(defaults.BaseDataPath(), "storage", "users"),
@@ -137,29 +137,6 @@ func LocalHome(cfg *config.Config) map[string]interface{} {
}
}
// OwnCloudSQL is the config mapping for the OwnCloudSQL storage driver
func OwnCloudSQL(cfg *config.Config) map[string]interface{} {
return map[string]interface{}{
"datadirectory": cfg.Drivers.OwnCloudSQL.Root,
"upload_info_dir": cfg.Drivers.OwnCloudSQL.UploadInfoDir,
"share_folder": cfg.Drivers.OwnCloudSQL.ShareFolder,
"user_layout": cfg.Drivers.OwnCloudSQL.UserLayout,
"enable_home": false,
"dbusername": cfg.Drivers.OwnCloudSQL.DBUsername,
"dbpassword": cfg.Drivers.OwnCloudSQL.DBPassword,
"dbhost": cfg.Drivers.OwnCloudSQL.DBHost,
"dbport": cfg.Drivers.OwnCloudSQL.DBPort,
"dbname": cfg.Drivers.OwnCloudSQL.DBName,
"userprovidersvc": cfg.Drivers.OwnCloudSQL.UsersProviderEndpoint,
"tokens": map[string]interface{}{
"download_endpoint": cfg.DataServerURL,
"datagateway_endpoint": cfg.DataGatewayURL,
"transfer_shared_secret": cfg.Commons.TransferSecret,
"transfer_expires": cfg.TransferExpires,
},
}
}
// Ocis is the config mapping for the Ocis storage driver
func Ocis(cfg *config.Config) map[string]interface{} {
return map[string]interface{}{
+18 -20
View File
@@ -5,31 +5,29 @@ import "github.com/owncloud/ocis/v2/services/storage-users/pkg/config"
// StorageProviderDrivers are the drivers for the storage provider
func StorageProviderDrivers(cfg *config.Config) map[string]interface{} {
return map[string]interface{}{
"eos": EOS(cfg),
"eoshome": EOSHome(cfg),
"eosgrpc": EOSGRPC(cfg),
"local": Local(cfg),
"localhome": LocalHome(cfg),
"owncloudsql": OwnCloudSQL(cfg),
"ocis": OcisNoEvents(cfg),
"s3": S3(cfg),
"s3ng": S3NGNoEvents(cfg),
"posix": Posix(cfg, true),
"eos": EOS(cfg),
"eoshome": EOSHome(cfg),
"eosgrpc": EOSGRPC(cfg),
"local": Local(cfg),
"localhome": LocalHome(cfg),
"ocis": OcisNoEvents(cfg),
"s3": S3(cfg),
"s3ng": S3NGNoEvents(cfg),
"posix": Posix(cfg, true),
}
}
// DataProviderDrivers are the drivers for the storage provider
func DataProviderDrivers(cfg *config.Config) map[string]interface{} {
return map[string]interface{}{
"eos": EOS(cfg),
"eoshome": EOSHome(cfg),
"eosgrpc": EOSGRPC(cfg),
"local": Local(cfg),
"localhome": LocalHome(cfg),
"owncloudsql": OwnCloudSQL(cfg),
"ocis": Ocis(cfg),
"s3": S3(cfg),
"s3ng": S3NG(cfg),
"posix": Posix(cfg, false),
"eos": EOS(cfg),
"eoshome": EOSHome(cfg),
"eosgrpc": EOSGRPC(cfg),
"local": Local(cfg),
"localhome": LocalHome(cfg),
"ocis": Ocis(cfg),
"s3": S3(cfg),
"s3ng": S3NG(cfg),
"posix": Posix(cfg, false),
}
}
+2 -15
View File
@@ -21,7 +21,7 @@ type Config struct {
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"USERS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"USERS_DRIVER" desc:"The driver which should be used by the users service. Supported values are 'ldap' and 'owncloudsql'." introductionVersion:"pre5.0"`
Driver string `yaml:"driver" env:"USERS_DRIVER" desc:"The driver which should be used by the users service. Supported value is 'ldap'." introductionVersion:"pre5.0"`
Drivers Drivers `yaml:"drivers"`
Context context.Context `yaml:"-"`
@@ -52,8 +52,7 @@ type GRPCConfig struct {
}
type Drivers struct {
LDAP LDAPDriver `yaml:"ldap"`
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
LDAP LDAPDriver `yaml:"ldap"`
JSON JSONDriver `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
REST RESTProvider `yaml:"rest,omitempty"` // not supported by the oCIS product, therefore not part of docs
@@ -113,18 +112,6 @@ type LDAPGroupSchema struct {
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;USERS_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
}
type OwnCloudSQLDriver struct {
DBUsername string `yaml:"db_username" env:"USERS_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
DBPassword string `yaml:"db_password" env:"USERS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
DBHost string `yaml:"db_host" env:"USERS_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
DBPort int `yaml:"db_port" env:"USERS_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
DBName string `yaml:"db_name" env:"USERS_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
IDP string `yaml:"idp" env:"USERS_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
Nobody int64 `yaml:"nobody" env:"USERS_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
JoinUsername bool `yaml:"join_username" env:"USERS_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames" introductionVersion:"pre5.0"`
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"USERS_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user IDs." introductionVersion:"pre5.0"`
EnableMedialSearch bool `yaml:"enable_medial_search" env:"USERS_OWNCLOUDSQL_ENABLE_MEDIAL_SEARCH" desc:"Allow 'medial search' when searching for users instead of just doing a prefix search. This allows finding 'Alice' when searching for 'lic'." introductionVersion:"pre5.0"`
}
type RESTProvider struct {
ClientID string
ClientSecret string
@@ -77,18 +77,6 @@ func DefaultConfig() *config.Config {
},
},
JSON: config.JSONDriver{},
OwnCloudSQL: config.OwnCloudSQLDriver{
DBUsername: "owncloud",
DBPassword: "secret",
DBHost: "mysql",
DBPort: 3306,
DBName: "owncloud",
IDP: "https://localhost:9200",
Nobody: 90,
JoinUsername: false,
JoinOwnCloudUUID: false,
EnableMedialSearch: false,
},
},
}
}
-12
View File
@@ -30,18 +30,6 @@ func UsersConfigFromStruct(cfg *config.Config) map[string]interface{} {
"users": cfg.Drivers.JSON.File,
},
"ldap": ldapConfigFromString(cfg.Drivers.LDAP),
"owncloudsql": map[string]interface{}{
"dbusername": cfg.Drivers.OwnCloudSQL.DBUsername,
"dbpassword": cfg.Drivers.OwnCloudSQL.DBPassword,
"dbhost": cfg.Drivers.OwnCloudSQL.DBHost,
"dbport": cfg.Drivers.OwnCloudSQL.DBPort,
"dbname": cfg.Drivers.OwnCloudSQL.DBName,
"idp": cfg.Drivers.OwnCloudSQL.IDP,
"nobody": cfg.Drivers.OwnCloudSQL.Nobody,
"join_username": cfg.Drivers.OwnCloudSQL.JoinUsername,
"join_ownclouduuid": cfg.Drivers.OwnCloudSQL.JoinOwnCloudUUID,
"enable_medial_search": cfg.Drivers.OwnCloudSQL.EnableMedialSearch,
},
},
},
},
@@ -356,6 +356,26 @@ Feature: edit/search user including email
"""
Scenario: non-admin user's e-mail search term matches nobody when search is restricted to name, surname and username
Given the config "GRAPH_LDAP_USER_SEARCH_ATTRIBUTES" has been set to "onPremisesSamAccountName,displayName,surname" for "graph" service
When user "Brian" searches for user "%22alice@example.org%22" using Graph API
Then the HTTP status code should be "200"
And the JSON data of the response should match
"""
{
"type": "object",
"required": ["value"],
"properties": {
"value": {
"type": "array",
"minItems": 0,
"maxItems": 0
}
}
}
"""
Scenario: non-admin user searches for a disabled users
Given the user "Admin" has disabled user "Alice"
When user "Brian" searches for user "alice" using Graph API
+20 -2
View File
@@ -135,13 +135,32 @@ 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"]
wait_for(lambda: ocis_healthy(ocis_url), 120, "ocis")
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",
)
print("ocis ready.")
playwright_env = {
@@ -172,7 +191,6 @@ 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
+18 -8
View File
@@ -21,6 +21,7 @@ import (
"crypto/aes"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
@@ -195,11 +196,11 @@ func (ctx rsaEncrypterVerifier) encryptKey(cek []byte, alg KeyAlgorithm) (recipi
func (ctx rsaEncrypterVerifier) encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) {
switch alg {
case RSA1_5:
return rsa.EncryptPKCS1v15(RandReader, ctx.publicKey, cek)
return rsa.EncryptPKCS1v15(randReader, ctx.publicKey, cek)
case RSA_OAEP:
return rsa.EncryptOAEP(sha1.New(), RandReader, ctx.publicKey, cek, []byte{})
return rsa.EncryptOAEP(sha1.New(), randReader, ctx.publicKey, cek, []byte{})
case RSA_OAEP_256:
return rsa.EncryptOAEP(sha256.New(), RandReader, ctx.publicKey, cek, []byte{})
return rsa.EncryptOAEP(sha256.New(), randReader, ctx.publicKey, cek, []byte{})
}
return nil, ErrUnsupportedAlgorithm
@@ -288,9 +289,9 @@ func (ctx rsaDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm
// TODO(https://github.com/go-jose/go-jose/issues/40): As of go1.20, the
// random parameter is legacy and ignored, and it can be nil.
// https://cs.opensource.google/go/go/+/refs/tags/go1.20:src/crypto/rsa/pkcs1v15.go;l=263;bpv=0;bpt=1
out, err = rsa.SignPKCS1v15(RandReader, ctx.privateKey, hash, hashed)
out, err = rsa.SignPKCS1v15(randReader, ctx.privateKey, hash, hashed)
case PS256, PS384, PS512:
out, err = rsa.SignPSS(RandReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
out, err = rsa.SignPSS(randReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthEqualsHash,
})
}
@@ -391,7 +392,7 @@ func (ctx ecKeyGenerator) keySize() int {
// Get a content encryption key for ECDH-ES
func (ctx ecKeyGenerator) genKey() ([]byte, rawHeader, error) {
priv, err := ecdsa.GenerateKey(ctx.publicKey.Curve, RandReader)
priv, err := ecdsa.GenerateKey(ctx.publicKey.Curve, randReader)
if err != nil {
return nil, rawHeader{}, err
}
@@ -483,7 +484,7 @@ func (ctx edDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm)
return Signature{}, ErrUnsupportedAlgorithm
}
sig, err := ctx.privateKey.Sign(RandReader, payload, crypto.Hash(0))
sig, err := ctx.privateKey.Sign(randReader, payload, crypto.Hash(0))
if err != nil {
return Signature{}, err
}
@@ -533,7 +534,7 @@ func (ctx ecDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm)
_, _ = hasher.Write(payload)
hashed := hasher.Sum(nil)
r, s, err := ecdsa.Sign(RandReader, ctx.privateKey, hashed)
r, s, err := ecdsa.Sign(randReader, ctx.privateKey, hashed)
if err != nil {
return Signature{}, err
}
@@ -571,12 +572,21 @@ func (ctx ecEncrypterVerifier) verifyPayload(payload []byte, signature []byte, a
case ES256:
keySize = 32
hash = crypto.SHA256
if ctx.publicKey.Curve != elliptic.P256() {
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
}
case ES384:
keySize = 48
hash = crypto.SHA384
if ctx.publicKey.Curve != elliptic.P384() {
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
}
case ES512:
keySize = 66
hash = crypto.SHA512
if ctx.publicKey.Curve != elliptic.P521() {
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
}
default:
return ErrUnsupportedAlgorithm
}
+5 -1
View File
@@ -51,6 +51,8 @@ func NewCBCHMAC(key []byte, newBlockCipher func([]byte) (cipher.Block, error)) (
hash = sha512.New384
case 32:
hash = sha512.New
default:
return nil, errors.New("go-jose/go-jose: invalid key size for CBC-HMAC")
}
return &cbcAEAD{
@@ -176,7 +178,9 @@ func padBuffer(buffer []byte, blockSize int) []byte {
// Remove padding
func unpadBuffer(buffer []byte, blockSize int) ([]byte, error) {
if len(buffer)%blockSize != 0 {
// A padded buffer can't be empty because an empty input is padded with
// `blockSize` bytes, resulting in a non-empty ciphertext.
if len(buffer) == 0 || len(buffer)%blockSize != 0 {
return nil, errors.New("go-jose/go-jose: invalid padding")
}
+72 -31
View File
@@ -258,6 +258,10 @@ func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
}
recipientInfo, err = makeJWERecipient(recipient.Algorithm, recipient.Key)
if err != nil {
return err
}
if recipient.KeyID != "" {
recipientInfo.keyID = recipient.KeyID
}
@@ -270,10 +274,8 @@ func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
}
}
if err == nil {
ctx.recipients = append(ctx.recipients, recipientInfo)
}
return err
ctx.recipients = append(ctx.recipients, recipientInfo)
return nil
}
func makeJWERecipient(alg KeyAlgorithm, encryptionKey interface{}) (recipientKeyInfo, error) {
@@ -426,6 +428,13 @@ func (ctx *genericEncrypter) Options() EncrypterOptions {
}
}
func validateContentEncryptionKeySize(cek []byte, cipher contentCipher) error {
if len(cek) != cipher.keySize() {
return ErrInvalidKeySize
}
return nil
}
// Decrypt and validate the object and return the plaintext. This
// function does not support multi-recipient. If you desire multi-recipient
// decryption use DecryptMulti instead.
@@ -490,21 +499,23 @@ func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error)
recipientHeaders := obj.mergedHeaders(&recipient)
cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
if err == nil {
// Found a valid CEK -- let's try to decrypt.
plaintext, err = cipher.decrypt(cek, authData, parts)
if err != nil {
return nil, ErrCryptoFailure
}
if plaintext == nil {
err = validateContentEncryptionKeySize(cek, cipher)
if err != nil {
return nil, ErrCryptoFailure
}
// The "zip" header parameter may only be present in the protected header.
if comp := obj.protected.getCompression(); comp != "" {
plaintext, err = decompress(comp, plaintext)
if err != nil {
return nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
}
// Found a valid CEK -- let's try to decrypt.
plaintext, err = cipher.decrypt(cek, authData, parts)
if err != nil {
return nil, ErrCryptoFailure
}
plaintext, err = obj.decompress(plaintext)
if err != nil {
return nil, err
}
return plaintext, nil
@@ -559,31 +570,42 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade
var plaintext []byte
var headers rawHeader
if len(obj.recipients) == 0 {
return -1, Header{}, nil, errors.New("go-jose/go-jose: no recipients")
}
// Loop sets `err` in the function scope; don't shadow it.
for i, recipient := range obj.recipients {
recipientHeaders := obj.mergedHeaders(&recipient)
cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
if err == nil {
// Found a valid CEK -- let's try to decrypt.
plaintext, err = cipher.decrypt(cek, authData, parts)
if err == nil {
index = i
headers = recipientHeaders
break
}
var cek []byte
cek, err = decrypter.decryptKey(recipientHeaders, &recipient, generator)
if err != nil {
continue
}
err = validateContentEncryptionKeySize(cek, cipher)
if err != nil {
continue
}
// Found a valid CEK -- let's try to decrypt.
plaintext, err = cipher.decrypt(cek, authData, parts)
if err != nil {
continue
}
index = i
headers = recipientHeaders
break
}
if plaintext == nil {
if err != nil {
return -1, Header{}, nil, ErrCryptoFailure
}
// The "zip" header parameter may only be present in the protected header.
if comp := obj.protected.getCompression(); comp != "" {
plaintext, err = decompress(comp, plaintext)
if err != nil {
return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
}
plaintext, err = obj.decompress(plaintext)
if err != nil {
return -1, Header{}, nil, err
}
sanitized, err := headers.sanitized()
@@ -593,3 +615,22 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade
return index, sanitized, plaintext, err
}
// decompress decompresses plaintext using the protected "zip" header, if present.
// It returns plaintext unchanged when there is no protected header or "zip" value.
func (obj JSONWebEncryption) decompress(plaintext []byte) ([]byte, error) {
if obj.protected == nil {
return plaintext, nil
}
comp := obj.protected.getCompression()
if comp == "" {
return plaintext, nil
}
plaintext, err := decompress(comp, plaintext)
if err != nil {
return nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
}
return plaintext, nil
}
+13 -6
View File
@@ -140,6 +140,10 @@ const (
parseArrayValue // parsing array value
)
// This limits the max nesting depth to prevent stack overflow.
// This is permitted by https://tools.ietf.org/html/rfc7159#section-9
const maxNestingDepth = 10000
// reset prepares the scanner for use.
// It must be called before calling s.step.
func (s *scanner) reset() {
@@ -170,8 +174,13 @@ func (s *scanner) eof() int {
}
// pushParseState pushes a new parse state p onto the parse stack.
func (s *scanner) pushParseState(p int) {
s.parseState = append(s.parseState, p)
// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned.
func (s *scanner) pushParseState(c byte, newParseState int, successState int) int {
s.parseState = append(s.parseState, newParseState)
if len(s.parseState) <= maxNestingDepth {
return successState
}
return s.error(c, "exceeded max depth")
}
// popParseState pops a parse state (already obtained) off the stack
@@ -211,12 +220,10 @@ func stateBeginValue(s *scanner, c byte) int {
switch c {
case '{':
s.step = stateBeginStringOrEmpty
s.pushParseState(parseObjectKey)
return scanBeginObject
return s.pushParseState(c, parseObjectKey, scanBeginObject)
case '[':
s.step = stateBeginValueOrEmpty
s.pushParseState(parseArrayValue)
return scanBeginArray
return s.pushParseState(c, parseArrayValue, scanBeginArray)
case '"':
s.step = stateInString
return scanBeginLiteral
+17 -9
View File
@@ -153,6 +153,10 @@ func ParseEncryptedJSON(
keyEncryptionAlgorithms []KeyAlgorithm,
contentEncryption []ContentEncryption,
) (*JSONWebEncryption, error) {
if len(input) == 0 {
return nil, errEmptyInput
}
var parsed rawJSONWebEncryption
err := json.Unmarshal([]byte(input), &parsed)
if err != nil {
@@ -198,15 +202,6 @@ func (parsed *rawJSONWebEncryption) sanitized(
}
}
// Note: this must be called _after_ we parse the protected header,
// otherwise fields from the protected header will not get picked up.
var err error
mergedHeaders := obj.mergedHeaders(nil)
obj.Header, err = mergedHeaders.sanitized()
if err != nil {
return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders)
}
if len(parsed.Recipients) == 0 {
obj.recipients = []recipientInfo{
{
@@ -260,6 +255,15 @@ func (parsed *rawJSONWebEncryption) sanitized(
}
}
// Note: this must be called _after_ we parse the protected header,
// otherwise fields from the protected header will not get picked up.
mergedHeaders := obj.mergedHeaders(nil)
var err error
obj.Header, err = mergedHeaders.sanitized()
if err != nil {
return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %w", err)
}
obj.iv = parsed.Iv.bytes()
obj.ciphertext = parsed.Ciphertext.bytes()
obj.tag = parsed.Tag.bytes()
@@ -291,6 +295,10 @@ func ParseEncryptedCompact(
var parts [5]string
var ok bool
if len(input) == 0 {
return nil, errEmptyInput
}
for i := range 4 {
parts[i], input, ok = strings.Cut(input, ".")
if !ok {
+217 -47
View File
@@ -107,7 +107,7 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) {
switch key := k.Key.(type) {
case ed25519.PublicKey:
raw = fromEdPublicKey(key)
raw, err = fromEdPublicKey(key)
case *ecdsa.PublicKey:
raw, err = fromEcPublicKey(key)
case *rsa.PublicKey:
@@ -177,13 +177,29 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) {
// UnmarshalJSON reads a key from its JSON representation.
//
// Returns ErrUnsupportedKeyType for unrecognized or unsupported "kty" header values.
func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
//
// Directly unmarshaling a JWK is not safe for untrusted input.
func (k *JSONWebKey) UnmarshalJSON(data []byte) error {
return k.unmarshalJSON(data, true)
}
// unmarshalJSON reads a key from its JSON representation.
//
// If allowPrivate is false, a JWK with private key material is rejected and the
// function is safe for use against untrusted input.
func (k *JSONWebKey) unmarshalJSON(data []byte, allowPrivate bool) (err error) {
var raw rawJSONWebKey
err = json.Unmarshal(data, &raw)
if err != nil {
return err
}
if !allowPrivate &&
(raw.K != nil || raw.D != nil || raw.P != nil || raw.Q != nil ||
raw.Dp != nil || raw.Dq != nil || raw.Qi != nil) {
return errors.New("go-jose/go-jose: JWK contains private parameters")
}
certs, err := parseCertificateChain(raw.X5c)
if err != nil {
return fmt.Errorf("go-jose/go-jose: failed to unmarshal x5c field: %s", err)
@@ -207,21 +223,29 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
case "EC":
if raw.D != nil {
key, err = raw.ecPrivateKey()
if err == nil {
keyPub = key.(*ecdsa.PrivateKey).Public()
if err != nil {
return err
}
keyPub = key.(*ecdsa.PrivateKey).Public()
} else {
key, err = raw.ecPublicKey()
if err != nil {
return err
}
keyPub = key
}
case "RSA":
if raw.D != nil {
key, err = raw.rsaPrivateKey()
if err == nil {
keyPub = key.(*rsa.PrivateKey).Public()
if err != nil {
return err
}
keyPub = key.(*rsa.PrivateKey).Public()
} else {
key, err = raw.rsaPublicKey()
if err != nil {
return err
}
keyPub = key
}
case "oct":
@@ -229,25 +253,28 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
return errors.New("go-jose/go-jose: invalid JWK, found 'oct' (symmetric) key with cert chain")
}
key, err = raw.symmetricKey()
if err != nil {
return err
}
case "OKP":
if raw.Crv == "Ed25519" {
if raw.D != nil {
key, err = raw.edPrivateKey()
if err == nil {
keyPub = key.(ed25519.PrivateKey).Public()
if err != nil {
return err
}
keyPub = key.(ed25519.PrivateKey).Public()
} else {
key, err = raw.edPublicKey()
if err != nil {
return err
}
keyPub = key
}
}
case "":
// kty MUST be present
err = fmt.Errorf("go-jose/go-jose: missing json web key type")
}
if err != nil {
return
return fmt.Errorf("go-jose/go-jose: missing json web key type")
}
if key == nil {
@@ -388,11 +415,12 @@ func rsaThumbprintInput(n *big.Int, e int) (string, error) {
func edThumbprintInput(ed ed25519.PublicKey) (string, error) {
crv := "Ed25519"
if len(ed) > 32 {
return "", errors.New("go-jose/go-jose: invalid elliptic key (too large)")
err := validateEd25519PublicKey(ed)
if err != nil {
return "", err
}
return fmt.Sprintf(edThumbprintTemplate, crv,
newFixedSizeBuffer(ed, 32).base64()), nil
newFixedSizeBuffer(ed, ed25519.PublicKeySize).base64()), nil
}
// Thumbprint computes the JWK Thumbprint of a key using the
@@ -493,23 +521,39 @@ func (k *JSONWebKey) Valid() bool {
return true
}
// MaxRSAModulusBits is the largest RSA modulus size, in bits, that will be
// accepted when parsing a JWK. Applications that need larger keys can raise
// this limit.
//
// If modifying MaxRSAModulusBits, do it before any parsing occurs.
var MaxRSAModulusBits = 4096
func (key rawJSONWebKey) rsaPublicKey() (*rsa.PublicKey, error) {
if key.N == nil || key.E == nil {
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, missing n/e values")
}
n := key.N.bigInt()
if n.BitLen() > MaxRSAModulusBits {
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large")
}
return &rsa.PublicKey{
N: key.N.bigInt(),
N: n,
E: key.E.toInt(),
}, nil
}
func fromEdPublicKey(pub ed25519.PublicKey) *rawJSONWebKey {
func fromEdPublicKey(pub ed25519.PublicKey) (*rawJSONWebKey, error) {
err := validateEd25519PublicKey(pub)
if err != nil {
return nil, err
}
return &rawJSONWebKey{
Kty: "OKP",
Crv: "Ed25519",
X: newBuffer(pub),
}
}, nil
}
func fromRsaPublicKey(pub *rsa.PublicKey) *rawJSONWebKey {
@@ -604,21 +648,36 @@ func (key rawJSONWebKey) edPrivateKey() (ed25519.PrivateKey, error) {
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed25519 private key, missing %s value(s)", strings.Join(missing, ", "))
}
privateKey := make([]byte, ed25519.PrivateKeySize)
copy(privateKey[0:32], key.D.bytes())
copy(privateKey[32:], key.X.bytes())
rv := ed25519.PrivateKey(privateKey)
return rv, nil
publicKey := key.X.bytes()
err := validateEd25519PublicKey(publicKey)
if err != nil {
return nil, err
}
seed := key.D.bytes()
if len(seed) != ed25519.SeedSize {
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed25519 private key, wrong length for d")
}
privateKey := ed25519.NewKeyFromSeed(seed)
derivedPublicKey := privateKey.Public().(ed25519.PublicKey)
if !bytes.Equal(derivedPublicKey, publicKey) {
return nil, errors.New("go-jose/go-jose: invalid Ed25519 private key, x does not match d")
}
return privateKey, nil
}
func (key rawJSONWebKey) edPublicKey() (ed25519.PublicKey, error) {
if key.X == nil {
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed key, missing x value")
}
publicKey := make([]byte, ed25519.PublicKeySize)
copy(publicKey[0:32], key.X.bytes())
rv := ed25519.PublicKey(publicKey)
return rv, nil
publicKey := key.X.bytes()
err := validateEd25519PublicKey(publicKey)
if err != nil {
return nil, err
}
return ed25519.PublicKey(bytes.Clone(publicKey)), nil
}
func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
@@ -642,16 +701,23 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", "))
}
n := key.N.bigInt()
if n.BitLen() > MaxRSAModulusBits {
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large")
}
p, q := key.P.bigInt(), key.Q.bigInt()
if p.BitLen()+q.BitLen() > n.BitLen()+1 || new(big.Int).Mul(p, q).Cmp(n) != 0 {
return nil, errors.New("go-jose/go-jose: invalid RSA private key, p * q != n")
}
rv := &rsa.PrivateKey{
PublicKey: rsa.PublicKey{
N: key.N.bigInt(),
N: n,
E: key.E.toInt(),
},
D: key.D.bigInt(),
Primes: []*big.Int{
key.P.bigInt(),
key.Q.bigInt(),
},
D: key.D.bigInt(),
Primes: []*big.Int{p, q},
}
if key.Dp != nil {
@@ -669,9 +735,17 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
}
func fromEdPrivateKey(ed ed25519.PrivateKey) (*rawJSONWebKey, error) {
raw := fromEdPublicKey(ed25519.PublicKey(ed[32:]))
if len(ed) != ed25519.PrivateKeySize {
return nil, errors.New("go-jose/go-jose: invalid Ed25519 private key length")
}
raw.D = newBuffer(ed[0:32])
publicKey := ed.Public().(ed25519.PublicKey)
raw, err := fromEdPublicKey(publicKey)
if err != nil {
return nil, err
}
raw.D = newBuffer(ed.Seed())
return raw, nil
}
@@ -810,7 +884,7 @@ var (
ErrJWKSKidNotFound = errors.New("go-jose/go-jose: JWK with matching kid not found in JWK Set")
)
func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
func tryJWKS(key interface{}, header Header) (interface{}, error) {
var jwks JSONWebKeySet
switch jwksType := key.(type) {
@@ -823,16 +897,8 @@ func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
return key, nil
}
// Determine the KID to search for from the headers.
var kid string
for _, header := range headers {
if header.KeyID != "" {
kid = header.KeyID
break
}
}
// If no KID is specified in the headers, reject.
// If no KID is specified in the header, reject.
kid := header.KeyID
if kid == "" {
return nil, ErrJWKSKidNotFound
}
@@ -846,3 +912,107 @@ func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
return keys[0].Key, nil
}
// weakEd25519PublicKeys contains the low-order Ed25519 encodings accepted by
// Go's verifier that must not be accepted as JOSE verification keys.
var weakEd25519PublicKeys = map[[ed25519.PublicKeySize]byte]struct{}{
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}: {},
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
}: {},
{
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
}: {},
{
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
}: {},
{
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05,
}: {},
{
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x85,
}: {},
{
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a,
}: {},
{
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0xfa,
}: {},
{
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
}: {},
{
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
}: {},
{
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
}: {},
{
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
}: {},
{
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
}: {},
{
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
}: {},
}
func validateEd25519PublicKey(publicKey ed25519.PublicKey) error {
if len(publicKey) != ed25519.PublicKeySize {
return fmt.Errorf("go-jose/go-jose: invalid Ed25519 public key, wrong length for x")
}
var encoded [ed25519.PublicKeySize]byte
copy(encoded[:], publicKey)
_, ok := weakEd25519PublicKeys[encoded]
if ok {
return errors.New("go-jose/go-jose: invalid Ed25519 public key, low-order point")
}
return nil
}
+29 -17
View File
@@ -22,6 +22,7 @@ import (
"errors"
"fmt"
"strings"
"unicode"
"github.com/go-jose/go-jose/v4/json"
)
@@ -89,12 +90,12 @@ func ParseSigned(
signature string,
signatureAlgorithms []SignatureAlgorithm,
) (*JSONWebSignature, error) {
signature = stripWhitespace(signature)
if strings.HasPrefix(signature, "{") {
trimmed := strings.TrimLeftFunc(signature, unicode.IsSpace)
if strings.HasPrefix(trimmed, "{") {
return ParseSignedJSON(signature, signatureAlgorithms)
}
return parseSignedCompact(signature, nil, signatureAlgorithms)
return parseSignedCompact(stripWhitespace(signature), nil, signatureAlgorithms)
}
// ParseSignedCompact parses a message in JWS Compact Serialization. Validation fails if the JWS is
@@ -186,6 +187,10 @@ func ParseSignedJSON(
input string,
signatureAlgorithms []SignatureAlgorithm,
) (*JSONWebSignature, error) {
if len(input) == 0 {
return nil, errEmptyInput
}
var parsed rawJSONWebSignature
err := json.Unmarshal([]byte(input), &parsed)
if err != nil {
@@ -270,17 +275,18 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
Signature: parsed.Signature,
}
var err error
signature.Header, err = signature.mergedHeaders().sanitized()
if err != nil {
return nil, err
}
alg := SignatureAlgorithm(signature.Header.Algorithm)
mergedHeaders := signature.mergedHeaders()
alg := mergedHeaders.getSignatureAlgorithm()
if !containsSignatureAlgorithm(signatureAlgorithms, alg) {
return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms)
}
var err error
signature.Header, err = mergedHeaders.sanitized()
if err != nil {
return nil, err
}
if signature.header != nil {
signature.Unprotected, err = signature.header.sanitized()
if err != nil {
@@ -318,17 +324,20 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
return nil, ErrUnprotectedNonce
}
var err error
obj.Signatures[i].Header, err = obj.Signatures[i].mergedHeaders().sanitized()
if err != nil {
return nil, err
}
obj.Signatures[i].header = sig.Header
alg := SignatureAlgorithm(obj.Signatures[i].Header.Algorithm)
mergedHeaders := obj.Signatures[i].mergedHeaders()
alg := mergedHeaders.getSignatureAlgorithm()
if !containsSignatureAlgorithm(signatureAlgorithms, alg) {
return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms)
}
var err error
obj.Signatures[i].Header, err = mergedHeaders.sanitized()
if err != nil {
return nil, err
}
if obj.Signatures[i].header != nil {
obj.Signatures[i].Unprotected, err = obj.Signatures[i].header.sanitized()
if err != nil {
@@ -354,7 +363,6 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
// Copy value of sig
original := sig
obj.Signatures[i].header = sig.Header
obj.Signatures[i].original = &original
}
@@ -369,6 +377,10 @@ func parseSignedCompact(
payload []byte,
signatureAlgorithms []SignatureAlgorithm,
) (*JSONWebSignature, error) {
if len(input) == 0 {
return nil, errEmptyInput
}
protected, s, ok := strings.Cut(input, tokenDelim)
if !ok { // no period found
return nil, fmt.Errorf("go-jose/go-jose: compact JWS format must have three parts")
+5
View File
@@ -46,6 +46,11 @@ func newOpaqueSigner(alg SignatureAlgorithm, signer OpaqueSigner) (recipientSigI
return recipientSigInfo{}, ErrUnsupportedAlgorithm
}
pk := signer.Public()
if pk != nil && !pk.IsPublic() {
return recipientSigInfo{}, ErrNotPublic
}
return recipientSigInfo{
sigAlg: alg,
publicKey: signer.Public,
+17 -20
View File
@@ -80,6 +80,12 @@ var (
// ErrUnsupportedCriticalHeader is returned when a header is marked critical but not supported by go-jose.
ErrUnsupportedCriticalHeader = errors.New("go-jose/go-jose: unsupported critical header")
// errEmptyInput is returned when go-jose was asked to parse an empty string.
errEmptyInput = errors.New("go-jose/go-jose: empty input")
// ErrNotPublic indicates a private key was passed where a public key was expected
ErrNotPublic = errors.New("go-jose/go-jose: public key was unexpectedly not public")
)
// Key management algorithms
@@ -291,9 +297,10 @@ func (parsed rawHeader) getEPK() (*JSONWebKey, error) {
if v == nil {
return nil, nil
}
var epk *JSONWebKey
err := json.Unmarshal(*v, &epk)
if err != nil {
// RFC 7518 Section 4.6.1.1: the "epk" header is the ephemeral public key
// of the originator. Reject private key material before parsing it.
epk := new(JSONWebKey)
if err := epk.unmarshalJSON(*v, false); err != nil {
return nil, err
}
return epk, nil
@@ -319,20 +326,6 @@ func (parsed rawHeader) getTag() (*byteBuffer, error) {
return parsed.getByteBuffer(headerTag)
}
// getJWK extracts parsed "jwk" from the raw JSON.
func (parsed rawHeader) getJWK() (*JSONWebKey, error) {
v := parsed[headerJWK]
if v == nil {
return nil, nil
}
var jwk *JSONWebKey
err := json.Unmarshal(*v, &jwk)
if err != nil {
return nil, err
}
return jwk, nil
}
// getCritical extracts parsed "crit" from the raw JSON. If omitted, it
// returns an empty slice.
func (parsed rawHeader) getCritical() ([]string, error) {
@@ -418,10 +411,14 @@ func (parsed rawHeader) sanitized() (h Header, err error) {
}
switch k {
case headerJWK:
var jwk *JSONWebKey
err = json.Unmarshal(*v, &jwk)
// RFC 7515 Section 4.1.3 and RFC 7516 Section 4.1.5: the "jwk"
// header is the public key that corresponds to the key used to
// sign the JWS or encrypt the JWE. Reject private key material
// before parsing it.
jwk := new(JSONWebKey)
err = jwk.unmarshalJSON(*v, false)
if err != nil {
err = fmt.Errorf("failed to unmarshal JWK: %v: %#v", err, string(*v))
err = fmt.Errorf("failed to unmarshal JWK: %w", err)
return
}
h.JSONWebKey = jwk
+65 -46
View File
@@ -130,6 +130,8 @@ type payloadVerifier interface {
verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error
}
var errInvalidVerificationKey = errors.New("go-jose/go-jose: invalid verification key")
type genericSigner struct {
recipients []recipientSigInfo
nonceSource NonceSource
@@ -138,11 +140,21 @@ type genericSigner struct {
}
type recipientSigInfo struct {
sigAlg SignatureAlgorithm
sigAlg SignatureAlgorithm
// publicKey returns a synthetic JSONWebKey for the signer.
// For opaque signers, it calls OpaqueSigner.Public().
publicKey func() *JSONWebKey
signer payloadSigner
}
// getPublicKey gets the public key, with a nil check on the func.
func (r recipientSigInfo) getPublicKey() *JSONWebKey {
if r.publicKey == nil {
return nil
}
return r.publicKey()
}
func staticPublicKey(jwk *JSONWebKey) func() *JSONWebKey {
return func() *JSONWebKey {
return jwk
@@ -178,14 +190,23 @@ func NewMultiSigner(sigs []SigningKey, opts *SignerOptions) (Signer, error) {
func newVerifier(verificationKey interface{}) (payloadVerifier, error) {
switch verificationKey := verificationKey.(type) {
case ed25519.PublicKey:
if len(verificationKey) == 0 {
return nil, errInvalidVerificationKey
}
return &edEncrypterVerifier{
publicKey: verificationKey,
}, nil
case *rsa.PublicKey:
if verificationKey == nil {
return nil, errInvalidVerificationKey
}
return &rsaEncrypterVerifier{
publicKey: verificationKey,
}, nil
case *ecdsa.PublicKey:
if verificationKey == nil {
return nil, errInvalidVerificationKey
}
return &ecEncrypterVerifier{
publicKey: verificationKey,
}, nil
@@ -196,6 +217,9 @@ func newVerifier(verificationKey interface{}) (payloadVerifier, error) {
case JSONWebKey:
return newVerifier(verificationKey.Key)
case *JSONWebKey:
if verificationKey == nil {
return nil, errInvalidVerificationKey
}
return newVerifier(verificationKey.Key)
case OpaqueVerifier:
return &opaqueVerifier{verifier: verificationKey}, nil
@@ -240,18 +264,18 @@ func newJWKSigner(alg SignatureAlgorithm, signingKey JSONWebKey) (recipientSigIn
if err != nil {
return recipientSigInfo{}, err
}
if recipient.publicKey != nil && recipient.publicKey() != nil {
if recipientPubKey := recipient.getPublicKey(); recipientPubKey != nil {
// This should be impossible, but let's check anyway.
if !recipientPubKey.IsPublic() {
return recipientSigInfo{}, ErrNotPublic
}
// recipient.publicKey is a JWK synthesized for embedding when recipientSigInfo
// was created for the inner key (such as a RSA or ECDSA public key). It contains
// the pub key for embedding, but doesn't have extra params like key id.
publicKey := signingKey
publicKey.Key = recipient.publicKey().Key
publicKey.Key = recipientPubKey.Key
recipient.publicKey = staticPublicKey(&publicKey)
// This should be impossible, but let's check anyway.
if !recipient.publicKey().IsPublic() {
return recipientSigInfo{}, errors.New("go-jose/go-jose: public key was unexpectedly not public")
}
}
return recipient, nil
}
@@ -266,7 +290,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) {
headerAlgorithm: string(recipient.sigAlg),
}
if recipient.publicKey != nil && recipient.publicKey() != nil {
if recipientPubKey := recipient.getPublicKey(); recipientPubKey != nil {
// We want to embed the JWK or set the kid header, but not both. Having a protected
// header that contains an embedded JWK while also simultaneously containing the kid
// header is confusing, and at least in ACME the two are considered to be mutually
@@ -274,11 +298,11 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) {
// result of the JOSE spec. We've decided that this library will only include one or
// the other to avoid this confusion.
//
// See https://github.com/go-jose/go-jose/issues/157 for more context.
// See https://github.com/square/go-jose/issues/157 for more context.
if ctx.embedJWK {
protected[headerJWK] = recipient.publicKey()
protected[headerJWK] = recipientPubKey
} else {
keyID := recipient.publicKey().KeyID
keyID := recipientPubKey.KeyID
if keyID != "" {
protected[headerKeyID] = keyID
}
@@ -390,7 +414,13 @@ func (obj JSONWebSignature) UnsafePayloadWithoutVerification() []byte {
// The verificationKey argument must have one of the types allowed for the
// verificationKey argument of JSONWebSignature.Verify().
func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey interface{}) error {
key, err := tryJWKS(verificationKey, obj.headers()...)
if len(obj.Signatures) > 1 {
return errors.New("go-jose/go-jose: too many signatures in payload; expecting only one")
}
signature := obj.Signatures[0]
key, err := tryJWKS(verificationKey, signature.Header)
if err != nil {
return err
}
@@ -399,12 +429,6 @@ func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey inter
return err
}
if len(obj.Signatures) > 1 {
return errors.New("go-jose/go-jose: too many signatures in payload; expecting only one")
}
signature := obj.Signatures[0]
if signature.header != nil {
// Per https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.11,
// 4.1.11. "crit" (Critical) Header Parameter
@@ -432,11 +456,11 @@ func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey inter
headers := signature.mergedHeaders()
alg := headers.getSignatureAlgorithm()
err = verifier.verifyPayload(input, signature.Signature, alg)
if err == nil {
return nil
if err != nil {
return ErrCryptoFailure
}
return ErrCryptoFailure
return nil
}
// VerifyMulti validates (one of the multiple) signatures on the object and
@@ -467,16 +491,6 @@ func (obj JSONWebSignature) VerifyMulti(verificationKey interface{}) (int, Signa
// The verificationKey argument must have one of the types allowed for the
// verificationKey argument of JSONWebSignature.Verify().
func (obj JSONWebSignature) DetachedVerifyMulti(payload []byte, verificationKey interface{}) (int, Signature, error) {
key, err := tryJWKS(verificationKey, obj.headers()...)
if err != nil {
return -1, Signature{}, err
}
verifier, err := newVerifier(key)
if err != nil {
return -1, Signature{}, err
}
outer:
for i, signature := range obj.Signatures {
if signature.header != nil {
// Per https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.11,
@@ -484,20 +498,31 @@ outer:
// "When used, this Header Parameter MUST be integrity
// protected; therefore, it MUST occur only within the JWS
// Protected Header."
err = signature.header.checkNoCritical()
err := signature.header.checkNoCritical()
if err != nil {
continue outer
continue
}
}
if signature.protected != nil {
// Check for only supported critical headers
err = signature.protected.checkSupportedCritical(supportedCritical)
err := signature.protected.checkSupportedCritical(supportedCritical)
if err != nil {
continue outer
continue
}
}
// If the verification key is a JWK Set, pick a key based on this signature's
// "kid" header. If no match, skip this signature.
key, err := tryJWKS(verificationKey, signature.Header)
if err != nil {
continue
}
verifier, err := newVerifier(key)
if err != nil {
continue
}
input, err := obj.computeAuthData(payload, &signature)
if err != nil {
continue
@@ -506,18 +531,12 @@ outer:
headers := signature.mergedHeaders()
alg := headers.getSignatureAlgorithm()
err = verifier.verifyPayload(input, signature.Signature, alg)
if err == nil {
return i, signature, nil
if err != nil {
continue
}
return i, signature, nil
}
return -1, Signature{}, ErrCryptoFailure
}
func (obj JSONWebSignature) headers() []Header {
headers := make([]Header, len(obj.Signatures))
for i, sig := range obj.Signatures {
headers[i] = sig.Header
}
return headers
}
Loaded 100 of 330 files, more files were not shown because too many files have changed in this diff. Show more