Compare commits

..
Author SHA1 Message Date
dependabot[bot] bc97ff2cae build(deps): bump the minor-and-patch group across 1 directory with 13 updates
Bumps the minor-and-patch group with 13 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [github.com/davidbyttow/govips/v2](https://github.com/davidbyttow/govips) | `2.19.0` | `2.20.0` |
| [github.com/gabriel-vasile/mimetype](https://github.com/gabriel-vasile/mimetype) | `1.4.15` | `1.4.16` |
| [github.com/go-chi/chi/v5](https://github.com/go-chi/chi) | `5.3.2` | `5.5.0` |
| [github.com/grpc-ecosystem/grpc-gateway/v2](https://github.com/grpc-ecosystem/grpc-gateway) | `2.31.0` | `2.32.0` |
| [github.com/kovidgoyal/imaging](https://github.com/kovidgoyal/imaging) | `1.8.23` | `1.9.0` |
| [github.com/leonelquinteros/gotext](https://github.com/leonelquinteros/gotext) | `1.7.2` | `1.8.0` |
| [github.com/libregraph/lico](https://github.com/libregraph/lico) | `0.68.0` | `0.69.0` |
| [github.com/onsi/ginkgo/v2](https://github.com/onsi/ginkgo) | `2.33.0` | `2.33.1` |
| [github.com/open-policy-agent/opa](https://github.com/open-policy-agent/opa) | `1.21.1` | `1.21.4` |
| [github.com/shamaton/msgpack/v2](https://github.com/shamaton/msgpack) | `2.4.2` | `2.4.4` |
| [golang.org/x/exp](https://github.com/golang/exp) | `0.0.0-20260908205506-85c1c2202aba` | `0.0.0-20261014143641-f0251eb4aa3e` |
| [golang.org/x/image](https://github.com/golang/image) | `0.46.0` | `0.47.0` |
| [google.golang.org/genproto/googleapis/api](https://github.com/googleapis/go-genproto) | `0.0.0-20260928230214-8a89bd6388cc` | `0.0.0-20261012220534-4341edf3f941` |



Updates `github.com/davidbyttow/govips/v2` from 2.19.0 to 2.20.0
- [Release notes](https://github.com/davidbyttow/govips/releases)
- [Commits](https://github.com/davidbyttow/govips/compare/v2.19.0...v2.20.0)

Updates `github.com/gabriel-vasile/mimetype` from 1.4.15 to 1.4.16
- [Release notes](https://github.com/gabriel-vasile/mimetype/releases)
- [Commits](https://github.com/gabriel-vasile/mimetype/compare/v1.4.15...v1.4.16)

Updates `github.com/go-chi/chi/v5` from 5.3.2 to 5.5.0
- [Release notes](https://github.com/go-chi/chi/releases)
- [Changelog](https://github.com/go-chi/chi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/go-chi/chi/compare/v5.3.2...v5.5.0)

Updates `github.com/grpc-ecosystem/grpc-gateway/v2` from 2.31.0 to 2.32.0
- [Release notes](https://github.com/grpc-ecosystem/grpc-gateway/releases)
- [Commits](https://github.com/grpc-ecosystem/grpc-gateway/compare/v2.31.0...v2.32.0)

Updates `github.com/kovidgoyal/imaging` from 1.8.23 to 1.9.0
- [Release notes](https://github.com/kovidgoyal/imaging/releases)
- [Commits](https://github.com/kovidgoyal/imaging/compare/v1.8.23...v1.9.0)

Updates `github.com/leonelquinteros/gotext` from 1.7.2 to 1.8.0
- [Release notes](https://github.com/leonelquinteros/gotext/releases)
- [Commits](https://github.com/leonelquinteros/gotext/compare/v1.7.2...v1.8.0)

Updates `github.com/libregraph/lico` from 0.68.0 to 0.69.0
- [Changelog](https://github.com/libregraph/lico/blob/master/CHANGELOG.md)
- [Commits](https://github.com/libregraph/lico/compare/v0.68.0...v0.69.0)

Updates `github.com/onsi/ginkgo/v2` from 2.33.0 to 2.33.1
- [Release notes](https://github.com/onsi/ginkgo/releases)
- [Changelog](https://github.com/onsi/ginkgo/blob/master/CHANGELOG.md)
- [Commits](https://github.com/onsi/ginkgo/compare/v2.33.0...v2.33.1)

Updates `github.com/open-policy-agent/opa` from 1.21.1 to 1.21.4
- [Release notes](https://github.com/open-policy-agent/opa/releases)
- [Changelog](https://github.com/open-policy-agent/opa/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-policy-agent/opa/compare/v1.21.1...v1.21.4)

Updates `github.com/shamaton/msgpack/v2` from 2.4.2 to 2.4.4
- [Release notes](https://github.com/shamaton/msgpack/releases)
- [Changelog](https://github.com/shamaton/msgpack/blob/v2.4.4/CHANGELOG.md)
- [Commits](https://github.com/shamaton/msgpack/compare/v2.4.2...v2.4.4)

Updates `golang.org/x/exp` from 0.0.0-20260908205506-85c1c2202aba to 0.0.0-20261014143641-f0251eb4aa3e
- [Commits](https://github.com/golang/exp/commits)

Updates `golang.org/x/image` from 0.46.0 to 0.47.0
- [Commits](https://github.com/golang/image/compare/v0.46.0...v0.47.0)

Updates `google.golang.org/genproto/googleapis/api` from 0.0.0-20260928230214-8a89bd6388cc to 0.0.0-20261012220534-4341edf3f941
- [Commits](https://github.com/googleapis/go-genproto/commits)

---
updated-dependencies:
- dependency-name: github.com/davidbyttow/govips/v2
  dependency-version: 2.20.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/gabriel-vasile/mimetype
  dependency-version: 1.4.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/go-chi/chi/v5
  dependency-version: 5.5.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/grpc-ecosystem/grpc-gateway/v2
  dependency-version: 2.32.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/kovidgoyal/imaging
  dependency-version: 1.9.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/leonelquinteros/gotext
  dependency-version: 1.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/libregraph/lico
  dependency-version: 0.69.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/onsi/ginkgo/v2
  dependency-version: 2.33.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/open-policy-agent/opa
  dependency-version: 1.21.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/shamaton/msgpack/v2
  dependency-version: 2.4.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/exp
  dependency-version: 0.0.0-20261014143641-f0251eb4aa3e
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/image
  dependency-version: 0.47.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: google.golang.org/genproto/googleapis/api
  dependency-version: 0.0.0-20261012220534-4341edf3f941
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-30 13:58:52 +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
489 changed files with 32590 additions and 10294 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,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
+24 -24
View File
@@ -1,6 +1,6 @@
module github.com/owncloud/ocis/v2
go 1.26.8
go 1.27
require (
dario.cat/mergo v1.0.2
@@ -16,13 +16,13 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3
github.com/coreos/go-oidc/v3 v3.21.0
github.com/cs3org/go-cs3apis v0.0.0-20241105092511-3ad35d174fc1
github.com/davidbyttow/govips/v2 v2.19.0
github.com/davidbyttow/govips/v2 v2.20.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
github.com/dutchcoders/go-clamd v0.0.0-20170520113014-b970184f4d9e
github.com/egirna/icap-client v0.1.1
github.com/gabriel-vasile/mimetype v1.4.15
github.com/gabriel-vasile/mimetype v1.4.16
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.3.2
github.com/go-chi/chi/v5 v5.5.0
github.com/go-chi/httprate v0.16.1
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.15
@@ -45,16 +45,16 @@ require (
github.com/gookit/config/v2 v2.2.9
github.com/gorilla/mux v1.8.1
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.32.0
github.com/invopop/validation v0.8.0
github.com/jellydator/ttlcache/v2 v2.11.1
github.com/jellydator/ttlcache/v3 v3.4.1
github.com/jinzhu/now v1.1.5
github.com/justinas/alice v1.2.0
github.com/kovidgoyal/imaging v1.8.23
github.com/leonelquinteros/gotext v1.7.2
github.com/kovidgoyal/imaging v1.9.0
github.com/leonelquinteros/gotext v1.8.0
github.com/libregraph/idm v0.5.0
github.com/libregraph/lico v0.68.0
github.com/libregraph/lico v0.69.0
github.com/mitchellh/mapstructure v1.5.0
github.com/mna/pigeon v1.3.0
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
@@ -62,12 +62,12 @@ require (
github.com/nats-io/nats.go v1.54.0
github.com/olekukonko/tablewriter v1.1.5
github.com/onsi/ginkgo v1.16.5
github.com/onsi/ginkgo/v2 v2.33.0
github.com/onsi/ginkgo/v2 v2.33.1
github.com/onsi/gomega v1.44.0
github.com/open-policy-agent/opa v1.21.1
github.com/open-policy-agent/opa v1.21.4
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
@@ -75,7 +75,7 @@ require (
github.com/rogpeppe/go-internal v1.16.0
github.com/rs/cors v1.11.1
github.com/rs/zerolog v1.35.1
github.com/shamaton/msgpack/v2 v2.4.2
github.com/shamaton/msgpack/v2 v2.4.4
github.com/sirupsen/logrus v1.10.2
github.com/spf13/afero v1.15.0
github.com/spf13/cobra v1.10.2
@@ -97,15 +97,15 @@ 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/exp v0.0.0-20260908205506-85c1c2202aba
golang.org/x/image v0.46.0
golang.org/x/net v0.60.0
golang.org/x/crypto v0.58.0
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e
golang.org/x/image v0.47.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
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
golang.org/x/term v0.47.0
golang.org/x/text v0.43.0
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941
google.golang.org/grpc v1.86.0-dev
google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v2 v2.4.0
@@ -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
@@ -340,12 +340,12 @@ require (
go.uber.org/zap v1.27.1 // indirect
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/mod v0.42.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.52.0 // indirect
google.golang.org/genproto v0.0.0-20260622175928-b703f567277d // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261005182115-fad411399dd8 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
+46 -46
View File
@@ -209,8 +209,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidbyttow/govips/v2 v2.19.0 h1:vIFpRodf/jrQlnKetj0BaQ1OwGNR+bR+QIBQ2sgxtxc=
github.com/davidbyttow/govips/v2 v2.19.0/go.mod h1:QK5liLrx7YaHC7xPcYnm4KaQIYvu9xSGrBt9goXrfgo=
github.com/davidbyttow/govips/v2 v2.20.0 h1:sftLOcLeI+sMPVrBiw/ulWHuMm0kKyTQ2hfnoIYSxwc=
github.com/davidbyttow/govips/v2 v2.20.0/go.mod h1:QK5liLrx7YaHC7xPcYnm4KaQIYvu9xSGrBt9goXrfgo=
github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4=
github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo=
@@ -266,8 +266,8 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/gdexlab/go-render v1.0.1 h1:rxqB3vo5s4n1kF0ySmoNeSPRYkEsyHgln4jFIQY7v0U=
github.com/gdexlab/go-render v1.0.1/go.mod h1:wRi5nW2qfjiGj4mPukH4UV0IknS1cHD4VgFTmJX5JzM=
github.com/ggwhite/go-masker v1.1.0 h1:kN/KIvktu2U+hd3KWrSlLj7xBGD1iBfc9/xdbVgFbRc=
@@ -286,8 +286,8 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro
github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
@@ -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=
@@ -499,8 +499,8 @@ github.com/gorilla/schema v1.4.1 h1:jUg5hUjCSDZpNGLuXQOgIWGdlgrIdYvgQ0wZtdK1M3E=
github.com/gorilla/schema v1.4.1/go.mod h1:Dg5SSm5PV60mhF2NFaTV1xuYYj8tV8NOPRo4FggUMnM=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.32.0 h1:QMILzF8BA7xftE4zVORkRrlv08m12St3csK4RsyRgRs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.32.0/go.mod h1:+ZQ6iUL8+ATyxGDQNuRKpNwJFdGDUi0e7E1QL9MvI7U=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-plugin v1.8.0 h1:ie8S6RRY8RvB2usYZv+AAZ/wBvx2AU5p5QeP5j/FORs=
@@ -594,8 +594,8 @@ github.com/kovidgoyal/go-parallel v1.1.1 h1:1OzpNjtrUkBPq3UaqrnvOoB2F9RttSt811ui
github.com/kovidgoyal/go-parallel v1.1.1/go.mod h1:BJNIbe6+hxyFWv7n6oEDPj3PA5qSw5OCtf0hcVxWJiw=
github.com/kovidgoyal/go-shm v1.0.0 h1:HJEel9D1F9YhULvClEHJLawoRSj/1u/EDV7MJbBPgQo=
github.com/kovidgoyal/go-shm v1.0.0/go.mod h1:Yzb80Xf9L3kaoB2RGok9hHwMIt7Oif61kT6t3+VnZds=
github.com/kovidgoyal/imaging v1.8.23 h1:4WsboyQ/E8tic2kX49P93Rvscg33SPsCwTBG5EZZF54=
github.com/kovidgoyal/imaging v1.8.23/go.mod h1:k3Iot3H0v2rSWXIxQISfT3e9wIryqzAHLHCuhG7z9lM=
github.com/kovidgoyal/imaging v1.9.0 h1:TxHvhClPANvDW7eLm7PYDTZU1KE15xbqlFv95DA6DmY=
github.com/kovidgoyal/imaging v1.9.0/go.mod h1:t2vWMc3uISm/jMP87nBCcZUcAK6EDUdgumwaXSuz0Jc=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
@@ -609,8 +609,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/leonelquinteros/gotext v1.7.2 h1:bDPndU8nt+/kRo1m4l/1OXiiy2v7Z7dfPQ9+YP7G1Mc=
github.com/leonelquinteros/gotext v1.7.2/go.mod h1:9/haCkm5P7Jay1sxKDGJ5WIg4zkz8oZKw4ekNpALob8=
github.com/leonelquinteros/gotext v1.8.0 h1:wwpxINWmWq3JN3WFI9BoSupBFrvAqxZTtf3qppijYkU=
github.com/leonelquinteros/gotext v1.8.0/go.mod h1:Wqke380+8unZq2F4oTmmqmbUY9zWQMzwImdC34XOAo8=
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
github.com/lestrrat-go/dsig v1.4.0 h1:g7LUjK8cT74A5DzBXJI5HzsJuLhoYN0Wzj4nuOMIrH8=
@@ -627,8 +627,8 @@ github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLO
github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
github.com/libregraph/idm v0.5.0 h1:tDMwKbAOZzdeDYMxVlY5PbSqRKO7dbAW9KT42A51WSk=
github.com/libregraph/idm v0.5.0/go.mod h1:BGMwIQ/6orJSPVzJ1x6kgG2JyG9GY05YFmbsnaD80k0=
github.com/libregraph/lico v0.68.0 h1:vzyxmawdWNEtLYV1GRhudZ4Kd78Hn9sZYdOpfyouFfk=
github.com/libregraph/lico v0.68.0/go.mod h1:QTteGTUpRjYdOyVatgF1NhOItrLbm5whJwm90ddy4UE=
github.com/libregraph/lico v0.69.0 h1:Rf5hhKcge0YgFN7cv39jkdZw9JW2o8yc3EntX/HzHCU=
github.com/libregraph/lico v0.69.0/go.mod h1:3PGOw3BxF5fbWdj8jj35xnrvZPGR2f2TqIz8rdlEgUQ=
github.com/libregraph/oidc-go v1.1.0 h1:RyudjL3UyQblqeBQI06W53PniWobqODeeyAy6v/HumA=
github.com/libregraph/oidc-go v1.1.0/go.mod h1:qW9ubcXvZrfbbWZBaLMuk7bt5qAUMYyt9/NtXQt07Cw=
github.com/longsleep/go-metrics v1.0.0 h1:o2A6Dbu4MhLpZuL444WFoZzM7X7igewrj2MouwTlmVM=
@@ -721,14 +721,14 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.33.0 h1:C8gBA6Uc2ZEubiV+SXiu5tZnMTwEmXHgkJwGozKtZf8=
github.com/onsi/ginkgo/v2 v2.33.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
github.com/onsi/ginkgo/v2 v2.33.1 h1:62XfWJbEIjPSCSDYrsCPP/SHcmH7O0M8ne8zfqQ2iz4=
github.com/onsi/ginkgo/v2 v2.33.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ=
github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA=
github.com/open-policy-agent/opa v1.21.1 h1:j6NIMLmdOPUTp9+1fgtWLqbOPqwkTaxNm4T3ngtUB48=
github.com/open-policy-agent/opa v1.21.1/go.mod h1:eJL6KUOIaW5YLnhJEA6sm3FOYRDJaHZvYT6geATbpPk=
github.com/open-policy-agent/opa v1.21.4 h1:zTVuy8yd8BM715t8WxMzAIkIX4w1x3MMHEv99IGUY2w=
github.com/open-policy-agent/opa v1.21.4/go.mod h1:mHDS61rXyiZ+9bLINSK634BcbPZcsZChPvSwFVMj88g=
github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-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-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=
@@ -838,8 +838,8 @@ github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sethvargo/go-password v0.4.0 h1:eSidVKQw5C7CmTDAtH3RipBTSjdU1ZRxQaynD2GWLVU=
github.com/sethvargo/go-password v0.4.0/go.mod h1:PO3nYHwUpcHPR0F9woy7a4abZPvzRuqJr0GaeIYTm3k=
github.com/shamaton/msgpack/v2 v2.4.2 h1:ukiqiwF8rIb8EG6hD8iPha3g85AC7EdCxFyobDj6oHk=
github.com/shamaton/msgpack/v2 v2.4.2/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
github.com/shamaton/msgpack/v2 v2.4.4 h1:O9ZkRWswpX6ZaqmYZEktiHKk9aDrYk4hwIxQ4C290Uo=
github.com/shamaton/msgpack/v2 v2.4.4/go.mod h1:6khjYnkx73f7VQU7wjcFS9DFjs+59naVWJv1TB7qdOI=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
@@ -1018,8 +1018,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=
@@ -1030,12 +1030,12 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU=
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E=
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A=
golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
@@ -1057,8 +1057,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -1102,8 +1102,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 +1191,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 +1200,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 +1213,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 +1267,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.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
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=
@@ -1329,10 +1329,10 @@ google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6D
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20260622175928-b703f567277d h1:CP5omUq8AJTiWMrPKM1WRLJ7zZeXd9OPcQD3TbBNAyY=
google.golang.org/genproto v0.0.0-20260622175928-b703f567277d/go.mod h1:DrwuGJgFSEVNpv3S5Q5VxhRTvdnjauw9GtvwVOEARfA=
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE=
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 h1:DS/w3N8rsfrwxwgGSj6WhMsPo7aNQGmDx74J81zd0NQ=
google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941/go.mod h1:AuGAdi9KnXss7xbLxIKhCvk+Ro/SxpET/iS45DNYN+M=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261005182115-fad411399dd8 h1:0SXBqli5dnuCKMjI/X3FM226zEaEa0GUcSCJtN1vL2o=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261005182115-fad411399dd8/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
+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) {
+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
+23 -1
View File
@@ -230,6 +230,14 @@ int save_buffer(const char *operationName, SaveParams *params,
return 1;
}
// "keep" is set here rather than in each per-format setter so every
// saver gets it the same way. It overrides the deprecated "strip".
if (params->keepSet &&
vips_object_set(VIPS_OBJECT(operation), "keep", params->keep, NULL)) {
g_object_unref(operation);
return 1;
}
if (vips_cache_operation_buildp(&operation)) {
vips_object_unref_outputs(VIPS_OBJECT(operation));
g_object_unref(operation);
@@ -300,12 +308,24 @@ int set_webpsave_options(VipsOperation *operation, SaveParams *params) {
"lossless", params->webpLossless,
"near_lossless", params->webpNearLossless,
"reduction_effort", params->webpReductionEffort,
"profile", params->webpIccProfile ? params->webpIccProfile : "none",
"min_size", params->webpMinSize,
"kmin", params->webpKMin,
"kmax", params->webpKMax,
NULL);
// Only pass a profile the caller chose; leaving "profile" unset lets
// strip/keep decide about the source image's own ICC, as for the other
// savers. With StripMetadata and no Keep, still pass "none": webpsave in
// libvips 8.14.0-8.14.1 ignores "strip" (a shadowed field, fixed in
// 8.14.2), and "none" is what keeps the ICC out there. Elsewhere strip
// already drops it.
if (!ret && params->webpIccProfile) {
ret = vips_object_set(VIPS_OBJECT(operation), "profile",
params->webpIccProfile, NULL);
} else if (!ret && params->stripMetadata && !params->keepSet) {
ret = vips_object_set(VIPS_OBJECT(operation), "profile", "none", NULL);
}
if (!ret && params->quality) {
ret = vips_object_set(VIPS_OBJECT(operation), "Q", params->quality, NULL);
}
@@ -551,6 +571,8 @@ static SaveParams defaultSaveParams = {
.interlace = FALSE,
.quality = 0,
.stripMetadata = FALSE,
.keep = 0,
.keepSet = FALSE,
.jpegOptimizeCoding = FALSE,
.jpegSubsample = VIPS_FOREIGN_SUBSAMPLE_ON,
+143 -17
View File
@@ -25,6 +25,74 @@ const (
VipsForeignSubsampleLast SubsampleMode = C.VIPS_FOREIGN_SUBSAMPLE_LAST
)
// ForeignKeep flags select which metadata a saver retains (libvips's "keep"
// save option, libvips 8.15+). Values may be combined with |.
//
// The values are libvips's VipsForeignKeep bits written as literals rather
// than C.VIPS_FOREIGN_KEEP_* because those macros don't exist in the
// libvips 8.14 headers govips still builds against.
const (
// ForeignKeepNone keeps no metadata. It is a Go-only sentinel (like
// KernelAuto) translated to VIPS_FOREIGN_KEEP_NONE (0) before reaching
// libvips, because the zero value of the Keep fields means "unset".
// It is a high bit rather than -1 so that it still composes with |.
ForeignKeepNone ForeignKeep = 1 << 30
ForeignKeepExif ForeignKeep = 1 << 0
ForeignKeepXmp ForeignKeep = 1 << 1
ForeignKeepIptc ForeignKeep = 1 << 2
ForeignKeepIcc ForeignKeep = 1 << 3
ForeignKeepOther ForeignKeep = 1 << 4
// ForeignKeepGainmap keeps the UltraHDR gain map (libvips 8.18+). Older
// libvips cannot load gain maps, so the bit is dropped there: combined
// with other flags it changes nothing, but on its own it keeps no
// metadata at all, exactly like ForeignKeepNone.
ForeignKeepGainmap ForeignKeep = 1 << 5
// ForeignKeepAll keeps all metadata the running libvips supports.
ForeignKeepAll = ForeignKeepExif | ForeignKeepXmp | ForeignKeepIptc |
ForeignKeepIcc | ForeignKeepOther | ForeignKeepGainmap
)
// errKeepUnsupported is returned by resolveKeep when the libvips version
// predates the "keep" save option.
var errKeepUnsupported = errors.New("keep requires libvips 8.15+")
// resolveKeep maps a ForeignKeep value to the libvips "keep" flags for the
// given libvips version. set is false when k is unset (zero), in which case
// the caller must not pass "keep" at all and StripMetadata decides.
func resolveKeep(k ForeignKeep, major, minor int) (flags int, set bool, err error) {
if k == 0 {
return 0, false, nil
}
if major < 8 || (major == 8 && minor < 15) {
return 0, false, errKeepUnsupported
}
if unknown := k &^ (ForeignKeepAll | ForeignKeepNone); unknown != 0 {
return 0, false, fmt.Errorf("unknown ForeignKeep bits: %#x", int(unknown))
}
k &^= ForeignKeepNone
if major == 8 && minor < 18 {
// libvips before 8.18 doesn't know VIPS_FOREIGN_KEEP_GAINMAP.
k &^= ForeignKeepGainmap
}
return int(k), true, nil
}
// applyKeep validates k against the running libvips and stores it in p.
// Every save-param builder calls it, so the buffer and streaming paths
// share one version guard.
func applyKeep(p *C.struct_SaveParams, k ForeignKeep) error {
flags, set, err := resolveKeep(k, MajorVersion, MinorVersion)
if errors.Is(err, errKeepUnsupported) {
return fmt.Errorf("Keep requires libvips 8.15+, found %s", Version)
}
if err != nil {
return err
}
p.keep = C.int(flags)
p.keepSet = C.int(boolToInt(set))
return nil
}
// ImageType represents an image type
type ImageType int
@@ -398,7 +466,7 @@ func createImportParams(format ImageType, params *ImportParams) C.LoadParams {
return p
}
func newSaveParamsJPEG(in *C.VipsImage, params JpegExportParams) C.struct_SaveParams {
func newSaveParamsJPEG(in *C.VipsImage, params JpegExportParams) (C.struct_SaveParams, error) {
p := C.create_save_params(C.JPEG)
p.inputImage = in
p.stripMetadata = C.int(boolToInt(params.StripMetadata))
@@ -410,16 +478,23 @@ func newSaveParamsJPEG(in *C.VipsImage, params JpegExportParams) C.struct_SavePa
p.jpegOvershootDeringing = C.int(boolToInt(params.OvershootDeringing))
p.jpegOptimizeScans = C.int(boolToInt(params.OptimizeScans))
p.jpegQuantTable = C.int(params.QuantTable)
return p
if err := applyKeep(&p, params.Keep); err != nil {
return p, err
}
return p, nil
}
func vipsSaveJPEGToBuffer(in *C.VipsImage, params JpegExportParams) ([]byte, error) {
incOpCounter("save_jpeg_buffer")
return vipsSaveToBuffer(newSaveParamsJPEG(in, params))
p, err := newSaveParamsJPEG(in, params)
if err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
func newSaveParamsPNG(in *C.VipsImage, params PngExportParams) C.struct_SaveParams {
func newSaveParamsPNG(in *C.VipsImage, params PngExportParams) (C.struct_SaveParams, error) {
p := C.create_save_params(C.PNG)
p.inputImage = in
p.quality = C.int(params.Quality)
@@ -430,13 +505,20 @@ func newSaveParamsPNG(in *C.VipsImage, params PngExportParams) C.struct_SavePara
p.pngPalette = C.int(boolToInt(params.Palette))
p.pngDither = C.double(params.Dither)
p.pngBitdepth = C.int(params.Bitdepth)
return p
if err := applyKeep(&p, params.Keep); err != nil {
return p, err
}
return p, nil
}
func vipsSavePNGToBuffer(in *C.VipsImage, params PngExportParams) ([]byte, error) {
incOpCounter("save_png_buffer")
return vipsSaveToBuffer(newSaveParamsPNG(in, params))
p, err := newSaveParamsPNG(in, params)
if err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
// newSaveParamsWebP returns the populated params and a cleanup function
@@ -468,9 +550,20 @@ func newSaveParamsWebP(in *C.VipsImage, params WebpExportParams) (C.struct_SaveP
p.webpTargetSize = C.int(params.TargetSize)
}
if err := applyKeep(&p, params.Keep); err != nil {
return p, noop, err
}
iccProfile := params.IccProfile
if p.keepSet != 0 && ForeignKeep(p.keep)&ForeignKeepIcc == 0 {
// An explicit Keep without ICC wins over any profile: libvips
// would otherwise embed a supplied profile regardless of keep.
iccProfile = ""
}
cleanup := noop
if params.IccProfile != "" {
p.webpIccProfile = C.CString(params.IccProfile)
if iccProfile != "" {
p.webpIccProfile = C.CString(iccProfile)
profile := p.webpIccProfile
cleanup = func() { C.free(unsafe.Pointer(profile)) }
}
@@ -489,7 +582,7 @@ func vipsSaveWebPToBuffer(in *C.VipsImage, params WebpExportParams) ([]byte, err
return vipsSaveToBuffer(p)
}
func newSaveParamsTIFF(in *C.VipsImage, params TiffExportParams) C.struct_SaveParams {
func newSaveParamsTIFF(in *C.VipsImage, params TiffExportParams) (C.struct_SaveParams, error) {
p := C.create_save_params(C.TIFF)
p.inputImage = in
p.stripMetadata = C.int(boolToInt(params.StripMetadata))
@@ -507,16 +600,23 @@ func newSaveParamsTIFF(in *C.VipsImage, params TiffExportParams) C.struct_SavePa
}
p.tiffTileHeight = C.int(tileHeight)
p.tiffTileWidth = C.int(tileWidth)
return p
if err := applyKeep(&p, params.Keep); err != nil {
return p, err
}
return p, nil
}
func vipsSaveTIFFToBuffer(in *C.VipsImage, params TiffExportParams) ([]byte, error) {
incOpCounter("save_tiff_buffer")
return vipsSaveToBuffer(newSaveParamsTIFF(in, params))
p, err := newSaveParamsTIFF(in, params)
if err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
func newSaveParamsHEIF(in *C.VipsImage, params HeifExportParams) C.struct_SaveParams {
func newSaveParamsHEIF(in *C.VipsImage, params HeifExportParams) (C.struct_SaveParams, error) {
p := C.create_save_params(C.HEIF)
p.inputImage = in
p.outputFormat = C.HEIF
@@ -524,13 +624,20 @@ func newSaveParamsHEIF(in *C.VipsImage, params HeifExportParams) C.struct_SavePa
p.heifLossless = C.int(boolToInt(params.Lossless))
p.heifBitdepth = C.int(params.Bitdepth)
p.heifEffort = C.int(params.Effort)
return p
if err := applyKeep(&p, params.Keep); err != nil {
return p, err
}
return p, nil
}
func vipsSaveHEIFToBuffer(in *C.VipsImage, params HeifExportParams) ([]byte, error) {
incOpCounter("save_heif_buffer")
return vipsSaveToBuffer(newSaveParamsHEIF(in, params))
p, err := newSaveParamsHEIF(in, params)
if err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
func vipsSaveAVIFToBuffer(in *C.VipsImage, params AvifExportParams) ([]byte, error) {
@@ -550,6 +657,9 @@ func vipsSaveAVIFToBuffer(in *C.VipsImage, params AvifExportParams) ([]byte, err
p.heifLossless = C.int(boolToInt(params.Lossless))
p.heifBitdepth = C.int(params.Bitdepth)
p.heifEffort = C.int(effort)
if err := applyKeep(&p, params.Keep); err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
@@ -565,24 +675,34 @@ func vipsSaveJP2KToBuffer(in *C.VipsImage, params Jp2kExportParams) ([]byte, err
p.jp2kTileWidth = C.int(params.TileWidth)
p.jp2kTileHeight = C.int(params.TileHeight)
p.jpegSubsample = C.VipsForeignSubsample(params.SubsampleMode)
if err := applyKeep(&p, params.Keep); err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
func newSaveParamsGIF(in *C.VipsImage, params GifExportParams) C.struct_SaveParams {
func newSaveParamsGIF(in *C.VipsImage, params GifExportParams) (C.struct_SaveParams, error) {
p := C.create_save_params(C.GIF)
p.inputImage = in
p.quality = C.int(params.Quality)
p.gifDither = C.double(params.Dither)
p.gifEffort = C.int(params.Effort)
p.gifBitdepth = C.int(params.Bitdepth)
return p
if err := applyKeep(&p, params.Keep); err != nil {
return p, err
}
return p, nil
}
func vipsSaveGIFToBuffer(in *C.VipsImage, params GifExportParams) ([]byte, error) {
incOpCounter("save_gif_buffer")
return vipsSaveToBuffer(newSaveParamsGIF(in, params))
p, err := newSaveParamsGIF(in, params)
if err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
func vipsSaveJxlToBuffer(in *C.VipsImage, params JxlExportParams) ([]byte, error) {
@@ -596,6 +716,9 @@ func vipsSaveJxlToBuffer(in *C.VipsImage, params JxlExportParams) ([]byte, error
p.jxlTier = C.int(params.Tier)
p.jxlDistance = C.double(params.Distance)
p.jxlEffort = C.int(params.Effort)
if err := applyKeep(&p, params.Keep); err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
@@ -617,6 +740,9 @@ func vipsSaveMagickToBuffer(in *C.VipsImage, params MagickExportParams) ([]byte,
p.magickOptimizeGifFrames = C.int(boolToInt(params.OptimizeGifFrames))
p.magickOptimizeGifTransparency = C.int(boolToInt(params.OptimizeGifTransparency))
p.magickBitDepth = C.int(params.BitDepth)
if err := applyKeep(&p, params.Keep); err != nil {
return nil, err
}
return vipsSaveToBuffer(p)
}
+4
View File
@@ -82,6 +82,10 @@ typedef struct SaveParams {
size_t outputLen;
BOOL stripMetadata;
// libvips "keep" flags (VipsForeignKeep, 8.15+). Plain int so the header
// still compiles against libvips 8.14; only applied when keepSet.
int keep;
BOOL keepSet;
int quality;
BOOL interlace;
+80
View File
@@ -255,6 +255,13 @@ type JpegExportParams struct {
OvershootDeringing bool
OptimizeScans bool
QuantTable int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewJpegExportParams creates default values for an export of a JPEG image.
@@ -277,6 +284,13 @@ type PngExportParams struct {
Dither float64
Bitdepth int
Profile string
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewPngExportParams creates default values for an export of a PNG image.
@@ -314,6 +328,23 @@ type WebpExportParams struct {
// Requires libvips 8.17.4+ (when target_size was added to webpsave);
// ExportWebp returns an error if TargetSize is set on an older libvips.
TargetSize int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata decides,
// as for the other formats: the source image's ICC profile is kept
// unless StripMetadata is set. A profile from IccProfile or
// OptimizeICCProfile replaces the source profile and is embedded even
// when StripMetadata is set. When set, Keep takes precedence over
// StripMetadata, and it
// alone decides whether an ICC profile is written: without
// ForeignKeepIcc no profile is embedded, whatever its source. With
// ForeignKeepIcc, the embedded profile is the one the path already
// chooses: ExportWebp uses the profile picked by OptimizeICCProfile
// (and ignores IccProfile, as before), while SaveToWriterWebp uses
// IccProfile. With neither, the source image's profile is kept.
// Requires libvips 8.15+; saving returns an error if Keep is set on an
// older libvips.
Keep ForeignKeep
}
// NewWebpExportParams creates default values for an export of a WEBP image.
@@ -337,6 +368,13 @@ type TiffExportParams struct {
Tile bool
TileHeight int
TileWidth int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewTiffExportParams creates default values for an export of a TIFF image.
@@ -370,6 +408,13 @@ type GifExportParams struct {
Dither float64
Effort int
Bitdepth int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewGifExportParams creates default values for an export of a GIF image.
@@ -387,6 +432,13 @@ type HeifExportParams struct {
Bitdepth int
Effort int
Lossless bool
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewHeifExportParams creates default values for an export of a HEIF image.
@@ -409,6 +461,13 @@ type AvifExportParams struct {
// DEPRECATED - Use Effort instead.
Speed int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewAvifExportParams creates default values for an export of an AVIF image.
@@ -428,6 +487,13 @@ type Jp2kExportParams struct {
TileWidth int
TileHeight int
SubsampleMode SubsampleMode
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewJp2kExportParams creates default values for an export of an JPEG2000 image.
@@ -447,6 +513,13 @@ type JxlExportParams struct {
Tier int
Distance float64
Effort int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewJxlExportParams creates default values for an export of an JXL image.
@@ -466,6 +539,13 @@ type MagickExportParams struct {
OptimizeGifFrames bool
OptimizeGifTransparency bool
BitDepth int
// Keep selects which metadata to retain (libvips's "keep" option; see
// ForeignKeep). The zero value leaves it unset, so StripMetadata (where
// present) decides as before. When set, it takes precedence over
// StripMetadata. Requires libvips 8.15+; saving returns an error if Keep
// is set on an older libvips.
Keep ForeignKeep
}
// NewMagickExportParams creates default values for an export of an image by ImageMagick.
+63 -11
View File
@@ -79,8 +79,27 @@ func (r *ImageRef) ResizeWithVScale(hScale, vScale float64, kernel Kernel) error
return err
}
pages := r.Pages()
pageHeight := r.PageHeight()
pages := r.loadedPages()
newPageHeight := 0
if pages > 1 {
scale := hScale
if vScale > 0 {
scale = vScale
}
newPageHeight = int(math.Round(float64(r.PageHeight()) * scale))
if newPageHeight < 1 {
newPageHeight = 1
}
// libvips resizes the stacked frames as one strip, so rounding the
// strip and the page height separately can leave the strip a few
// rows short of pages*newPageHeight (#350, #554). When that happens,
// pick the vertical scale that makes the strip height exact, as
// vips_thumbnail does. Output is unchanged when the rounding agrees.
height := r.Height()
if int(math.Round(float64(height)*scale)) != pages*newPageHeight {
vScale = float64(pages*newPageHeight) / float64(height)
}
}
out, err := vipsResizeWithVScale(r.image, hScale, vScale, kernel)
if err != nil {
@@ -89,11 +108,6 @@ func (r *ImageRef) ResizeWithVScale(hScale, vScale float64, kernel Kernel) error
r.setImage(out)
if pages > 1 {
scale := hScale
if vScale != -1 {
scale = vScale
}
newPageHeight := int(math.Round(float64(pageHeight) * scale))
if err := r.SetPageHeight(newPageHeight); err != nil {
return err
}
@@ -102,6 +116,16 @@ func (r *ImageRef) ResizeWithVScale(hScale, vScale float64, kernel Kernel) error
return r.UnpremultiplyAlpha()
}
// loadedPages is the number of pages stacked in the image. Pages() reports
// the page count of the file, which is larger when only some were loaded.
func (r *ImageRef) loadedPages() int {
pageHeight := r.PageHeight()
if pageHeight <= 0 {
return 1
}
return r.Height() / pageHeight
}
// Thumbnail resizes the image to the given width and height.
// crop decides algorithm vips uses to shrink and crop to fill target,
func (r *ImageRef) Thumbnail(width, height int, crop Interesting) error {
@@ -196,11 +220,17 @@ func (r *ImageRef) EmbedBackgroundRGBA(left, top, width, height int, backgroundC
// Zoom zooms the image by repeating pixels (fast nearest-neighbour)
func (r *ImageRef) Zoom(xFactor int, yFactor int) error {
defer runtime.KeepAlive(r)
pages := r.loadedPages()
pageHeight := r.PageHeight()
out, err := vipsGenZoom(r.image, xFactor, yFactor)
if err != nil {
return err
}
r.setImage(out)
if pages > 1 {
// Zooming the strip zooms every frame; only the page height is stale.
return r.SetPageHeight(pageHeight * yFactor)
}
return nil
}
@@ -218,7 +248,16 @@ func (r *ImageRef) Gravity(gravity Gravity, width int, height int) error {
// Flip flips the image either horizontally or vertically based on the parameter
func (r *ImageRef) Flip(direction Direction) error {
defer runtime.KeepAlive(r)
out, err := vipsFlip(r.image, direction)
var out *C.VipsImage
var err error
if direction == DirectionVertical && r.loadedPages() > 1 {
// Flipping the strip would reverse the frame order.
out, err = vipsMapPages(r.image, func(page *C.VipsImage) (*C.VipsImage, error) {
return vipsFlip(page, direction)
})
} else {
out, err = vipsFlip(r.image, direction)
}
if err != nil {
return err
}
@@ -279,15 +318,28 @@ func (r *ImageRef) Recomb(matrix [][]float64) error {
func (r *ImageRef) Rotate(angle Angle) error {
defer runtime.KeepAlive(r)
width := r.Width()
pages := r.loadedPages()
if r.Pages() > 1 && (angle == Angle90 || angle == Angle270) {
if pages > 1 && angle == Angle180 {
// Rotating the strip would reverse the frame order.
out, err := vipsMapPages(r.image, func(page *C.VipsImage) (*C.VipsImage, error) {
return vipsGenRot(page, angle)
})
if err != nil {
return err
}
r.setImage(out)
return nil
}
if pages > 1 && (angle == Angle90 || angle == Angle270) {
if angle == Angle270 {
if err := r.Flip(DirectionHorizontal); err != nil {
return err
}
}
if err := r.Grid(r.PageHeight(), r.Pages(), 1); err != nil {
if err := r.Grid(r.PageHeight(), pages, 1); err != nil {
return err
}
@@ -305,7 +357,7 @@ func (r *ImageRef) Rotate(angle Angle) error {
}
r.setImage(out)
if r.Pages() > 1 && (angle == Angle90 || angle == Angle270) {
if pages > 1 && (angle == Angle90 || angle == Angle270) {
if err := r.SetPageHeight(width); err != nil {
return err
}
+27 -10
View File
@@ -371,26 +371,43 @@ func vipsExtractArea(in *C.VipsImage, left, top, width, height int) (*C.VipsImag
func vipsExtractAreaMultiPage(in *C.VipsImage, left, top, width, height int) (*C.VipsImage, error) {
incOpCounter("extractAreaMultiPage")
return vipsMapPages(in, func(page *C.VipsImage) (*C.VipsImage, error) {
return vipsGenExtractArea(page, left, top, width, height)
})
}
// vipsMapPages applies op to each loaded page of a multi-page image and
// restacks the results. Operations that act on the whole strip (flip,
// rot180, resize) would otherwise reorder or merge the frames. The page
// height of the result is taken from the first mapped page.
func vipsMapPages(in *C.VipsImage, op func(page *C.VipsImage) (*C.VipsImage, error)) (*C.VipsImage, error) {
pageHeight := vipsGetPageHeight(in)
nPages := int(in.Ysize) / pageHeight
if nPages < 1 {
nPages, pageHeight = 1, int(in.Ysize)
}
pages := make([]*C.VipsImage, nPages)
pages := make([]*C.VipsImage, 0, nPages)
defer func() {
for _, p := range pages {
clearImage(p)
}
}()
for i := 0; i < nPages; i++ {
page, err := vipsGenExtractArea(in, left, pageHeight*i+top, width, height)
page, err := vipsGenExtractArea(in, 0, pageHeight*i, int(in.Xsize), pageHeight)
if err != nil {
for j := 0; j < i; j++ {
clearImage(pages[j])
}
return nil, err
}
pages[i] = page
mapped, err := op(page)
clearImage(page)
if err != nil {
return nil, err
}
pages = append(pages, mapped)
}
across := 1
joined, err := vipsGenArrayjoin(pages, &ArrayjoinOptions{Across: &across})
for _, p := range pages {
clearImage(p)
}
if err != nil {
return nil, err
}
@@ -401,7 +418,7 @@ func vipsExtractAreaMultiPage(in *C.VipsImage, left, top, width, height int) (*C
return nil, err
}
vipsSetPageHeight(out, height)
vipsSetPageHeight(out, int(pages[0].Ysize))
return out, nil
}
+7
View File
@@ -257,6 +257,13 @@ static int save_target(const char *operationName, SaveParams *params,
return 1;
}
// Same as save_buffer: "keep" overrides the deprecated "strip".
if (params->keepSet &&
vips_object_set(VIPS_OBJECT(operation), "keep", params->keep, NULL)) {
g_object_unref(operation);
return 1;
}
// Build uncached, mirroring load_from_source: the unique target
// object makes cache hits impossible.
if (vips_object_build(VIPS_OBJECT(operation))) {
+20 -10
View File
@@ -637,7 +637,8 @@ func (r *ImageRef) SaveToWriterJpeg(w io.Writer, params *JpegExportParams) error
}
p := *params
return r.saveToWriter(w, ImageTypeJPEG, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) {
return newSaveParamsJPEG(in, p), func() {}, nil
sp, err := newSaveParamsJPEG(in, p)
return sp, func() {}, err
})
}
@@ -651,7 +652,8 @@ func (r *ImageRef) SaveToWriterPng(w io.Writer, params *PngExportParams) error {
}
p := *params
return r.saveToWriter(w, ImageTypePNG, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) {
return newSaveParamsPNG(in, p), func() {}, nil
sp, err := newSaveParamsPNG(in, p)
return sp, func() {}, err
})
}
@@ -680,7 +682,8 @@ func (r *ImageRef) SaveToWriterTiff(w io.Writer, params *TiffExportParams) error
}
p := *params
return r.saveToWriter(w, ImageTypeTIFF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) {
return newSaveParamsTIFF(in, p), func() {}, nil
sp, err := newSaveParamsTIFF(in, p)
return sp, func() {}, err
})
}
@@ -693,7 +696,8 @@ func (r *ImageRef) SaveToWriterHeif(w io.Writer, params *HeifExportParams) error
}
p := *params
return r.saveToWriter(w, ImageTypeHEIF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) {
return newSaveParamsHEIF(in, p), func() {}, nil
sp, err := newSaveParamsHEIF(in, p)
return sp, func() {}, err
})
}
@@ -707,7 +711,8 @@ func (r *ImageRef) SaveToWriterGif(w io.Writer, params *GifExportParams) error {
}
p := *params
return r.saveToWriter(w, ImageTypeGIF, func(in *C.VipsImage) (C.struct_SaveParams, func(), error) {
return newSaveParamsGIF(in, p), func() {}, nil
sp, err := newSaveParamsGIF(in, p)
return sp, func() {}, err
})
}
@@ -806,17 +811,22 @@ func streamSaveParams(in *C.VipsImage, format ImageType, params *ExportParams) (
switch format {
case ImageTypeJPEG:
return newSaveParamsJPEG(in, *jpegParamsFromExport(params)), noop, nil
p, err := newSaveParamsJPEG(in, *jpegParamsFromExport(params))
return p, noop, err
case ImageTypePNG:
return newSaveParamsPNG(in, *pngParamsFromExport(params)), noop, nil
p, err := newSaveParamsPNG(in, *pngParamsFromExport(params))
return p, noop, err
case ImageTypeWEBP:
return newSaveParamsWebP(in, *webpParamsFromExport(params))
case ImageTypeHEIF:
return newSaveParamsHEIF(in, *heifParamsFromExport(params)), noop, nil
p, err := newSaveParamsHEIF(in, *heifParamsFromExport(params))
return p, noop, err
case ImageTypeTIFF:
return newSaveParamsTIFF(in, *tiffParamsFromExport(params)), noop, nil
p, err := newSaveParamsTIFF(in, *tiffParamsFromExport(params))
return p, noop, err
case ImageTypeGIF:
return newSaveParamsGIF(in, *gifParamsFromExport(params)), noop, nil
p, err := newSaveParamsGIF(in, *gifParamsFromExport(params))
return p, noop, err
default:
return C.struct_SaveParams{}, noop, fmt.Errorf("streaming save does not support format %q", ImageTypes[format])
}
+3
View File
@@ -13,6 +13,9 @@
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype">
<img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
</a>
<a href="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml">
<img alt="Tests" src="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml/badge.svg">
</a>
<a href="https://codecov.io/gh/gabriel-vasile/mimetype">
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
</a>
+142 -29
View File
@@ -46,12 +46,14 @@ type cdf struct {
satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input
satEntries int // number of valid SAT entries reachable through satSecs
firstSSAT int32
ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain
dirRaw []byte // directory stream bytes (entries are decoded on demand)
sst []byte // short-stream pool (root storage's stream)
sstBuilt bool // whether sst was already loaded (it is loaded lazily)
rootStreamFirst int32 // first sector of the root storage short-stream pool
rootStreamSize uint32 // size of the root storage short-stream pool
rootStorageUUID []byte
rootChild int32 // directory id of the root storage's child tree
rootStorageUUID [16]byte
}
// parse reads the entire on-disk structure required for type detection. It
@@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool {
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
c.buildSAT(masterSAT, firstMSAT, nMSAT)
c.buildSSAT()
c.dirRaw = c.readLong(firstDirSec, 0)
c.rootStreamFirst = -1
c.rootChild = -1
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ != dirTypeRootStorage || d.streamFirst < 0 {
if d.typ != dirTypeRootStorage {
continue
}
c.rootStorageUUID = d.storageUUID[:]
copy(c.rootStorageUUID[:], d.storageUUID[:])
c.rootChild = d.child
// Record where the short-stream pool lives; it is loaded lazily by
// shortStream the first time a short stream is actually read.
c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
if d.streamFirst >= 0 {
c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
}
break
}
return true
}
// rootChildIter iterates over the directory entries that are direct children
// of the root storage, walking the red-black sibling tree hanging off the root
// entry's child pointer. Restricting detection to root-level entries matters:
// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry
// their own SummaryInformation streams deeper in the hierarchy, and a flat
// directory scan can pick those up instead of the document's own.
// If the tree is unusable (no valid root child) iteration degrades to a flat
// scan of all entries so truncated or malformed files still get best-effort
// detection. The iterator lives entirely on the caller's stack: it allocates
// nothing and decodes each visited entry into its inline d field.
type rootChildIter struct {
c *cdf
d dirEntry // entry decoded by the latest successful next call
n int // total directory entries
i int // next index for the flat fallback scan
flat bool // no usable tree; scan all entries instead
visited int // entries visited so far; guards against cyclic trees
sp int // number of ids on stack
stack [64]int32
}
// rootChildren returns an iterator over the root storage's direct children.
// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... }
func (c *cdf) rootChildren() rootChildIter {
it := rootChildIter{c: c, n: c.dirLen()}
if c.rootChild >= 0 && int(c.rootChild) < it.n {
it.stack[0] = c.rootChild
it.sp = 1
} else {
it.flat = true
}
return it
}
// next advances to the next entry, decoding it into it.d. It reports false
// when iteration is done.
func (it *rootChildIter) next() bool {
if it.flat {
if it.i >= it.n {
return false
}
it.c.dirAt(it.i, &it.d)
it.i++
return true
}
for it.sp > 0 {
it.sp--
id := it.stack[it.sp]
if id < 0 || int(id) >= it.n {
continue
}
if it.visited++; it.visited > it.n {
return false // cyclic sibling pointers in a malformed directory
}
it.c.dirAt(int(id), &it.d)
// Push the siblings. A valid red-black tree of n entries is at most
// 2*log2(n) deep, so the fixed-size stack cannot overflow for any
// real directory; if a malformed tree overflows it, the excess
// branches are dropped and detection degrades gracefully.
for _, sib := range [2]int32{it.d.left, it.d.right} {
if sib >= 0 && it.sp < len(it.stack) {
it.stack[it.sp] = sib
it.sp++
}
}
return true
}
return false
}
func (c *cdf) detect() CDFType {
for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} {
if t, ok := c.detectFromSummary(name); ok {
return t
}
}
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if t, ok := lookupSection(d.nameBytes(), d.typ); ok {
for it := c.rootChildren(); it.next(); {
if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok {
return t
}
}
@@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType {
// derive a CDFType from the root-storage CLSID, the property NameOfApplication,
// and finally the names of sibling user streams.
func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) {
if bytes.Equal(c.rootStorageUUID[:], msiCLSID) {
return CDFTypeInstaller, true
}
raw, ok := c.userStream(streamName)
@@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
return t, true
}
}
for i, n := 0, c.dirLen(); i < n; i++ {
var d dirEntry
c.dirAt(i, &d)
if d.nameLen == 0 {
for it := c.rootChildren(); it.next(); {
if it.d.nameLen == 0 {
continue
}
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok {
if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok {
return t, true
}
}
@@ -164,6 +237,9 @@ type dirEntry struct {
name [32]byte
nameLen uint8
typ uint8
left int32 // left sibling directory id
right int32 // right sibling directory id
child int32 // first child directory id (for storages)
streamFirst int32
size uint32
storageUUID [16]byte
@@ -172,23 +248,56 @@ type dirEntry struct {
// nameBytes returns the decoded ASCII name without copying.
func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] }
func (c *cdf) ssatAt(i int32) int32 {
// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain
// through the SAT once. The SSAT contents are not materialized; ssatAt computes
// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt.
// The walk is bounded by the number of sectors in the file so a cyclic SAT
// (a self-looping sector) cannot spin forever.
func (c *cdf) buildSSAT() {
maxIDs := len(c.data)/c.secSize + 1
buf := make([]byte, 0, 4*8)
var tmp [4]byte
for sid := c.firstSSAT; sid >= 0; {
if int(sid) >= c.satLen() {
break // SAT is truncated; stop collecting
}
buf, ok := c.sector(sid)
if !ok {
if _, ok := c.sector(sid); !ok {
break
}
lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32
if i < lbuf {
return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id
binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id
buf = append(buf, tmp[:]...)
if len(buf)/4 > maxIDs {
break // cyclic SAT chain; stop allocating
}
i -= lbuf
sid = c.satAt(sid)
}
return -1
c.ssatSecs = int32s{b: buf}
}
// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly
// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns
// -1 when i is past the end of the SSAT or the backing sector is truncated.
func (c *cdf) ssatAt(i int32) int32 {
if i < 0 {
return -1
}
perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two
secIdx := int(i / perSec)
if secIdx >= c.ssatSecs.len() {
return -1
}
sid := c.ssatSecs.at(secIdx)
buf, ok := c.sector(sid)
if !ok {
return -1
}
entryIdx := i % perSec
//nolint:gosec // anything divided by 4 fits int32
if entryIdx >= int32(len(buf)/4) {
return -1 // sector truncated short of this entry
}
//nolint:gosec // intentional two's-complement reinterpretation of a sector id
return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:]))
}
// shortStream returns the root storage short-stream pool, loading it on first
@@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte {
}
off := int(off64)
out = append(out, sst[off:off+c.shortSecSize]...)
if length > 0 && int64(len(out)) >= int64(length) {
break // read enough to satisfy the stream's declared length
}
if len(out) >= len(sst) {
break // chain longer than the pool: cyclic SSAT, stop
}
@@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) {
}
out.nameLen = k
out.typ = raw[66]
out.left = readSecID(raw[68:72])
out.right = readSecID(raw[72:76])
out.child = readSecID(raw[76:80])
out.streamFirst = readSecID(raw[116:120])
out.size = binary.LittleEndian.Uint32(raw[120:])
copy(out.storageUUID[:], raw[80:96])
}
// userStream finds a user stream by name and returns its bytes.
// userStream finds a root-level user stream by name and returns its bytes.
func (c *cdf) userStream(name string) ([]byte, bool) {
var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d)
if d.typ == dirTypeUserStream && string(d.nameBytes()) == name {
buf := c.readChain(d.streamFirst, d.size)
for it := c.rootChildren(); it.next(); {
if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name {
buf := c.readChain(it.d.streamFirst, it.d.size)
if buf == nil {
return nil, false
}
+15 -12
View File
@@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool {
// AAC matches an Advanced Audio Coding file.
func AAC(raw []byte, _ uint32) bool {
return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9))
return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9)
}
// MP3 matches a .mp3 file.
@@ -128,27 +128,30 @@ func id3v2(raw []byte) bool {
}
size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9])
// Disallow too big frames, let's say 10MB.
return size > 0 && size < 10*1024*1024
// The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB
// cap rejected legitimate files with large ID3v2 album art. #839
return size > 0
}
// iff checks for an Interchange File Format layout: 4-byte container tag,
// 4-byte size, 4-byte format tag.
func iff(raw []byte, container, format []byte) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], container) &&
bytes.Equal(raw[8:12], format)
}
// Wav matches a Waveform Audio File Format file.
func Wav(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45})
return iff(raw, []byte("RIFF"), []byte("WAVE"))
}
// Aiff matches Audio Interchange File Format file.
func Aiff(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) &&
bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46})
return iff(raw, []byte("FORM"), []byte("AIFF"))
}
// Qcp matches a Qualcomm Pure Voice file.
func Qcp(raw []byte, limit uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte("QLCM"))
return iff(raw, []byte("RIFF"), []byte("QLCM"))
}
+9 -16
View File
@@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool {
return slices.Contains(dbfTypes, raw[0])
}
// ElfObj matches an object file.
func ElfObj(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x01))
func elfType(raw []byte, t byte) bool {
return len(raw) > 17 &&
((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t))
}
// ElfObj matches an object file.
func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 0x01) }
// ElfExe matches an executable file.
func ElfExe(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x02))
}
func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) }
// ElfLib matches a shared library file.
func ElfLib(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x03))
}
func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) }
// ElfDump matches a core dump file.
func ElfDump(raw []byte, limit uint32) bool {
return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x04))
}
func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) }
// Dcm matches a DICOM medical format file.
func Dcm(raw []byte, limit uint32) bool {
+1 -3
View File
@@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool {
// Webp matches a WebP file.
func Webp(raw []byte, _ uint32) bool {
return len(raw) > 12 &&
bytes.Equal(raw[0:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50})
return iff(raw, []byte("RIFF"), []byte("WEBP"))
}
// Dwg matches a CAD drawing file.
+1 -13
View File
@@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool {
return false
}
func markupCheck(sig, raw []byte) bool {
if len(raw) < len(sig)+1 {
if !ciCheck(sig, raw) {
return false
}
// perform case insensitive check
for i, b := range sig {
db := raw[i]
if 'A' <= b && b <= 'Z' {
db &= 0xDF
}
if b != db {
return false
}
}
// Next byte must be space or right angle bracket.
if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' {
return false
}
return true
}
+31 -59
View File
@@ -46,26 +46,16 @@ func Ole(raw []byte, limit uint32) bool {
return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1})
}
// Doc matches a Microsoft Word 97-2003 file.
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
func Doc(raw []byte, _ uint32) bool {
// cdfOrClsid checks if the raw input is detected as the given CDF type, and if
// the CDF parser returns a generic result, falls back to matching root storage CLSIDs.
func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeDoc {
if fromParsing == want {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit: match
// the root storage CLSID, which often lies within the first sectors.
clsids := [][]byte{
// Microsoft Word 97-2003 Document (Word.Document.8)
{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word Picture (Word.Picture.8)
{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
for _, clsid := range clsids {
if matchOleClsid(raw, clsid) {
return true
@@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool {
return false
}
// Doc matches a Microsoft Word 97-2003 file.
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
func Doc(raw []byte, _ uint32) bool {
return cdfOrClsid(raw, cdf.CDFTypeDoc,
// Microsoft Word 97-2003 Document (Word.Document.8)
[]byte{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
[]byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
// Microsoft Word Picture (Word.Picture.8)
[]byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
)
}
// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation.
func Ppt(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypePpt {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8,
}) || matchOleClsid(raw, []byte{
0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3,
}) {
if cdfOrClsid(raw, cdf.CDFTypePpt,
[]byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8},
[]byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3},
) {
return true
}
@@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool {
// Xls matches a Microsoft Excel 97-2003 file.
func Xls(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeXls {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory is past the read limit.
// Root CLSID test is the safest way to identify the OLE, however, the format
// often places the root CLSID at the end of the file.
if matchOleClsid(raw, []byte{
0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
}) || matchOleClsid(raw, []byte{
0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
}) {
if cdfOrClsid(raw, cdf.CDFTypeXls,
[]byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
[]byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
) {
return true
}
@@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool {
// Msg matches a Microsoft Outlook email file.
func Msg(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeMsg {
return true
}
if fromParsing != cdf.CDFTypeGeneric {
return false
}
// Fallback for inputs where the CDF directory does not carry the streams the
// parser keys on: match the root storage CLSID instead.
return matchOleClsid(raw, []byte{
0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
})
return cdfOrClsid(raw, cdf.CDFTypeMsg,
[]byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
)
}
// Msi matches a Microsoft Windows Installer file.
+70 -44
View File
@@ -345,6 +345,7 @@ with `net/http` can be used with chi's mux.
| [Compress] | Gzip compression for clients that accept compressed responses |
| [ContentCharset] | Ensure charset for Content-Type request headers |
| [CleanPath] | Clean double slashes from request path |
| [Deprecation] | Set the Deprecation response header (RFC 9745); see also [Sunset] |
| [GetHead] | Automatically route undefined HEAD requests to GET handlers |
| [Heartbeat] | Monitoring endpoint to check the servers pulse |
| [Logger] | Logs the start and end of each request with the elapsed processing time |
@@ -361,57 +362,58 @@ with `net/http` can be used with chi's mux.
| [RouteHeaders] | Route handling for request headers |
| [SetHeader] | Short-hand middleware to set a response header key/value |
| [StripSlashes] | Strip slashes on routing paths |
| [Sunset] | Sunset set Deprecation/Sunset header to response |
| [Sunset] | Set the Sunset response header (RFC 8594); see also [Deprecation] |
| [Throttle] | Puts a ceiling on the number of concurrent requests |
| [Timeout] | Signals to the request context when the timeout deadline is reached |
| [URLFormat] | Parse extension from url and put it on request context |
| [WithValue] | Short-hand middleware to set a key/value on the request context |
----------------------------------------------------------------------------------------------------
[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentEncoding
[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentType
[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/middleware#BasicAuth
[Compress]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compress
[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ContentCharset
[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/middleware#CleanPath
[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetHead
[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetReqID
[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Heartbeat
[Logger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Logger
[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/middleware#NoCache
[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Profiler
[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromHeader
[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFF
[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFFTrustedProxies
[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromRemoteAddr
[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIP
[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIPAddr
[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RealIP
[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Recoverer
[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RedirectSlashes
[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestLogger
[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestID
[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RouteHeaders
[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#SetHeader
[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#StripSlashes
[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentEncoding
[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentType
[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#BasicAuth
[Compress]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compress
[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ContentCharset
[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#CleanPath
[Deprecation]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Deprecation
[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetHead
[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetReqID
[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Heartbeat
[Logger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Logger
[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#NoCache
[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Profiler
[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromHeader
[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFF
[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFFTrustedProxies
[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromRemoteAddr
[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIP
[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIPAddr
[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RealIP
[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Recoverer
[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RedirectSlashes
[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestLogger
[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestID
[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RouteHeaders
[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#SetHeader
[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#StripSlashes
[Sunset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Sunset
[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Throttle
[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleBacklog
[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleWithOpts
[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Timeout
[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#URLFormat
[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithLogEntry
[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithValue
[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compressor
[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#DefaultLogFormatter
[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/middleware#EncoderFunc
[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRoute
[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRouter
[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogEntry
[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogFormatter
[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LoggerInterface
[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleOpts
[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WrapResponseWriter
[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Throttle
[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleBacklog
[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleWithOpts
[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Timeout
[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#URLFormat
[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithLogEntry
[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithValue
[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compressor
[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#DefaultLogFormatter
[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#EncoderFunc
[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRoute
[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRouter
[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogEntry
[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogFormatter
[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LoggerInterface
[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleOpts
[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WrapResponseWriter
### Choosing a ClientIP middleware
@@ -474,6 +476,30 @@ See the per-function godoc for the full semantics of each middleware, and
[adam-p's "The perils of the 'real' client IP"](https://adam-p.ca/blog/2022/03/x-forwarded-for/)
for the underlying threat model.
### Deprecating and removing a route
Use `Deprecation` first. Add `Sunset` when you know the removal date.
| Situation | Use |
| :------------------------------------------------------- | :-------------------------- |
| Route works, clients should migrate, no removal date yet | `Deprecation` |
| You know the date the route will stop working | `Deprecation` + `Sunset` |
| Route is already removed | Neither. Return `410 Gone`. |
```go
// A bad date parses to the zero time, and the middleware panics at startup.
deprecatedAt, _ := time.Parse(time.DateOnly, "2026-01-15")
sunsetAt, _ := time.Parse(time.DateOnly, "2026-07-01")
// Step 1: the route is deprecated.
r.With(middleware.Deprecation(deprecatedAt)).Get("/v1/users", listUsers)
// Step 2: the removal date is known.
r.With(middleware.Deprecation(deprecatedAt), middleware.Sunset(sunsetAt)).Get("/v1/users", listUsers)
// After sunsetAt: remove the route, or return 410 Gone.
```
### Extra middlewares & packages
Please see https://github.com/go-chi for additional packages.
+9 -7
View File
@@ -2,7 +2,7 @@
//
// chi supports the four most recent major versions of Go.
//
// Example:
// # Example
//
// package main
//
@@ -25,11 +25,13 @@
// http.ListenAndServe(":3333", r)
// }
//
// See github.com/go-chi/chi/_examples/ for more in-depth examples.
// See [github.com/go-chi/chi/v5/_examples] for more in-depth examples.
//
// # URL patterns
//
// URL patterns allow for easy matching of path components in HTTP
// requests. The matching components can then be accessed using
// chi.URLParam(). All patterns must begin with a slash.
// [chi.URLParam](). All patterns must begin with a slash.
//
// A simple named placeholder {name} matches any sequence of characters
// up to the next / or the end of the URL. Trailing slashes on paths must
@@ -37,11 +39,11 @@
//
// A placeholder with a name followed by a colon allows a regular
// expression match, for example {number:\\d+}. The regular expression
// syntax is Go's normal regexp RE2 syntax, except that / will never be
// matched. An anonymous regexp pattern is allowed, using an empty string
// before the colon in the placeholder, such as {:\\d+}
// syntax is Go's normal [regexp] RE2 syntax (see [regexp/syntax]), except
// that / will never be matched. An anonymous regexp pattern is allowed, using
// an empty string before the colon in the placeholder, such as {:\\d+}.
//
// The special placeholder of asterisk matches the rest of the requested
// The special placeholder of asterisk (*) matches the rest of the requested
// URL. Any trailing characters in the pattern are ignored. This is the only
// placeholder which will match / characters.
//
+31 -7
View File
@@ -3,15 +3,13 @@ package chi
import (
"context"
"net/http"
"slices"
"strings"
)
// URLParam returns the url parameter from a http.Request object.
func URLParam(r *http.Request, key string) string {
if rctx := RouteContext(r.Context()); rctx != nil {
return rctx.URLParam(key)
}
return ""
return URLParamFromCtx(r.Context(), key)
}
// URLParamFromCtx returns the url parameter from a http.Request Context.
@@ -42,6 +40,8 @@ var (
// Context is the default routing context set on the root node of a
// request context to track route patterns, URL parameters and
// an optional routing path.
//
// NOTE: New reference fields (slices, maps, pointers) must be deep-copied in Clone.
type Context struct {
Routes Routes
@@ -95,12 +95,36 @@ func (x *Context) Reset() {
x.parentCtx = nil
}
// Clone a routing context so that it may be used outside of the request/response
// lifecycle, e.g. in a goroutine that outlives the request handler.
//
// Clone must be called before the request handler returns; after that, the
// original context is reset and put back into the pool for reuse by another
// request, racing with the copy.
func (x *Context) Clone() *Context {
clone := *x
// Detach from the request's context, which is canceled once the request finishes.
clone.parentCtx = nil
clone.URLParams.Keys = slices.Clone(x.URLParams.Keys)
clone.URLParams.Values = slices.Clone(x.URLParams.Values)
clone.routeParams.Keys = slices.Clone(x.routeParams.Keys)
clone.routeParams.Values = slices.Clone(x.routeParams.Values)
clone.RoutePatterns = slices.Clone(x.RoutePatterns)
clone.methodsAllowed = slices.Clone(x.methodsAllowed)
return &clone
}
// URLParam returns the corresponding URL parameter value from the request
// routing context.
func (x *Context) URLParam(key string) string {
for k := len(x.URLParams.Keys) - 1; k >= 0; k-- {
if x.URLParams.Keys[k] == key {
return x.URLParams.Values[k]
for i, k := range slices.Backward(x.URLParams.Keys) {
if k == key {
return x.URLParams.Values[i]
}
}
return ""
+100 -33
View File
@@ -5,6 +5,7 @@ import (
"net"
"net/http"
"net/netip"
"slices"
"strings"
)
@@ -38,15 +39,37 @@ const xForwardedForHeader = "X-Forwarded-For"
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before storage.
func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
//
// Overwriting only protects requests that pass through your proxy. A client
// that reaches this server directly can set the header to anything. Pass
// your proxy's CIDR prefixes as trustedIPPrefixes to close that gap: the
// header is then read only when r.RemoteAddr falls within one of them;
// otherwise r.RemoteAddr itself is the client IP. This mirrors nginx
// (set_real_ip_from), Apache (RemoteIPTrustedProxy), and Caddy
// (trusted_proxies), and Cloudflare's advice to accept origin traffic only
// from its IP ranges. Without trustedIPPrefixes, guarantee at the network
// layer (security group / firewall) that only your proxy can reach this
// server.
//
// r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP",
// "173.245.48.0/20", // Cloudflare IPv4, see https://www.cloudflare.com/ips/
// "2400:cb00::/32", // Cloudflare IPv6
// ))
//
// Panics at startup if any prefix is invalid.
func ClientIPFromHeader(trustedHeader string, trustedIPPrefixes ...string) func(http.Handler) http.Handler {
header := http.CanonicalHeaderKey(trustedHeader)
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
values := r.Header.Values(header)
if len(values) > 0 {
if ip, ok := parseHeaderAddr(values[len(values)-1]); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
var found netip.Addr
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else if values := r.Header.Values(header); len(values) > 0 {
found, _ = parseHeaderAddr(values[len(values)-1])
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
h.ServeHTTP(w, r)
})
@@ -77,9 +100,15 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// "2600:9000::/28", // CloudFront IPv6
// ))
//
// Calling with no arguments returns the rightmost XFF entry, or no IP if
// that entry doesn't parse (fail-closed) — safe only if you have exactly
// one trusted hop directly in front of this server (e.g., nginx on localhost).
// The TCP peer in r.RemoteAddr is treated as the rightmost hop: if it is
// not within a trusted prefix, it is the client IP and X-Forwarded-For is
// ignored. A client reaching this server directly therefore cannot spoof
// its IP. If r.RemoteAddr doesn't parse, no client IP is set (fail-closed).
//
// At least one prefix is required. For a single trusted hop directly in
// front of this server (e.g., nginx on localhost), pass its address:
//
// r.Use(middleware.ClientIPFromXFF("127.0.0.1/32", "::1/128"))
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before the prefix check and storage; otherwise an attacker
@@ -88,26 +117,30 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// If you know the number of trusted proxies but not their IPs, use
// [ClientIPFromXFFTrustedProxies] instead.
//
// Panics at startup if any prefix is invalid.
// Panics at startup if no prefix is given or any prefix is invalid.
func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handler {
prefixes := make([]netip.Prefix, len(trustedIPPrefixes))
for i, p := range trustedIPPrefixes {
prefixes[i] = netip.MustParsePrefix(p)
if len(trustedIPPrefixes) == 0 {
panic("middleware.ClientIPFromXFF: at least one trusted IP prefix is required; use ClientIPFromXFFTrustedProxies(1) to trust any peer")
}
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var found netip.Addr
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else {
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
@@ -186,12 +219,8 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt
// IPv6 zones are preserved (link-local connections may legitimately have one).
func ClientIPFromRemoteAddr(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
if ip, err := netip.ParseAddr(host); err == nil {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip.Unmap()))
if ip, ok := parseRemoteAddr(r.RemoteAddr); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
h.ServeHTTP(w, r)
})
@@ -226,8 +255,7 @@ func GetClientIPAddr(ctx context.Context) netip.Addr {
// comma-separated entries in order received — so an attacker cannot pick
// which value security logic sees by sending a duplicate header.
func walkXFF(headers []string, visit func(entry string) bool) {
for hi := len(headers) - 1; hi >= 0; hi-- {
h := headers[hi]
for _, h := range slices.Backward(headers) {
for h != "" {
var v string
if i := strings.LastIndexByte(h, ','); i >= 0 {
@@ -246,6 +274,45 @@ func walkXFF(headers []string, visit func(entry string) bool) {
}
}
// mustParsePrefixes parses CIDR prefixes, panicking on the first invalid one.
func mustParsePrefixes(cidrs []string) []netip.Prefix {
prefixes := make([]netip.Prefix, len(cidrs))
for i, p := range cidrs {
prefixes[i] = netip.MustParsePrefix(p)
}
return prefixes
}
// untrustedPeer reports whether the TCP peer in r.RemoteAddr is outside
// prefixes. If so, peer is the client IP, or invalid if RemoteAddr doesn't
// parse. With no prefixes, every peer is trusted.
func untrustedPeer(r *http.Request, prefixes []netip.Prefix) (peer netip.Addr, untrusted bool) {
if len(prefixes) == 0 {
return netip.Addr{}, false
}
peer, ok := parseRemoteAddr(r.RemoteAddr)
if !ok {
return netip.Addr{}, true
}
// Zoned addresses never match a prefix, so check a link-local peer without its zone.
return peer, !inAnyPrefix(peer.WithZone(""), prefixes)
}
// parseRemoteAddr parses the host of r.RemoteAddr. v4-mapped IPv6 folds to
// plain v4; the IPv6 zone is preserved (link-local connections may
// legitimately have one).
func parseRemoteAddr(remoteAddr string) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
ip, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
return ip.Unmap(), true
}
// inAnyPrefix reports whether ip falls within any of the given prefixes.
func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
@@ -263,7 +330,7 @@ func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
// address, so without folding/stripping an attacker could escape an
// otherwise valid trust list.
//
// Header-sourced IPs only. [ClientIPFromRemoteAddr] normalizes inline
// Header-sourced IPs only. r.RemoteAddr goes through parseRemoteAddr
// (Unmap, but zone preserved for legitimate link-local connections).
func parseHeaderAddr(s string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(s)
Loaded 100 of 489 files, more files were not shown because too many files have changed in this diff. Show more