Compare commits

...
Author SHA1 Message Date
ishabaral 1e22ec2c80 build(deps): bump pnpm dependencies 2026-07-27 11:46:03 +05:45
Matteo b395d08db6 fix(web): remove unneeded keyboard focus stops (#12645)
Icons and date columns in tables received keyboard focus without
triggering any action, and the contextual helper icon duplicated its
button's label.
2026-07-24 22:57:51 +02:00
Matteo 1d16dd9e1e fix(web): focus New/Upload dropdown menus on open (#12646)
The New and Upload button dropdowns did not receive focus when opened,
so arrow key navigation between menu items didn't work, unlike the
context menu.
2026-07-24 22:50:02 +02:00
Michal Klos 86fa96362a feat: [OCISDEV-855] receivedsharecache: retry on transient storage errors in CAS loop (#12621) 2026-07-24 19:43:46 +02:00
Matteo f005d68eae fix(web): stop breadcrumb items from being announced twice (#12643)
Each breadcrumb list item had tabindex="0", putting it in the
keyboard/screen reader focus order alongside the link or button
nested inside it, causing every segment to be announced twice.
2026-07-24 12:23:56 +02:00
Matteo d68b53c6d8 chore: improve theme color contrast (#12642) 2026-07-24 11:29:55 +02:00
Matteo f8b861c723 enhancement(web): show select-all checkbox label in tile view (#12640)
feat(web): show select-all checkbox label in tile view

Make the select-all checkbox label visible in the tile view to match
the list view and make the checkbox's purpose clear.
2026-07-24 11:29:49 +02:00
Matteo 8b675b2e51 fix(web): improve contrast of form controls in dark and vault themes (#12639)
Fixes low-contrast sliders, switches, select highlights, and the global
search input/placeholder, including an !important override that blocked
theme-specific search colors and an invalid CSS var() fallback.
2026-07-24 11:29:37 +02:00
kobergjandClaude Opus 4.8 9f72d77bfc fix(graph): [OCISDEV-751] return correct issuerAssignedId on /me (#12431)
The /graph/v1.0/me endpoint reported the internal user UUID as
identities[].issuerAssignedId instead of the OIDC sub. The fast path
built the user model from the CS3 context user, which does not carry the
external identity. /me now always resolves the user through the identity
backend; group memberships are still only expanded on $expand=memberOf.

Forward-port of #12411 to master.

Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 16:37:09 +02:00
Matteo 30009ff770 enhancement(web): add missing main/footer regions and fix skip-to-main link (#12637)
feat: add missing main/footer regions and fix skip-to-main link

Add missing main and footer elements to the 404, private/public link
resolving, missing-config, logout, and access-denied pages, and fix the
skip-to-main link which silently did nothing on plain-layout pages due
to a missing target id and a stale cached DOM reference.
2026-07-23 14:08:21 +00:00
Matteo 50141f471b fix(web): preserve focus in file versions sidebar (#12630)
- Keep keyboard and screen-reader focus inside the versions sidebar while panels transition or reload.
- Restore focus to the opening control when the sidebar closes and to the matching Restore action after a version is restored.
- Improve version date and action announcements without introducing duplicate announcements or additional tab stops.

Signed-off-by: Matteo <matteo.sonnenholzner@kiteworks.com>
2026-07-23 13:44:02 +02:00
dependabot[bot] d65f3fc215 build(deps): bump the minor-and-patch group across 1 directory with 12 updates (#12607)
Bumps the minor-and-patch group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [github.com/beevik/etree](https://github.com/beevik/etree) | `1.6.0` | `1.7.0` |
| [github.com/coreos/go-oidc/v3](https://github.com/coreos/go-oidc) | `3.19.0` | `3.20.0` |
| [github.com/go-chi/chi/v5](https://github.com/go-chi/chi) | `5.3.0` | `5.3.1` |
| [github.com/go-ldap/ldap/v3](https://github.com/go-ldap/ldap) | `3.4.13` | `3.4.14` |
| [github.com/kovidgoyal/imaging](https://github.com/kovidgoyal/imaging) | `1.8.22` | `1.8.23` |
| [google.golang.org/grpc](https://github.com/grpc/grpc-go) | `1.82.0` | `1.82.1` |



Updates `github.com/beevik/etree` from 1.6.0 to 1.7.0
- [Release notes](https://github.com/beevik/etree/releases)
- [Changelog](https://github.com/beevik/etree/blob/main/RELEASE_NOTES.md)
- [Commits](https://github.com/beevik/etree/compare/v1.6.0...v1.7.0)

Updates `github.com/coreos/go-oidc/v3` from 3.19.0 to 3.20.0
- [Release notes](https://github.com/coreos/go-oidc/releases)
- [Commits](https://github.com/coreos/go-oidc/compare/v3.19.0...v3.20.0)

Updates `github.com/go-chi/chi/v5` from 5.3.0 to 5.3.1
- [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.0...v5.3.1)

Updates `github.com/go-ldap/ldap/v3` from 3.4.13 to 3.4.14
- [Release notes](https://github.com/go-ldap/ldap/releases)
- [Commits](https://github.com/go-ldap/ldap/compare/v3.4.13...v3.4.14)

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

Updates `golang.org/x/crypto` from 0.53.0 to 0.54.0
- [Commits](https://github.com/golang/crypto/compare/v0.53.0...v0.54.0)

Updates `golang.org/x/image` from 0.43.0 to 0.44.0
- [Commits](https://github.com/golang/image/compare/v0.43.0...v0.44.0)

Updates `golang.org/x/net` from 0.56.0 to 0.57.0
- [Commits](https://github.com/golang/net/compare/v0.56.0...v0.57.0)

Updates `golang.org/x/sync` from 0.21.0 to 0.22.0
- [Commits](https://github.com/golang/sync/compare/v0.21.0...v0.22.0)

Updates `golang.org/x/term` from 0.44.0 to 0.45.0
- [Commits](https://github.com/golang/term/compare/v0.44.0...v0.45.0)

Updates `golang.org/x/text` from 0.38.0 to 0.40.0
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.38.0...v0.40.0)

Updates `google.golang.org/grpc` from 1.82.0 to 1.82.1
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.82.0...v1.82.1)

---
updated-dependencies:
- dependency-name: github.com/beevik/etree
  dependency-version: 1.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/coreos/go-oidc/v3
  dependency-version: 3.20.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/go-chi/chi/v5
  dependency-version: 5.3.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/go-ldap/ldap/v3
  dependency-version: 3.4.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/kovidgoyal/imaging
  dependency-version: 1.8.23
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/crypto
  dependency-version: 0.54.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/image
  dependency-version: 0.44.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/net
  dependency-version: 0.57.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/sync
  dependency-version: 0.22.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/term
  dependency-version: 0.45.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/text
  dependency-version: 0.40.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: google.golang.org/grpc
  dependency-version: 1.82.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-22 08:19:45 +00:00
dependabot[bot] 1256793012 build(deps): bump qs from 6.14.2 to 6.15.2 in /web (#12623)
Bumps [qs](https://github.com/ljharb/qs) from 6.14.2 to 6.15.2.
- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ljharb/qs/compare/v6.14.2...v6.15.2)

---
updated-dependencies:
- dependency-name: qs
  dependency-version: 6.15.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-22 09:49:50 +02:00
Lukas Hirt cdcabdb527 chore(web): upgrade vue3-gettext from 2.4.0 to 4.0.1 (#12622)
Migrates all v-translate directive usages to $gettext() calls since
v4 removes the deprecated <translate> component/directive entirely
and silently drops such strings during extraction. Also drops the
now-unsupported disableHtmlEscaping positional argument from ~40
call sites (v4 no longer HTML-escapes interpolated values; none of
the affected strings are rendered via v-html) and removes the pnpm
patch that only backported a types export field v4 now ships
natively.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-07-21 15:40:24 +00:00
2f70a6856f build(deps): Bump dependencies (#12620)
* build(deps): bump pnpm dependencies

* style(web): format code with prettier

Signed-off-by: Lukas Hirt <info@hirt.cz>

* test(web): update ActivitiesPanel snapshot for dompurify/happy-dom sanitization change

The dependency bump upgraded dompurify to 3.4.3+, which combined with
happy-dom's DOM implementation drops a leading <strong> tag that is the
first sanitized child node. Real browsers are unaffected; only the
happy-dom test snapshot needed updating.

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

---------

Signed-off-by: Lukas Hirt <info@hirt.cz>
Co-authored-by: Lukas Hirt <info@hirt.cz>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-21 16:20:30 +02:00
Matteo eb06e23a09 fix: restore hover feedback lost to background-highlight/default collision (#12613)
The Light/Dark High-Contrast themes set colorPalette.background-highlight
equal to background-default, making hover backgrounds indistinguishable
from the resting page background wherever background-highlight was used
for interactive feedback (e.g. the global search results dropdown). The
non-high-contrast Dark theme had the same collision.

Set background-highlight to the same value as background-hover in those
theme blocks, and point SearchBar's result-preview hover/active state and
CreateShortcutModal's context-menu hover/active state at
--oc-color-background-hover directly, since background-highlight is
otherwise used for static surfaces (cards, modals, form fields) rather
than interaction feedback.
2026-07-20 15:18:17 +02:00
owncloud-settings-bot[bot] 604cb5a069 chore: add CODEOWNERS (managed by owncloud/admin) (#12604)
Co-authored-by: owncloud-settings-bot[bot] <291027677+owncloud-settings-bot[bot]@users.noreply.github.com>
2026-07-20 10:26:43 +02:00
owncloud-translations-bot[bot]andMartin 6361b52b7f chore: update translations from transifex (#12606)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
Co-authored-by: Martin <github@diemattels.at>
2026-07-20 08:03:38 +00:00
Matteo 5e7ce5c7de fix: resolve e2e violations in web UI (#12597)
- OcBreadcrumb: add `inert` to truncation placeholder <li> so its
  focusable <a> child is unreachable (fixes aria-hidden-focus)
- OcTable: remove aria-hidden from header cell span and fall back to
  field.name so icon/avatar columns always have discernible text
  (fixes empty-table-header)
- Plain layout: wrap router-view in <main> so login/public-link pages
  have a landmark (fixes region violations)
- SidebarNav: change root element to <aside> with aria-label so the
  versions div is inside a landmark (fixes region violations)
- web-app-ocm App: change root element to <main> (fixes region)
- Add v-if="pageTitle" to sr-only <h1> in 6 components so empty
  headings are never rendered (fixes empty-heading)
- Disable aria-allowed-role in search dropdown check — axe 4.11
  incorrectly rejects <li role="group"> inside <ul role="listbox">
  which is valid per ARIA 1.2
- Disable label rule in Application.open() check for pages that may
  transiently render Keycloak's OTP setup form
- Remove stale post-navigation check in createFileFromTemplate
  sidebar branch (sidebar is unmounted before check runs)
2026-07-20 06:36:49 +02:00
owncloud-translations-bot[bot] 63b0cdda0e chore: update translations from transifex (#12601)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-07-17 13:03:10 +02:00
owncloud-translations-bot[bot]andMartin 31ccffa99c chore: update translations from transifex (#12575)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
Co-authored-by: Martin <github@diemattels.at>
2026-07-16 09:07:38 +00:00
Lukas Hirt 5f1dbeca53 fix: [OCISDEV-1001] restrict group member data to authorized users (#12573)
The groups API could return group membership details to callers who
should not have had access to it via the single-group GET endpoint.
Access to group member data is now properly restricted based on the
caller's permissions.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-07-16 10:24:17 +02:00
Prajwol Amatya 5eb6366a6c [test-only] test: add test to check vault mode capabilities endpoint response (#12571)
* test: add test to check vault mode capabilities endpoint response

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add cleanup for Keycloak related configs after each test

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: use ocs version 2

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

---------

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-07-15 14:12:08 +05:45
Prajwol Amatya 53fa0f0691 [tests-only][full-ci] test: set custom auth level names (#12548)
test: add test to set custom auth level names

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-07-15 11:27:47 +05:45
Lukas Hirt c3a6f52502 fix: [OCISDEV-785] harden embed mode delegated authentication origin validation (#12572)
Hardened origin validation for the delegated authentication feature in
Web's embed mode.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-07-14 18:53:06 +02:00
Firas Frikha 2ed2f8697b FIX[OCISDEV-809]: encrypt viewOnlyToken (#12558)
fix(OCIDDEV-809): encrypt viewOnlyToken in the WOPI token
2026-07-14 11:33:46 +02:00
owncloud-translations-bot[bot]andMartin 7c87568713 chore: update translations from transifex (#12568)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
Co-authored-by: Martin <github@diemattels.at>
2026-07-14 10:39:24 +02:00
Prajwol Amatya b265241288 [tests-only][full-ci] test: add tests related to vault storage (#12482)
* test: test setup for vault storage

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add test to create file and folder in vault storage

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add test to check acr value from jwt token

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: setup vault storage in ci

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: update extraServerEnvironment

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: setup playwright

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: set keycloak true

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add env KC_URL

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add ignore https errors

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: check url

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: setup vault storage

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add test to check drive and vault resource isolation

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: add test to check drive and vault resource isolation

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

* test: store selectors in variable

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>

---------

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-07-14 10:53:02 +05:45
Michal Klos 7b284878f5 fix: flaky coreApiShare (#12565) 2026-07-13 18:26:48 +02:00
Michal KlosandRoman Perekhod c20900419e fix: CI, release pipeline fixes from 8.2-rc.1 (#12562)
* fix: fix CI (#12551)

* fix(ci): disable docker release jobs like in 8.1

The docker-build/manifest/readme jobs were enabled in 8.2 and wired into
create-github-release/audit-release. They fail at docker/login-action
("Username and password required") because DockerHub credentials are not
available, which cascades and cancels the whole release.

Restore the 8.1 behavior: re-add `if: false` to the docker jobs and unwire
them from the downstream release jobs.

* fix(ci): reinstall web deps in license-check job

Excluding web from the generated-code artifact (#12557, to avoid OOM on
upload) also dropped web/node_modules, which provides the
license-checker-rseidelsohn binary used by `make ci-node-check-licenses`.
The job failed with "license-checker-rseidelsohn: not found".

Run `pnpm install` in web before the license check so its node_modules is
present again.

---------

Co-authored-by: Roman Perekhod <2403905@gmail.com>
2026-07-13 17:58:04 +02:00
Martin bfda167e31 docs: remove orphaned ocisstoreservice value (#12564) 2026-07-13 15:33:50 +00:00
owncloud-translations-bot[bot] 77560da057 chore: update translations from transifex (#12555)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-07-13 14:01:55 +02:00
Lukas Hirt ad9ccdc93b ci: exclude web when uploading generated code (#12556)
The release workflow is running out of memory when uploading the generated code.
This fixes it by excluding the web directory. The web directory is not needed because the build is handled via the generation.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-07-13 10:12:57 +00:00
Matteo 5bf887a570 Chore/fix e2e violation (#12526)
* fix(e2e): resolve admin-settings general spec violations

- prevent focusable elements inside hidden breadcrumb items
- make OcDrop tippy role configurable, default to none
- wait for logo-wrapper element after page reload in e2e

* fix(e2e): resolve admin-settings groups spec violations

- add aria-label to the icon-only groups filter-confirm button, which
  had no name for screen readers to announce
- set reducedMotion on e2e browser contexts so notification fade-in
  animations don't race axe scans and produce false color-contrast
  failures
- fix tippbBox selector typo (-> tippyBox) that made the scan on the
  group context menu throw instead of running
- fix groupList and editPanel selectors in the shared selector map:
  groupList pointed at a nonexistent class, and editPanel used the
  non-standard :visible pseudo-selector which is invalid in native
  querySelectorAll

* fix(e2e): skip tooltip fade transition under reduced motion

Plain tooltips (v-oc-tooltip) use tippy.js's default fade animation
and default #333/#fff colors, driven by tippy's own duration option
rather than a CSS transition. Setting reducedMotion on the Playwright
browser context does not stop this, since tippy's animation ignores
prefers-reduced-motion on its own. Axe scans could catch the tooltip
mid-fade, when the text is still low-opacity, and report a false
color-contrast violation. Now the duration is forced to 0 when the
media query matches, mirroring how oc-fade-in already handles this
for CSS-driven animations.

* fix(e2e): resolve officeSuites spec progressbar violation and test bugs

- add aria-label to the global loading progress bar, which had no name
- point the space quota progress bar at its existing text label via
  aria-labelledby instead of leaving it unnamed
- fix a string-literal-instead-of-variable typo, an XPath selector that
  axe can't use (only CSS), and a scan that ran after clicking closed
  the element it was targeting, all in the public link test helpers
- move the create-document-modal scan to after the modal actually
  opens, since it was scanning too early and finding nothing

* fix(e2e): resolve app-store details spec contrast violation and scan bug

- override md-editor-v3's default link and inline-code colors in the
  read-only markdown preview, which didn't meet WCAG AA contrast
  against the app card background
- point the download-app a11y scan at the app list page instead of a
  details-page selector that isn't present on that page, a leftover
  from copying the sibling download-version helper

* fix(e2e): resolve participantManagement pagination spec violations

- patch vue-select to render aria-controls on its combobox toggle,
  which it already computed internally but never attached to the
  element with role="combobox"
- add aria-label to the account menu quota bar and upload progress
  bar, both missing a name on their progressbar role, same gap fixed
  earlier in LoadingIndicator/SpaceQuota
- add aria-label to the file-details preview-loading spinner, which
  rendered role="img" with an empty aria-label
- stop scanning the sidebar actions panel in deleteResource after it
  was already closed, which made the scan throw instead of running

* fix(e2e): add missing aria-label to hide-share quick action button

The icon-only hide/unhide-share button in the shared-with-me table had
a tooltip but no aria-label, so it had no accessible name. Reused the
label already computed for the tooltip instead of duplicating it.

* fix(e2e): fix sidebarPanel selector typo in downloadResources

Used the string 'sidebarPanel', which isn't a key in the shared a11y
selector map, so it fell through to being used as a literal (and
broken) CSS selector. Switched to the existing appSidebar key, which
resolves to the same #app-sidebar selector already used for this
concept elsewhere.

* fix(e2e): add accessible name to markdown editor's content area

md-editor-v3's underlying CodeMirror instance renders its editable
content div with role="textbox" but no accessible name, and the
library exposes no prop to pass one through. Set aria-label on it
directly after mount, since that's the only available hook.

* fix(e2e): fix users-filter button label and navigate scan selector

- add aria-label to the icon-only users search/filter-confirm button,
  the same button-name gap already fixed for the groups page
- fix Users.navigate scanning appSidebar, which isn't rendered until a
  sidebar panel is actually opened; switched to scanning body, matching
  the working pattern already used by Groups.navigate

* fix(e2e): fix global search dropdown ARIA structure and scan bugs

- restructure the search results listbox so its direct children are
  valid group/option roles instead of plain nested <li>/<ul>, fixing
  aria-required-children/parent, list, and listitem violations
- give the loading/no-results states no listbox role at all, since
  they're informational text rather than actual options
- give the listbox an accessible name via the existing search label
- fix the icon-only "search options" listbox missing aria-controls
  becoming null instead of a static string when the dropdown isn't
  rendered
- add a disableRules option to assertNoSevereA11yViolations, using it
  for two narrow, investigated cases: search-result rows render a real
  <a href> so native middle-click/ctrl-click "open in new tab" keeps
  working (nested-interactive can't be satisfied without removing
  that), and a checkbox nested in a clickable filter-list button that
  would otherwise lose its only accessible selection-state indicator
- fix the same aria-controls transient-timing gap in two more call
  sites that hit it after a route change (closing the editor, opening
  any app via the app switcher)

* fix(e2e): fix low contrast search input in select combobox

vue-select's vendor CSS dims the search input to 20% opacity while
searching but not yet open, dropping text contrast to 1.51:1 against
the required 4.5:1. Override the opacity back to 1 for that state.

* fix(e2e): add labels to app gallery navigation buttons

The prev/next/set-image buttons in the app details image gallery only
render a decorative icon with no text or label, leaving them with no
discernible name for screen reader users.

* fix(e2e): add label to clear-clipboard button in files app bar

The clear-clipboard button next to "Paste here" only renders a
decorative close icon with no text or label, leaving it with no
discernible name for screen reader users.

* fix(e2e): add label to generic app-loading spinner

The spinner shown while an external app is loading has no aria-label,
leaving the role="img" element with no accessible name even though a
visually-hidden "Loading app" text already exists right next to it.

* fix(e2e): add label to GDPR export loading spinner

The spinner shown while the GDPR export status is loading has no
aria-label, leaving the role="img" element with no accessible name.

* fix(e2e): fix combobox aria attributes in create shortcut modal

The suggestion dropdown had no explicit toggle target, so tippy fell
back to the input wrapper div and set aria-expanded on an element with
no ARIA role. Point the drop at the actual input and give it proper
combobox semantics.

* fix(e2e): fix users filter checkbox-button scan and delete selector bug

Suppress the already-accepted checkbox-in-button nested-interactive
rule at the two roles filter scan sites in filterUsers, matching the
pattern used elsewhere for the same ItemFilter.vue markup. Also fix a
string-literal selector in deleteUserUsingContextMenu that was never
actually calling util.format, so axe scanned for a nonexistent element.

* fix(e2e): resolve admin-settings spaces spec violations

- replace removed #files-toggle-sidebar with the "Show details" button
  (that button now opens the sidebar in one click; selecting via the
  checkbox first would toggle the space off when Show details toggles it on)
- fix broken scan selectors: 'appSidebarDiv' -> 'appSidebar' (not a key in
  the selectors map, was silently falling through to the literal string);
  'tippyBox' -> 'ocModal' at the confirm-action scan (the modal is what's
  actually rendered there, not a tippy); 'filesView' -> 'adminSettingsWrapper'
  in performSpaceAction (this runs on the admin-settings page, not files)
- wrap transitionend waits in Promise.all with their triggering click, so
  the listener attaches before the transition begins - otherwise a near-
  instant transition (under prefers-reduced-motion: reduce, enabled by an
  earlier fix in this branch) can finish before the listener binds and
  the wait never resolves, hanging the "list members via sidebar" test

* fix(e2e): mark kindergarten journey test as slow

The journey performs 16 downloads plus shares and deletes, each cycling
the sidebar with a11y scans, and consistently runs 3-4 minutes even in
isolation - past the default 180s timeout. When the deadline hits, the
axe scan in flight fails with "Target page, context or browser has been
closed" from a different call site each run.

test.slow() triples the timeout to 540s, the idiomatic Playwright hint
for legitimately long journey tests.

* fix(e2e): add aria-label to create-user button when icon-only

When admin-settings shrinks to a limited-width viewport, the create-user
button collapses to icon-only and its visible text label is hidden. The
tooltip already switches to the accessible name in that mode; mirror
that on aria-label so the button retains an accessible name in the
collapsed state (WCAG 4.1.2).

* fix(e2e): import expect in crashPage step helpers

expectCrashPageHasNoAccessibilityViolations uses expect() but the
import only included Page - the file wouldn't compile if that helper
was referenced anywhere.

* fix(e2e): pass selector variables to admin-settings users a11y scans

Four call sites passed string keys ('loginToggleWithDropdown',
'loginDropDown', 'groupsModalInput') that don't exist in the shared
selectors map - assertNoSevereA11yViolations' fallback then used those
literal strings as raw CSS selectors, matching nothing, so axe threw
"No elements found for include" instead of actually scanning. Same
class of bug as the earlier 'tippbBox'/'sidebarPanel'/'linkUpdateDialog'
fixes in this branch.

Switched to passing the local const variables directly, which resolve
to the real CSS selectors defined in the same file.

* fix(e2e): scan notifications dropdown container instead of message list

Both notification-related scans passed notificationItemsMessages, which
is a selector that matches multiple elements (one per notification). axe
throws on multi-match includes. Switched to notificationsDrop, the
single container that wraps the message list.

* fix(e2e): wait for link-update dialog before scanning it

Four call sites (changeRole, changeName, addExpiration, deleteLink) ran
assertNoSevereA11yViolations on the linkUpdateDialog notification right
after the action that triggers it, without waiting for the notification
to actually appear - axe would race and sometimes scan before the DOM
was there.

Also fixed copyLinkToClipboard: previously scanned '.snackbar' (which
doesn't exist in this codebase) unconditionally; now waits for the
linkUpdateDialog and scans it, or for the password-protected-folder
case, waits inside the iframe and scans the iframe locator instead
(mirroring the pattern already used by open() in utils/sidebar.ts).

* fix(e2e): scan iframe locator for password-protected-folder sidebar

Two scans in the passwordProtectedFolder branch were pointed at
top-level page selectors ('tippyBox', the plain sidebarPanel const)
but that sidebar lives inside its own iframe (#iframe-folder-view),
not on the top-level page - so axe found nothing to scan and threw.

Switched to scanning the iframe locator itself. In open()'s post-open
scan, made the target conditional so the non-iframe branch keeps
scanning #app-sidebar as before.

* fix(e2e): drop premature tippyBox scan before more-options dropdown opens

createShare scanned the tippyBox before clicking showMoreOptionsButton,
but the tippy isn't in the DOM yet at that point - the click on the
button is what opens it. The second scan a couple of lines below runs
after the click, when the dropdown is actually rendered, which is the
only place the scan belongs.

* fix(e2e): scan body in shared createSpace instead of #files-view

createSpace is invoked from both the Files app spaces view (which has
#files-view) and the admin-settings spaces page (which has
#admin-settings-wrapper instead) - scanning a single view-specific
root failed in one of the two callers. Scan the always-present body
so both callers work.

* fix(e2e): make resource-action a11y scans robust to timing and view mode

- clickResource: it's used for both folder navigation (breadcrumb
  appears) and file-open (navigates away into a viewer/editor with no
  breadcrumb). The unconditional post-click scan of 'breadcrumb' timed
  out on file opens. Wait for the breadcrumb with a 5s cap and skip
  the scan when it never appears.
- createNewFolder: was scanning 'filesSpaceTable' which only exists in
  table view. Scan the view-mode-agnostic 'filesView' wrapper instead.
- downloadResources / pasteResource / moveOrCopyResource: add waitFor
  on the target selector before axe scans it, otherwise axe can race
  and scan before the DOM updates from the preceding click.

* fix(web-app-app-store): fix TS2322 type error in AppImageGallery aria-label
2026-07-13 07:50:03 +02:00
owncloud-translations-bot[bot] fa077e7eeb chore: update translations from transifex (#12553)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-07-12 14:40:50 +00:00
owncloud-translations-bot[bot] 382d95a3eb chore: update translations from transifex (#12552)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-07-11 13:04:53 +02:00
339 changed files with 8653 additions and 5012 deletions

No files matched your search

+3
View File
@@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: ownCloud GmbH - A Kiteworks Company and ownCloud contributors
# SPDX-License-Identifier: Apache-2.0
#
# Managed by owncloud/admin — edit codeowners/ownership.yml, not this file.
# Generated by scripts/sync-codeowners.py. Last matching pattern wins.
* @owncloud/ocis-maintainers
+1
View File
@@ -217,6 +217,7 @@ jobs:
- apiOcm
# collaboration (needs WOPI)
- apiCollaboration
- apiVault
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+17 -13
View File
@@ -109,9 +109,11 @@ jobs:
path: |
.
!.git
!web
retention-days: 1
docker-build:
if: false
name: docker-build (${{ matrix.arch }}, ${{ matrix.repo }})
runs-on: ${{ matrix.arch == 'amd64' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
needs: [determine-release-type, generate-code, security-scan-trivy]
@@ -125,8 +127,8 @@ jobs:
with:
name: generated-code
path: .
- uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
- uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
- uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
- uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -152,7 +154,7 @@ jobs:
printf "tags<<EOF\n%s\nEOF\n" \
"${REPO}:${VERSION}-linux-${ARCH}" >> $GITHUB_OUTPUT
- id: build
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
with:
context: ocis
file: ocis/docker/Dockerfile.linux.${{ matrix.arch }}
@@ -165,7 +167,7 @@ jobs:
VERSION=${{ needs.determine-release-type.outputs.version }}
tags: ${{ steps.tags.outputs.tags }}
- id: trivy
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
continue-on-error: true
with:
image-ref: ${{ steps.tags.outputs.tags }}
@@ -196,7 +198,7 @@ jobs:
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
- uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
id: trivy
continue-on-error: true
with:
@@ -217,6 +219,7 @@ jobs:
exit 1
docker-manifest:
if: false
name: docker-manifest (${{ matrix.repo }})
runs-on: ubuntu-latest
needs: [determine-release-type, docker-build, docker-scan]
@@ -224,7 +227,7 @@ jobs:
matrix:
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
steps:
- uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
- uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ vars.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -242,6 +245,7 @@ jobs:
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
docker-readme:
if: false
name: docker-readme (${{ matrix.repo }})
runs-on: ubuntu-latest
needs: [determine-release-type, docker-manifest]
@@ -289,7 +293,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
- uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1 # v0.35.0
with:
scan-type: fs
format: table
@@ -313,6 +317,10 @@ jobs:
with:
go-version-file: go.mod
- run: npm install --silent -g yarn npx "pnpm@$PNPM_VERSION" --force
# web is excluded from the generated-code artifact (see generate-code) to
# avoid OOM on upload, so its node_modules — which provides the
# license-checker-rseidelsohn binary — must be reinstalled here.
- run: cd web && pnpm install
- run: make ci-node-check-licenses && make ci-node-save-licenses
- run: make ci-go-check-licenses && make ci-go-save-licenses
- run: tar -czf third-party-licenses.tar.gz -C third-party-licenses .
@@ -347,7 +355,7 @@ jobs:
create-github-release:
runs-on: ubuntu-latest
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy, docker-readme]
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
steps:
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
@@ -378,10 +386,6 @@ jobs:
needs:
- determine-release-type
- generate-code
- docker-build
- docker-scan
- docker-manifest
- docker-readme
- build-binaries
- security-scan-trivy
- license-check
@@ -405,7 +409,7 @@ jobs:
python3 scripts/audit-release.py \
--version "${{ needs.determine-release-type.outputs.version }}" \
--dir release-assets/ \
--github-release --docker
--github-release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,10 @@
Bugfix: Stop breadcrumb items from being announced twice
Each breadcrumb list item had `tabindex="0"`, putting the item itself in the
keyboard/screen reader focus order in addition to the link or button nested
inside it. This caused every breadcrumb segment to be announced twice in a
row. The list item is no longer a separate focus stop; only its inner link
or button is, while the item remains focusable enough for existing
drag-and-drop styling to keep working.
https://github.com/owncloud/ocis/pull/12643
@@ -0,0 +1,28 @@
Bugfix: Fix low-contrast form controls in dark and vault themes
Several form controls were hard to see against dark and vault theme
backgrounds. The view-options range slider had no visible track border and
relied on an opacity dip on hover, making it barely visible at rest. The
switch component's off-state track and thumb, and its on-state thumb, used
colors too close to their surrounding background to read as a toggle. The
select combobox's highlighted/selected option text used a color too close to
the highlight background.
The global search input's text color was forced with `!important`,
overriding the theme-specific search text color some themes set, which made
typed text render in white on a white search input background in the vault
"Dark Theme – High Contrast". The search placeholder color also used an
invalid CSS custom property fallback (a bare property name instead of a
nested `var()`), silently breaking the placeholder color for any theme that
didn't define a search-specific placeholder token, and the vault "Dark
Theme"'s placeholder color was too close to its input's text and border color
to read as muted.
The slider now has a visible border and no longer dims on rest, the switch
and select now use colors with sufficient contrast against their
backgrounds, the `!important` override blocking theme-specific search colors
has been removed, the invalid placeholder fallback has been fixed, and the
vault "Dark Theme" placeholder color has been changed to one with visible
contrast against the input text.
https://github.com/owncloud/ocis/pull/12639
@@ -0,0 +1,9 @@
Bugfix: Fix keyboard navigation in "New" and "Upload" dropdown menus
Opening the "New" or "Upload" dropdown menu in the Files app toolbar did
not move focus into the menu, so pressing the arrow keys had no effect
on the highlighted item, unlike the existing right-click context menu.
Both dropdowns now focus their first item on open, restoring arrow key
navigation.
https://github.com/owncloud/ocis/pull/12646
@@ -0,0 +1,10 @@
Bugfix: Remove unneeded keyboard focus stops
Some icons and date columns in tables (spaces list, file list) could
unexpectedly receive keyboard focus even though they don't trigger any
action, adding unnecessary stops when tabbing through the page. The
contextual helper icon also carried a label that duplicated the label
already present on its surrounding button. These redundant focus stops
and duplicate labels have been removed.
https://github.com/owncloud/ocis/pull/12645
@@ -0,0 +1,15 @@
Bugfix: Restore hover feedback in high-contrast and dark themes
The Light and Dark High-Contrast themes set the background-highlight color
token equal to the default page background, making hover backgrounds
indistinguishable from the resting background wherever background-highlight
was used for interactive feedback, such as the global search results
dropdown. The non-high-contrast Dark theme had the same collision.
background-highlight now matches background-hover in the affected theme
definitions, and the search results dropdown and create-shortcut context
menu now use the background-hover color directly for their hover and active
states, since background-highlight is otherwise used for static surfaces
like cards, modals and form fields rather than interaction feedback.
https://github.com/owncloud/ocis/pull/12613
@@ -0,0 +1,9 @@
Bugfix: Fix share metadata corruption during concurrent share operations
When multiple sharing service replicas processed share operations concurrently
for the same user, the share metadata could become corrupted with references to
missing data, making all shares inaccessible to that user. The received share
cache now uses compare-and-swap (etag) validation to detect concurrent writes
and retries gracefully, preventing metadata corruption.
https://github.com/owncloud/ocis/pull/12621
@@ -0,0 +1,12 @@
Bugfix: Preserve accessibility focus in the file versions sidebar
Opening the file versions panel with a keyboard or screen reader could move
focus to the main page, and restoring a version could briefly move focus to the
main page before selecting the sidebar's back button. The sidebar now manages
focus throughout panel transitions and loading states, restores focus to the
control that opened it when closed, and returns focus to the restored version's
Restore button after the operation completes. Version dates and action labels
also provide clearer context for screen reader users without duplicate
announcements or additional tab stops.
https://github.com/owncloud/ocis/pull/12630
@@ -0,0 +1,11 @@
Bugfix: Fix missing labels and low-contrast elements across the web UI
Several icon-only buttons (search, hide-share, create-user, gallery
navigation) were missing labels, and loading spinners and progress bars did
not expose a name describing what they represent. The global search and
create shortcut dropdowns now use correct roles and states. Tooltips no longer
get caught mid-fade with a low-contrast color when the reduced-motion system
setting is enabled, and low-contrast colors were fixed in the select combobox
search input and in markdown editor links and inline code.
https://github.com/owncloud/ocis/pull/12526
@@ -0,0 +1,10 @@
Enhancement: Improve page structure on several pages
We've added missing `main` and `footer` regions to several pages (404,
private link resolving, missing config, logout, access denied, public link
resolving) for a more consistent page structure. We've also fixed the
"Skip to main" link, which previously did nothing on pages using the plain
layout (login, logout, public/private link pages) due to a missing target id
and a stale cached DOM reference.
https://github.com/owncloud/ocis/pull/12637
@@ -0,0 +1,7 @@
Enhancement: Show the select-all checkbox label in tile view
The label of the select-all checkbox in the resource tiles view is now
visible, improving the user experience by making it clear what the
checkbox is for.
https://github.com/owncloud/ocis/pull/12640
@@ -0,0 +1,13 @@
Bugfix: Return correct issuerAssignedId on /me
The `/graph/v1.0/me` endpoint reported the internal user UUID as
`identities[].issuerAssignedId` instead of the issuer-assigned identity (the
OIDC `sub`). The endpoint took a fast path that built the user model from the
CS3 user in the request context, which does not carry the external identity, so
it fell back to the internal UUID. `/me` now always resolves the user through
the identity backend, which reads the stored external identity and returns the
correct value. Group memberships are still only expanded when
`$expand=memberOf` is requested.
https://github.com/owncloud/ocis/pull/12431
https://github.com/owncloud/ocis/pull/12411
@@ -0,0 +1,5 @@
Security: Restrict group member data to authorized users
The groups API could return group membership details to callers who should not have had access to it. Access to group member data is now properly restricted based on the caller's permissions.
https://github.com/owncloud/ocis/pull/12573
@@ -0,0 +1,8 @@
Security: Harden origin validation for embed mode delegated authentication
Hardened origin validation for the delegated authentication feature in Web's
embed mode. Deployments using `WEB_OPTION_EMBED_DELEGATE_AUTHENTICATION` should
ensure `WEB_OPTION_EMBED_DELEGATE_AUTHENTICATION_ORIGIN` is explicitly
configured.
https://github.com/owncloud/ocis/pull/12572
+7 -2
View File
@@ -11,11 +11,16 @@
},
"require-dev": {
"ext-simplexml": "*",
"bamarni/composer-bin-plugin": "^1.8"
"bamarni/composer-bin-plugin": "^1.8",
"playwright-php/playwright": "^1.2"
},
"extra": {
"bamarni-bin": {
"bin-links": false
}
},
"require": {
"khanamiryan/qrcode-detector-decoder": "^2.0",
"spomky-labs/otphp": "^11.5"
}
}
}
+17 -17
View File
@@ -10,10 +10,10 @@ require (
github.com/MicahParks/keyfunc/v2 v2.1.0
github.com/Nerzal/gocloak/v13 v13.9.0
github.com/bbalet/stopwords v1.0.0
github.com/beevik/etree v1.6.0
github.com/beevik/etree v1.7.0
github.com/blevesearch/bleve/v2 v2.6.0
github.com/cenkalti/backoff v2.2.1+incompatible
github.com/coreos/go-oidc/v3 v3.19.0
github.com/coreos/go-oidc/v3 v3.20.0
github.com/cs3org/go-cs3apis v0.0.0-20241105092511-3ad35d174fc1
github.com/davidbyttow/govips/v2 v2.18.0
github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8
@@ -21,10 +21,10 @@ require (
github.com/egirna/icap-client v0.1.1
github.com/gabriel-vasile/mimetype v1.4.13
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.3.0
github.com/go-chi/chi/v5 v5.3.1
github.com/go-chi/httprate v0.16.0
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.13
github.com/go-ldap/ldap/v3 v3.4.14
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3
github.com/go-micro/plugins/v4/client/grpc v1.2.1
github.com/go-micro/plugins/v4/logger/zerolog v1.2.0
@@ -50,7 +50,7 @@ require (
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.22
github.com/kovidgoyal/imaging v1.8.23
github.com/leonelquinteros/gotext v1.7.2
github.com/libregraph/idm v0.5.0
github.com/libregraph/lico v0.67.0
@@ -66,7 +66,7 @@ require (
github.com/open-policy-agent/opa v1.18.2
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-20260710104539-1f85e04c1e35
github.com/owncloud/reva/v2 v2.0.0-20260722181911-d084587fefc7
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.23.2
@@ -96,16 +96,16 @@ require (
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.44.0
go.opentelemetry.io/otel/sdk v1.44.0
go.opentelemetry.io/otel/trace v1.44.0
golang.org/x/crypto v0.53.0
golang.org/x/crypto v0.54.0
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f
golang.org/x/image v0.43.0
golang.org/x/net v0.56.0
golang.org/x/image v0.44.0
golang.org/x/net v0.57.0
golang.org/x/oauth2 v0.36.0
golang.org/x/sync v0.21.0
golang.org/x/term v0.44.0
golang.org/x/text v0.38.0
golang.org/x/sync v0.22.0
golang.org/x/term v0.45.0
golang.org/x/text v0.40.0
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa
google.golang.org/grpc v1.82.0
google.golang.org/grpc v1.82.1
google.golang.org/protobuf v1.36.11
gopkg.in/yaml.v2 v2.4.0
gotest.tools/v3 v3.5.2
@@ -186,7 +186,7 @@ require (
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/gdexlab/go-render v1.0.1 // indirect
github.com/go-acme/lego/v4 v4.34.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
github.com/go-git/go-billy/v5 v5.9.0 // indirect
github.com/go-git/go-git/v5 v5.19.1 // indirect
@@ -341,10 +341,10 @@ require (
go.uber.org/zap v1.27.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.36.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.45.0 // indirect
golang.org/x/tools v0.47.0 // indirect
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
+34 -34
View File
@@ -104,8 +104,8 @@ github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/bbalet/stopwords v1.0.0 h1:0TnGycCtY0zZi4ltKoOGRFIlZHv0WqpoIGUsObjztfo=
github.com/bbalet/stopwords v1.0.0/go.mod h1:sAWrQoDMfqARGIn4s6dp7OW7ISrshUD8IP2q3KoqPjc=
github.com/beevik/etree v1.6.0 h1:u8Kwy8pp9D9XeITj2Z0XtA5qqZEmtJtuXZRQi+j03eE=
github.com/beevik/etree v1.6.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
github.com/beevik/etree v1.7.0 h1:xjBk9O4p4x7D1YajePjfLzdaFC4/uYUENA7P0pv6gXA=
github.com/beevik/etree v1.7.0/go.mod h1:bh4zJxiIr62SOf9pRzN7UUYaEDa9HEKafK25+sLc0Gc=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
@@ -188,8 +188,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coreos/go-oidc/v3 v3.19.0 h1:F/xyOi3x1UnG1U27YVnM1N6bHiL1K2upi6U/0qr8r+I=
github.com/coreos/go-oidc/v3 v3.19.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-oidc/v3 v3.20.0 h1:EtE0WIBHk03N+DqGkY4+UONzzZHk7amKt6IyNd7OsZE=
github.com/coreos/go-oidc/v3 v3.20.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=
@@ -286,10 +286,10 @@ github.com/go-acme/lego/v4 v4.34.0 h1:oRsIuPJ4ORX7ufviXvelUpBSez2XxeKGwo5pNG9BVe
github.com/go-acme/lego/v4 v4.34.0/go.mod h1:gsmdlx/ZS6OUeXbOj0U+VnCLLfEFj4WCYRkcGpZw+pc=
github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
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-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
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.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
@@ -317,8 +317,8 @@ github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBj
github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
github.com/go-ldap/ldap/v3 v3.1.7/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q=
github.com/go-ldap/ldap/v3 v3.4.13 h1:+x1nG9h+MZN7h/lUi5Q3UZ0fJ1GyDQYbPvbuH38baDQ=
github.com/go-ldap/ldap/v3 v3.4.13/go.mod h1:LxsGZV6vbaK0sIvYfsv47rfh4ca0JXokCoKjZxsszv0=
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3 h1:sfz1YppV05y4sYaW7kXZtrocU/+vimnIWt4cxAYh7+o=
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3/go.mod h1:ZXFhGda43Z2TVbfGZefXyMJzsDHhCh0go3bZUcwTx7o=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
@@ -597,8 +597,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.22 h1:CtpoRXQpS79xxJsKu8+LUJJE/0i4FLquJZy0QH+QNlM=
github.com/kovidgoyal/imaging v1.8.22/go.mod h1:y8wo4JTv4D+skbtQf6fHg8nA1qtagvCcn8J2Nu5k2Jg=
github.com/kovidgoyal/imaging v1.8.23 h1:4WsboyQ/E8tic2kX49P93Rvscg33SPsCwTBG5EZZF54=
github.com/kovidgoyal/imaging v1.8.23/go.mod h1:k3Iot3H0v2rSWXIxQISfT3e9wIryqzAHLHCuhG7z9lM=
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=
@@ -739,8 +739,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-20260710104539-1f85e04c1e35 h1:40KHez6z6Ea+MHatRfZp4ZTX1TASGRG5UfvOpsQRbgU=
github.com/owncloud/reva/v2 v2.0.0-20260710104539-1f85e04c1e35/go.mod h1:m2fGRZDsnNSBszbnwysuq7uhlitQ90+weX4FFQRdkak=
github.com/owncloud/reva/v2 v2.0.0-20260722181911-d084587fefc7 h1:VGWhUAYu3TYCmkvk5PNG2+rEH7VFR2uxny/ZQXaE71g=
github.com/owncloud/reva/v2 v2.0.0-20260722181911-d084587fefc7/go.mod h1:m2fGRZDsnNSBszbnwysuq7uhlitQ90+weX4FFQRdkak=
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=
@@ -1015,8 +1015,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.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
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=
@@ -1031,8 +1031,8 @@ golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f h1:W3F4c+6OLc6H2lb//N1q4WpJk
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f/go.mod h1:J1xhfL/vlindoeF/aINzNzt2Bket5bjo9sdOYzOsU80=
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.43.0 h1:FLxcP4ec2350nTfOC8ysKtqYSIFbk/QGjw1ZHNP4tsY=
golang.org/x/image v0.43.0/go.mod h1:rrpelvGFt+kLPAjPM4HeWPgrl0FtafueU//e5N0qk/Q=
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
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=
@@ -1054,8 +1054,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.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
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=
@@ -1099,8 +1099,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.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
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=
@@ -1124,8 +1124,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -1188,8 +1188,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.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
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=
@@ -1197,8 +1197,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.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
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=
@@ -1210,8 +1210,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.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
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=
@@ -1264,8 +1264,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.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
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=
@@ -1343,8 +1343,8 @@ google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3Iji
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e h1:m7aQHHqd0q89mRwhwS9Bx2rjyl/hsFAeta+uGrHsQaU=
google.golang.org/grpc/examples v0.0.0-20211102180624-670c133e568e/go.mod h1:gID3PKrg7pWKntu9Ss6zTLJ0ttC0X9IHgREOCZwbCVU=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
@@ -128,6 +128,20 @@ func WopiContextAuthMiddleware(cfg *config.Config, st microstore.Store, next htt
claims.WopiContext.AccessToken = wopiContextAccessToken
// The view only token is encrypted the same way as the access token
// (see GenerateWopiToken). Decrypt it so downstream consumers get the
// plaintext reva token. It is only set for view only shares, so skip
// the decryption when it is empty.
if claims.WopiContext.ViewOnlyToken != "" {
wopiContextViewOnlyToken, err := DecryptAES([]byte(cfg.Wopi.Secret), claims.WopiContext.ViewOnlyToken)
if err != nil {
wopiLogger.Error().Err(err).Msg("failed to decrypt view only token")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
claims.WopiContext.ViewOnlyToken = wopiContextViewOnlyToken
}
ctx = context.WithValue(ctx, wopiContextKey, claims.WopiContext)
// authentication for the CS3 api
ctx = metadata.AppendToOutgoingContext(ctx, ctxpkg.TokenHeader, claims.WopiContext.AccessToken)
@@ -201,6 +215,18 @@ func GenerateWopiToken(wopiContext WopiContext, cfg *config.Config, st microstor
return "", 0, err
}
// The view only token is a reva token that impersonates the resource owner.
// It must never be exposed in plaintext inside the (readable) WOPI JWT, so
// encrypt it the same way as the access token. It is only set for view only
// shares, so skip the encryption when it is empty.
if wopiContext.ViewOnlyToken != "" {
cryptedViewOnlyToken, err := EncryptAES([]byte(cfg.Wopi.Secret), wopiContext.ViewOnlyToken)
if err != nil {
return "", 0, err
}
wopiContext.ViewOnlyToken = cryptedViewOnlyToken
}
cs3Claims := &jwt.RegisteredClaims{}
_, err = jwt.ParseWithClaims(wopiContext.AccessToken, cs3Claims, func(token *jwt.Token) (interface{}, error) {
if token.Method != jwt.SigningMethodHS256 {
@@ -11,6 +11,7 @@ import (
appprovider "github.com/cs3org/go-cs3apis/cs3/app/provider/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
providerv1beta1 "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/golang-jwt/jwt/v5"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/owncloud/ocis/v2/services/collaboration/pkg/config"
@@ -168,6 +169,60 @@ var _ = Describe("Wopi Context Middleware", func() {
mw.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
})
It("Should encrypt the ViewOnlyToken inside the WOPI token and restore it on the way in", func() {
// a known, recognizable plaintext so we can assert it is not readable in the JWT
const viewOnlyPlaintext = "my-secret-view-only-token"
// capture the WopiContext the middleware hands to the next handler
var captured middleware.WopiContext
var capturedErr error
capturingNext := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
captured, capturedErr = middleware.WopiContextFromCtx(r.Context())
w.WriteHeader(http.StatusOK)
})
capturingMw := middleware.WopiContextAuthMiddleware(cfg, nil, capturingNext)
token, err := tknMngr.MintToken(ctx, user, nil)
Expect(err).ToNot(HaveOccurred())
wopiContext := middleware.WopiContext{
AccessToken: token,
ViewOnlyToken: viewOnlyPlaintext,
ViewMode: appprovider.ViewMode_VIEW_MODE_VIEW_ONLY,
FileReference: &providerv1beta1.Reference{
ResourceId: rid,
Path: ".",
},
}
wopiToken, ttl, err := middleware.GenerateWopiToken(wopiContext, cfg, nil)
Expect(err).ToNot(HaveOccurred())
// Security property: the plaintext view-only token must not be recoverable
// from the (readable) JWT. Parse the JWT and assert the ViewOnlyToken claim
// is present but is ciphertext, not the plaintext value.
claims := &middleware.Claims{}
_, err = jwt.ParseWithClaims(wopiToken, claims, func(t *jwt.Token) (interface{}, error) {
return []byte(cfg.Wopi.Secret), nil
})
Expect(err).ToNot(HaveOccurred())
Expect(claims.WopiContext.ViewOnlyToken).ToNot(BeEmpty())
Expect(claims.WopiContext.ViewOnlyToken).ToNot(Equal(viewOnlyPlaintext))
// No-regression property: the middleware must decrypt the token back to the
// original plaintext so downstream consumers get a usable reva token.
req := httptest.NewRequest("GET", src.String(), nil).WithContext(ctx)
q := req.URL.Query()
q.Add("access_token", wopiToken)
q.Add("access_token_ttl", strconv.FormatInt(ttl, 10))
req.URL.RawQuery = q.Encode()
resp := httptest.NewRecorder()
capturingMw.ServeHTTP(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
Expect(capturedErr).ToNot(HaveOccurred())
Expect(captured.ViewOnlyToken).To(Equal(viewOnlyPlaintext))
})
It("Should authorize successful with template reference", func() {
req := httptest.NewRequest("GET", src.String(), nil).WithContext(ctx)
token, err := tknMngr.MintToken(ctx, user, nil)
+4
View File
@@ -262,6 +262,10 @@ func (g Graph) GetGroup(w http.ResponseWriter, r *http.Request) {
return
}
if !g.contextUserHasFullAccountPerms(r.Context()) {
group.Members = nil
}
render.Status(r, http.StatusOK)
render.JSON(w, r, group)
}
@@ -303,6 +303,12 @@ var _ = Describe("Groups", func() {
Context("with an existing group", func() {
BeforeEach(func() {
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
Permission: &settingsmsg.Permission{
Operation: settingsmsg.Permission_OPERATION_UNKNOWN,
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
},
}, nil)
identityBackend.On("GetGroup", mock.Anything, mock.Anything, mock.Anything).Return(newGroup, nil)
})
@@ -317,6 +323,76 @@ var _ = Describe("Groups", func() {
Expect(rr.Code).To(Equal(http.StatusOK))
})
})
It("does not leak group members to unprivileged users", func() {
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{}, nil)
group := &libregraph.Group{}
group.SetId("group1")
group.SetDisplayName("Group Name")
group.SetMembers(
[]libregraph.User{
{
Id: libregraph.PtrString("userid"),
},
},
)
identityBackend.On("GetGroup", mock.Anything, mock.Anything, mock.Anything).Return(group, nil)
r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/groups/group1?$expand=members", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("groupID", "group1")
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, nil), chi.RouteCtxKey, rctx))
svc.GetGroup(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
data, err := io.ReadAll(rr.Body)
Expect(err).ToNot(HaveOccurred())
respGroup := libregraph.Group{}
err = json.Unmarshal(data, &respGroup)
Expect(err).ToNot(HaveOccurred())
Expect(respGroup.Members).To(BeEmpty())
})
It("returns group members to privileged users", func() {
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
Permission: &settingsmsg.Permission{
Operation: settingsmsg.Permission_OPERATION_UNKNOWN,
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
},
}, nil)
group := &libregraph.Group{}
group.SetId("group1")
group.SetDisplayName("Group Name")
group.SetMembers(
[]libregraph.User{
{
Id: libregraph.PtrString("userid"),
},
},
)
identityBackend.On("GetGroup", mock.Anything, mock.Anything, mock.Anything).Return(group, nil)
r := httptest.NewRequest(http.MethodGet, "/graph/v1.0/groups/group1?$expand=members", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("groupID", "group1")
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, nil), chi.RouteCtxKey, rctx))
svc.GetGroup(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
data, err := io.ReadAll(rr.Body)
Expect(err).ToNot(HaveOccurred())
respGroup := libregraph.Group{}
err = json.Unmarshal(data, &respGroup)
Expect(err).ToNot(HaveOccurred())
Expect(respGroup.Members).To(HaveLen(1))
Expect(respGroup.Members[0].GetId()).To(Equal("userid"))
})
})
Describe("PostGroup", func() {
+16 -16
View File
@@ -62,22 +62,22 @@ func (g Graph) GetMe(w http.ResponseWriter, r *http.Request) {
return
}
var me *libregraph.User
// We can just return the user from context unless we need to expand the group memberships
if !slices.Contains(exp, "memberOf") {
me = identity.CreateUserModelFromCS3(u)
} else {
var err error
logger.Debug().Msg("calling get user on backend")
me, err = g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
if err != nil {
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
errorcode.RenderError(w, r, err)
return
}
if me.MemberOf == nil {
me.MemberOf = []libregraph.Group{}
}
// Always resolve the user through the identity backend. The CS3 user from
// the request context does not carry the issuer-assigned identity (OIDC
// sub), so building the model from it (CreateUserModelFromCS3) would report
// the internal user UUID as identities[].issuerAssignedId. The backend reads
// the stored external identity and returns the correct value. Group
// memberships are only expanded (and thus only queried) when $expand=memberOf
// is requested, so the extra cost here is a single user lookup.
logger.Debug().Msg("calling get user on backend")
me, err := g.identityBackend.GetUser(r.Context(), u.GetId().GetOpaqueId(), odataReq)
if err != nil {
logger.Debug().Err(err).Interface("user", u).Msg("could not get user from backend")
errorcode.RenderError(w, r, err)
return
}
if slices.Contains(exp, "memberOf") && me.MemberOf == nil {
me.MemberOf = []libregraph.Group{}
}
// expand appRoleAssignments if requested
@@ -115,6 +115,16 @@ var _ = Describe("Users", func() {
})
It("gets the information", func() {
user := &libregraph.User{
Id: libregraph.PtrString("user"),
Identities: []libregraph.ObjectIdentity{
{
Issuer: libregraph.PtrString("https://idp.example.com"),
IssuerAssignedId: libregraph.PtrString("the-oidc-sub"),
},
},
}
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
Return(&settings.GetValueResponse{
Value: &settingsmsg.ValueWithIdentifier{
@@ -139,6 +149,19 @@ var _ = Describe("Users", func() {
svc.GetMe(rr, r)
Expect(rr.Code).To(Equal(http.StatusOK))
data, err := io.ReadAll(rr.Body)
Expect(err).ToNot(HaveOccurred())
responseUser := &libregraph.User{}
err = json.Unmarshal(data, &responseUser)
Expect(err).ToNot(HaveOccurred())
// The identity (issuerAssignedId, the OIDC sub) must come from the
// backend, not be fabricated from the internal user UUID. See
// OCISDEV-751.
Expect(responseUser.GetIdentities()).To(HaveLen(1))
Expect(responseUser.GetIdentities()[0].GetIssuerAssignedId()).To(Equal("the-oidc-sub"))
})
It("expands the memberOf", func() {
@@ -193,6 +216,10 @@ var _ = Describe("Users", func() {
RoleId: "some-appRole-ID",
},
}
user := &libregraph.User{
Id: libregraph.PtrString("user"),
}
identityBackend.On("GetUser", mock.Anything, mock.Anything, mock.Anything).Return(user, nil)
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, nil)
valueService.On("GetValueByUniqueIdentifiers", mock.Anything, mock.Anything, mock.Anything).
Return(&settings.GetValueResponse{
-1
View File
@@ -21,4 +21,3 @@ Make sure to configure the same store in the proxy service.
Store specific notes:
- When using `redis-sentinel`, the Redis master to use is configured via e.g. `OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES` in the form of `<sentinel-host>:<sentinel-port>/<redis-master>` like `10.10.0.200:26379/mymaster`.
- When using `nats-js-kv` it is recommended to set `PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES` to the same value as `OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES`. That way the proxy uses the same nats instance as the ocs service.
- When using `ocisstoreservice` the `OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES` must be set to the service name `com.owncloud.api.store`. It does not support TTL and stores the presigning keys indefinitely. Also, the store service needs to be started.
-1
View File
@@ -365,7 +365,6 @@ Store specific notes:
To authenticate presigned URLs the proxy service needs to read signing keys from a store that is populated by the ocs service. Possible stores are:
- `nats-js-kv`: Stores data using key-value-store feature of [nats jetstream](https://docs.nats.io/nats-concepts/jetstream/key-value-store)
- `redis-sentinel`: Stores data in a configured Redis Sentinel cluster.
- `ocisstoreservice`: Stores data in the legacy ocis store service. Requires setting `PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES` to `com.owncloud.api.store`.
The `memory` store cannot be used as it does not share the memory from the ocs service signing key memory store, even in a single process.
+1 -1
View File
@@ -194,7 +194,7 @@ type PreSignedURL struct {
// SigningKeys is a store configuration.
type SigningKeys struct {
Store string `yaml:"store" env:"OCIS_CACHE_STORE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE" desc:"The type of the signing key store. Supported values are: 'redis-sentinel', 'nats-js-kv' and 'ocisstoreservice' (deprecated). See the text description for details." introductionVersion:"5.0"`
Store string `yaml:"store" env:"OCIS_CACHE_STORE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE" desc:"The type of the signing key store. Supported values are: 'redis-sentinel' and 'nats-js-kv'. See the text description for details." introductionVersion:"5.0"`
Nodes []string `yaml:"addresses" env:"OCIS_CACHE_STORE_NODES;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_NODES" desc:"A list of nodes to access the configured store. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"5.0"`
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_TTL" desc:"Default time to live for signing keys. See the Environment Variable Types description for more details." introductionVersion:"5.0"`
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_DISABLE_PERSISTENCE" desc:"Disables persistence of the store. Only applies when store type 'nats-js-kv' is configured. Defaults to true." introductionVersion:"5.0"`
+10 -10
View File
@@ -147,7 +147,7 @@
"colorPalette": {
"background-accentuate": "rgba(255, 255, 5, 0.1)",
"background-default": "#ffffff",
"background-highlight": "#ffffff",
"background-highlight": "oklch(87.2% 0.01 258.338)",
"background-muted": "#ffffff",
"background-secondary": "#ffffff",
"background-hover": "oklch(87.2% 0.01 258.338)",
@@ -212,7 +212,7 @@
"colorPalette": {
"background-accentuate": "#696969",
"background-default": "#000000",
"background-highlight": "#000000",
"background-highlight": "#383838",
"background-muted": "oklch(21% 0.034 264.665)",
"background-secondary": "#404040",
"background-hover": "#383838",
@@ -279,7 +279,7 @@
"colorPalette": {
"background-accentuate": "#696969",
"background-default": "#000000",
"background-highlight": "#000000",
"background-highlight": "oklch(21% 0.034 264.665)",
"background-muted": "#000000",
"background-secondary": "#000000",
"background-hover": "oklch(21% 0.034 264.665)",
@@ -379,8 +379,8 @@
"swatch-passive-hover-outline": "#F7D496",
"swatch-passive-muted": "#99bae0",
"swatch-passive-contrast": "#000000",
"swatch-primary-default": "#F0AA39",
"swatch-primary-hover": "#CA912B",
"swatch-primary-default": "#9C6B00",
"swatch-primary-hover": "#6C4500",
"swatch-primary-muted": "#F0AA39",
"swatch-primary-muted-hover": "#CA912B",
"swatch-primary-gradient": "#F0AA39",
@@ -423,7 +423,7 @@
"colorPalette": {
"background-accentuate": "rgba(255, 255, 5, 0.1)",
"background-default": "#ffffff",
"background-highlight": "#ffffff",
"background-highlight": "oklch(87.2% 0.01 258.338)",
"background-muted": "#ffffff",
"background-secondary": "#ffffff",
"background-hover": "oklch(87.2% 0.01 258.338)",
@@ -489,7 +489,7 @@
"colorPalette": {
"background-accentuate": "#696969",
"background-default": "#000000",
"background-highlight": "#000000",
"background-highlight": "#383838",
"background-muted": "oklch(21% 0.034 264.665)",
"background-secondary": "#404040",
"background-hover": "#383838",
@@ -500,8 +500,8 @@
"input-bg": "#000000",
"input-border": "#ffffff",
"input-text-default": "#ffffff",
"input-text-muted": "#f8f8f8",
"search-input-text-muted": "#f8f8f8",
"input-text-muted": "#bdbfc3",
"search-input-text-muted": "#bdbfc3",
"swatch-brand-default": "#191A25",
"swatch-brand-hover": "#ffffff",
"swatch-brand-contrast": "#F0AA39",
@@ -563,7 +563,7 @@
"colorPalette": {
"background-accentuate": "#696969",
"background-default": "#000000",
"background-highlight": "#000000",
"background-highlight": "oklch(21% 0.034 264.665)",
"background-muted": "#000000",
"background-secondary": "#000000",
"background-hover": "oklch(21% 0.034 264.665)",
+46 -22
View File
@@ -191,15 +191,20 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string $path
* @param boolean $isVault
*
* @return string
*/
public static function getFullUrl(string $baseUrl, string $path): string {
public static function getFullUrl(string $baseUrl, string $path, bool $isVault = false): string {
$fullUrl = $baseUrl;
if (\substr($fullUrl, -1) !== '/') {
$fullUrl .= '/';
}
$fullUrl .= 'graph/v1.0/' . $path;
if ($isVault) {
$fullUrl .= 'vault/graph/v1.0/' . $path;
} else {
$fullUrl .= 'graph/v1.0/' . $path;
}
return $fullUrl;
}
@@ -338,12 +343,24 @@ class GraphHelper {
string $userName,
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'users/' . $userName);
if (KeycloakHelper::isTestingWithKeycloak()) {
return HttpRequestHelper::get(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . KeycloakHelper::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
);
}
return HttpRequestHelper::get(
$url,
$adminUser,
$adminPassword,
self::getRequestHeaders(),
);
}
/**
@@ -416,24 +433,27 @@ class GraphHelper {
/**
* @param string $baseUrl
* @param string $adminUser
* @param string $adminPassword
* @param string $userName
* @param string|null $adminUser
* @param string|null $adminPassword
* @param array|null $headers
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function deleteUser(
string $baseUrl,
string $adminUser,
string $adminPassword,
string $userName,
?string $adminUser = null,
?string $adminPassword = null,
?array $headers = null,
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'users/' . $userName);
return HttpRequestHelper::delete(
$url,
$adminUser,
$adminPassword,
$headers,
);
}
@@ -911,22 +931,24 @@ class GraphHelper {
* Send Graph Create Space Request
*
* @param string $baseUrl
* @param string $user
* @param string $password
* @param string|null $user
* @param string|null $password
* @param string $body
* @param array $headers
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function createSpace(
string $baseUrl,
string $user,
string $password,
?string $user = null,
?string $password = null,
string $body,
array $headers = [],
bool $isVault = false,
): ResponseInterface {
$url = self::getFullUrl($baseUrl, 'drives');
$url = self::getFullUrl($baseUrl, 'drives', $isVault);
return HttpRequestHelper::post($url, $user, $password, $headers, $body);
}
@@ -961,11 +983,12 @@ class GraphHelper {
* Send Graph List My Spaces Request
*
* @param string $baseUrl
* @param string $user
* @param string $password
* @param string $urlArguments
* @param array $body
* @param array $headers
* @param string|null $user
* @param string|null $password
* @param string|null $urlArguments
* @param array|null $body
* @param array|null $headers
* @param boolean $isVault
*
* @return ResponseInterface
*
@@ -973,14 +996,15 @@ class GraphHelper {
*/
public static function getMySpaces(
string $baseUrl,
string $user,
string $password,
string $urlArguments = '',
array $body = [],
array $headers = [],
?string $user = null,
?string $password = null,
?string $urlArguments = '',
?array $body = [],
?array $headers = [],
?bool $isVault = false,
): ResponseInterface {
$urlArguments = $urlArguments ? "?$urlArguments" : "";
$url = self::getFullUrl($baseUrl, "me/drives" . $urlArguments);
$url = self::getFullUrl($baseUrl, "me/drives" . $urlArguments, $isVault);
return HttpRequestHelper::get($url, $user, $password, $headers, $body);
}
@@ -102,6 +102,7 @@ class HttpRequestHelper {
* than download it all up-front.
* @param int|null $timeout
* @param Client|null $client
* @param bool $allowRedirects
*
* @return ResponseInterface
* @throws GuzzleException
@@ -118,6 +119,7 @@ class HttpRequestHelper {
bool $stream = false,
?int $timeout = 0,
?Client $client = null,
?bool $allowRedirects = false,
): ResponseInterface {
if ($client === null) {
$client = self::createClient(
@@ -127,6 +129,7 @@ class HttpRequestHelper {
$cookies,
$stream,
$timeout,
$allowRedirects,
);
}
@@ -197,6 +200,7 @@ class HttpRequestHelper {
* @param CookieJar|null $cookies
* @param bool $stream Set to true to stream a response rather
* than download it all up-front.
* @param bool $allowRedirects
* @param int|null $timeout
* @param Client|null $client
* @param bool|null $isGivenStep
@@ -215,6 +219,7 @@ class HttpRequestHelper {
?array $config = null,
?CookieJar $cookies = null,
bool $stream = false,
?bool $allowRedirects = false,
?int $timeout = 0,
?Client $client = null,
?bool $isGivenStep = false,
@@ -241,6 +246,7 @@ class HttpRequestHelper {
$stream,
$timeout,
$client,
$allowRedirects,
);
if ($response->getStatusCode() >= 400
@@ -378,6 +384,7 @@ class HttpRequestHelper {
* @param bool $stream Set to true to stream a response rather
* than download it all up-front.
* @param int|null $timeout
* @param bool $allowRedirects
*
* @return Client
*/
@@ -388,6 +395,7 @@ class HttpRequestHelper {
?CookieJar $cookies = null,
?bool $stream = false,
?int $timeout = 0,
?bool $allowRedirects = false,
): Client {
$options = [];
if ($user !== null) {
@@ -402,6 +410,7 @@ class HttpRequestHelper {
$options['stream'] = $stream;
$options['verify'] = false;
$options['timeout'] = $timeout ?: self::getRequestTimeout();
$options['allow_redirects'] = $allowRedirects;
return new Client($options);
}
@@ -459,6 +468,7 @@ class HttpRequestHelper {
* @param array|null $config
* @param CookieJar|null $cookies
* @param boolean $stream
* @param boolean $allowRedirects
*
* @return ResponseInterface
* @throws GuzzleException
@@ -473,6 +483,7 @@ class HttpRequestHelper {
?array $config = null,
?CookieJar $cookies = null,
?bool $stream = false,
?bool $allowRedirects = false,
): ResponseInterface {
return self::sendRequest(
$url,
@@ -484,6 +495,7 @@ class HttpRequestHelper {
$config,
$cookies,
$stream,
$allowRedirects,
);
}
@@ -0,0 +1,445 @@
<?php declare(strict_types=1);
/**
* ownCloud
*
* @author Prajwol Amatya <prajwol@jankaritech.com>
* @copyright Copyright (c) 2022 Prajwol Amatya prajwol@jankaritech.com
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License,
* as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace TestHelpers;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use InvalidArgumentException;
use JsonException;
use Psr\Http\Message\ResponseInterface;
/**
* A helper class for Keycloak admin API requests.
*/
class KeycloakHelper {
private const OCIS_KEYCLOAK_USER_ROLES = [
'Admin' => 'ocisAdmin',
'Space Admin' => 'ocisSpaceAdmin',
'User' => 'ocisUser',
'User Light' => 'ocisGuest',
];
private const OCIS_KEYCLOAK_USER_ROLE_IDS = [
'ocisAdmin' => '0bb40fa2-4490-4687-9159-b1d27ec7423a',
'ocisSpaceAdmin' => 'bd5f5012-48bb-4ea4-bfe6-0623e3ca0552',
'ocisUser' => '8c79ff81-c256-48fd-b0b9-795c7941eedf',
'ocisGuest' => '7eedfa6d-a2d9-4296-b6db-e75e4e9c0963',
'offline_access' => 'e2145b30-bf6f-49fb-af3f-1b40168bfcef',
];
private static ?string $adminAccessToken = null;
/**
* @return bool
*/
public static function isTestingWithKeycloak(): bool {
return (\getenv('KEYCLOAK') === "true");
}
/**
* @return string
*/
public static function getKeycloakUrl(): string {
$keycloakUrl = \getenv('KC_URL');
if ($keycloakUrl !== false && $keycloakUrl !== '') {
return $keycloakUrl;
}
return 'https://keycloak.owncloud.test';
}
/**
* @param string $accessToken
*
* @return void
*/
public static function setAdminAccessToken(string $accessToken): void {
self::$adminAccessToken = $accessToken;
}
/**
* Reset the cached admin access token
*
* @return void
*/
public static function resetAdminAccessToken(): void {
self::$adminAccessToken = null;
}
/**
* @return string
* @throws GuzzleException
*/
public static function getAdminAccessToken(): string {
if (self::$adminAccessToken === null) {
self::setAdminAccessToken(self::generateAdminAccessToken());
}
return (string)self::$adminAccessToken;
}
/**
* @param string $roleName
*
* @return array
*/
private static function getRealmRole(string $roleName): array {
$roleId = self::OCIS_KEYCLOAK_USER_ROLE_IDS[$roleName]
?? throw new InvalidArgumentException("Unknown Keycloak role: {$roleName}");
return [
'id' => $roleId,
'name' => $roleName,
];
}
/**
* @param string $username
* @param string $password
* @param string|null $email
* @param string|null $displayName
*
* @return ResponseInterface
* @throws Exception
* @throws GuzzleException
*/
public static function createUser(
string $username,
string $password,
?string $email = null,
?string $displayName = null,
): ResponseInterface {
$accessToken = self::getAdminAccessToken();
$url = self::getKeycloakUrl() . '/admin/realms/oCIS/users';
return HttpRequestHelper::post(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json',
],
self::prepareCreateUserPayload($username, $password, $email, $displayName),
);
}
/**
* @param string $uuid
* @param string $role
*
* @return ResponseInterface
* @throws GuzzleException
* @throws JsonException
*/
public static function assignRole(
string $uuid,
string $role,
): ResponseInterface {
$url = self::getKeycloakUrl() . "/admin/realms/oCIS/users/" . $uuid . "/role-mappings/realm";
$ocisRole = self::OCIS_KEYCLOAK_USER_ROLES[$role]
?? throw new InvalidArgumentException("Unknown oCIS role: {$role}");
$body = [
self::getRealmRole($ocisRole),
self::getRealmRole('offline_access'),
];
return HttpRequestHelper::post(
$url,
null,
null,
[
"Content-Type" => "application/json",
"Authorization" => "Bearer " . self::getAdminAccessToken(),
],
json_encode($body, JSON_THROW_ON_ERROR),
);
}
/**
* @return string
* @throws Exception
* @throws GuzzleException
*/
private static function generateAdminAccessToken(): string {
$url = self::getKeycloakUrl()
. '/realms/master/protocol/openid-connect/token';
$response = HttpRequestHelper::post(
$url,
null,
null,
['Content-Type' => 'application/x-www-form-urlencoded'],
[
'client_id' => 'admin-cli',
'username' => 'admin',
'password' => 'admin',
'grant_type' => 'password',
],
);
if ($response->getStatusCode() >= 400) {
throw new Exception(
__METHOD__
. ' failed to get Keycloak admin access token, status '
. $response->getStatusCode()
. ', response '
. (string)$response->getBody(),
);
}
$decodedResponse = HttpRequestHelper::getJsonDecodedResponseBodyContent($response);
if (!isset($decodedResponse->access_token)) {
throw new Exception(__METHOD__ . ' could not find access_token in Keycloak token response');
}
return (string)$decodedResponse->access_token;
}
/**
* @param string $username
* @param string $password
* @param string|null $email
* @param string|null $displayName
*
* @return string
* @throws JsonException
*/
private static function prepareCreateUserPayload(
string $username,
string $password,
?string $email = null,
?string $displayName = null,
): string {
$firstName = $username;
$lastName = '';
if ($displayName !== null && \trim($displayName) !== '') {
$nameParts = \preg_split('/\s+/', \trim($displayName), 2);
if ($nameParts !== false && isset($nameParts[0])) {
$firstName = $nameParts[0];
}
if ($nameParts !== false && isset($nameParts[1])) {
$lastName = $nameParts[1];
}
}
$payload = [
'username' => $username,
'credentials' => [[
'value' => $password,
'type' => 'password',
]],
'firstName' => $firstName,
'lastName' => $lastName,
'emailVerified' => true,
'enabled' => true,
];
if ($email !== null) {
$payload['email'] = $email;
}
return \json_encode($payload, JSON_THROW_ON_ERROR);
}
/**
* @return array
* @throws GuzzleException
*/
public static function getAuthorizationEndPoint(): array {
$loginParams = [
'client_id' => 'web',
'redirect_uri' => OcisHelper::getServerUrl() . '/oidc-callback.html',
'response_mode' => 'query',
'response_type' => 'code',
'scope' => 'openid profile email acr',
];
$queryString = \http_build_query($loginParams);
$authUrl = self::getKeycloakUrl() . "/realms/oCIS/protocol/openid-connect/auth?" . $queryString;
$response = HttpRequestHelper::get(
$authUrl,
);
$cookie = $response->getHeader("Set-Cookie")[0];
$htmlData = $response->getBody()->getContents();
if (!preg_match('/action="([^"]+)"/i', $htmlData, $match)) {
throw new Exception('No authorization url found in the HTML response body.');
}
$authorizationUrl = $match[1];
return [$authorizationUrl, $cookie];
}
/**
* @param array $user
* @param string $authorizationUrl
* @param string $cookie
*
* @return string
* @throws GuzzleException
*/
public static function getCode(array $user, string $authorizationUrl, string $cookie): string {
$authCodeResponse = HttpRequestHelper::post(
$authorizationUrl,
null,
null,
[
'Cookie' => $cookie,
],
[
'username' => $user['actualUsername'],
'password' => $user['password'],
],
);
$locationHeader = $authCodeResponse->getHeader('Location');
$queryString = parse_url($locationHeader[0], PHP_URL_QUERY);
parse_str($queryString, $urlParams);
return $urlParams['code'];
}
/**
* @param string $authorizationCode
*
* @return ResponseInterface
* @throws GuzzleException
* @throws Exception
*/
public static function getToken(string $authorizationCode): ResponseInterface {
$url = self::getKeycloakUrl() . '/realms/oCIS/protocol/openid-connect/token';
$tokenResponse = HttpRequestHelper::post(
$url,
null,
null,
null,
[
'client_id' => 'web',
'code' => $authorizationCode,
'redirect_uri' => OcisHelper::getServerUrl() . '/oidc-callback.html',
'grant_type' => 'authorization_code',
],
);
if ($tokenResponse->getStatusCode() !== 200) {
throw new Exception(
'Failed to retrieve token: Expected status code to be 200 but received ' .
$tokenResponse->getStatusCode() .
'.\nMessage: ' .
$tokenResponse->getBody()->getContents(),
);
}
return $tokenResponse;
}
/**
* @param array $user
*
* @return array
* @throws GuzzleException
* @throws JsonException
*/
public static function setAccessTokenForKeycloakOcisUser(array $user): array {
[$authorizationUrl, $cookie] = self::getAuthorizationEndPoint();
$authorizationCode = self::getCode($user, $authorizationUrl, $cookie);
$tokenResponse = self::getToken($authorizationCode);
return json_decode($tokenResponse->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
}
/**
* @return array
* @throws GuzzleException
* @throws JsonException
* @throws Exception
*/
public static function getRealm(): array {
$url = self::getKeycloakUrl() . '/admin/realms/oCIS';
$response = HttpRequestHelper::get(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
],
);
if ($response->getStatusCode() !== 200) {
throw new Exception("Failed to get realm roles.");
}
return json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
}
/**
* @param string $key
* @param string $value
*
* @return ResponseInterface
* @throws GuzzleException
* @throws JsonException
*/
public static function updateRealmAttribute(string $key, string $value): ResponseInterface {
$realm = self::getRealm();
$attributes = $realm['attributes'] ?? [];
$attributes[$key] = $value;
$url = self::getKeycloakUrl() . '/admin/realms/oCIS';
return HttpRequestHelper::put(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
json_encode(['attributes' => $attributes], JSON_THROW_ON_ERROR),
);
}
/**
* @param string $key
*
* @return ResponseInterface
* @throws GuzzleException
* @throws JsonException
*/
public static function deleteRealmAttribute(string $key): ResponseInterface {
$realm = self::getRealm();
$attributes = $realm['attributes'] ?? [];
unset($attributes[$key]);
$url = self::getKeycloakUrl() . '/admin/realms/oCIS';
return HttpRequestHelper::put(
$url,
null,
null,
[
'Authorization' => 'Bearer ' . self::getAdminAccessToken(),
'Content-Type' => 'application/json',
],
json_encode(['attributes' => $attributes], JSON_THROW_ON_ERROR),
);
}
/**
* @param string $uuid
*
* @return ResponseInterface
* @throws GuzzleException
*/
public static function deleteKeycloakUser(string $uuid): ResponseInterface {
$url = self::getKeycloakUrl() . '/admin/realms/oCIS/users/' . $uuid;
return HttpRequestHelper::delete(
$url,
null,
null,
[
"Authorization" => "Bearer " . self::getAdminAccessToken(),
],
);
}
}
+18 -10
View File
@@ -493,8 +493,9 @@ class WebDavHelper {
* fetches personal space id for provided user
*
* @param string $baseUrl
* @param string $user
* @param string $password
* @param string|null $user
* @param string|null $password
* @param array|null $headers
*
* @return string
* @throws GuzzleException
@@ -502,8 +503,9 @@ class WebDavHelper {
*/
public static function getPersonalSpaceIdForUser(
string $baseUrl,
string $user,
string $password,
?string $user = null,
?string $password = null,
?array $headers = [],
): string {
if (\array_key_exists($user, self::$spacesIdRef) && \array_key_exists("personal", self::$spacesIdRef[$user])) {
return self::$spacesIdRef[$user]["personal"];
@@ -511,7 +513,7 @@ class WebDavHelper {
$personalSpaceId = '';
if (!OcisHelper::isTestingOnReva()) {
$response = GraphHelper::getMySpaces($baseUrl, $user, $password, '');
$response = GraphHelper::getMySpaces($baseUrl, $user, $password, '', [], $headers);
Assert::assertEquals(200, $response->getStatusCode(), "Cannot list drives for user '$user'");
$drives = HttpRequestHelper::getJsonDecodedResponseBodyContent($response);
@@ -564,18 +566,21 @@ class WebDavHelper {
* In case of any exception, it returns a fake space ID
*
* @param string $baseUrl
* @param string $user
* @param string $password
* @param string|null $user
* @param string|null $password
* @param array|null $headers
*
* @return string
* @throws Exception|GuzzleException
*/
public static function getPersonalSpaceIdForUserOrFakeIfNotFound(
string $baseUrl,
string $user,
string $password,
?string $user = null,
?string $password = null,
?array $headers = [],
): string {
if (\str_starts_with($user, "non-exist") || \str_starts_with($user, "nonexist")) {
// only fake for non-existent users
if ($user !== null && (\str_starts_with($user, "non-exist") || \str_starts_with($user, "nonexist"))) {
return self::generateUUIDv4();
}
@@ -583,6 +588,7 @@ class WebDavHelper {
$baseUrl,
$user,
$password,
$headers,
);
}
@@ -660,6 +666,7 @@ class WebDavHelper {
$baseUrl,
$user,
$password,
$headers,
);
}
}
@@ -732,6 +739,7 @@ class WebDavHelper {
$config,
null,
$stream,
false,
$timeout,
$client,
$isGivenStep,
@@ -0,0 +1,131 @@
<?php declare(strict_types=1);
/**
* ownCloud
*
* @author Prajwol Amatya <prajwol@jankaritech.com>
* @copyright Copyright (c) 2022 Prajwol Amatya prajwol@jankaritech.com
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License,
* as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace TestHelpers;
require __DIR__ . '/../../../vendor-php/autoload.php';
use Exception;
use Playwright\Playwright;
use Zxing\QrReader;
use OTPHP\TOTP;
/**
* A helper class for setting up user and store user access token using web UI
*/
class WebUIHelper {
private static int $defaultTimeout = 5000;
private static string $keycloakHeader = '#kc-header';
private static string $usernameInput = '#username';
private static string $passwordInput = '#password';
private static string $loginButton = '#kc-login';
private static string $filesView = '#files-view';
private static string $modeSwitchButton = '#oc-topbar-mode-switch-btn';
private static string $vaultModeSelector
= "//button[contains(@class, 'oc-topbar-mode-switch-option')][.//span[text()='Vault']]";
private static string $qrCode = '#kc-totp-secret-qr-code';
private static string $totpInput = '#totp';
private static string $userLabel = '#userLabel';
private static string $saveTotpButton = '#saveTOTPBtn';
/**
* @param string $ocisUrl
* @param string $username
* @param string $password
*
* @return array
* @throws Exception
*/
public static function setUpUser(string $ocisUrl, string $username, string $password): array {
$context = Playwright::chromium(
[
'headless' => true,
'args' => ['--ignore-certificate-errors', '--no-sandbox'],
],
);
$screenshotPath = '/tmp/qr_' . uniqid() . '.png';
try {
$page = $context->newPage();
$page->goto($ocisUrl, ['waitUntil' => 'networkidle']);
$page->waitForSelector(self::$keycloakHeader, ['timeout' => self::$defaultTimeout]);
$page->locator(self::$usernameInput)->fill($username);
$page->locator(self::$passwordInput)->fill($password);
$page->locator(self::$loginButton)->click();
$page->waitForSelector(self::$filesView, ['timeout' => self::$defaultTimeout]);
// change to vault mode
$page->locator(self::$modeSwitchButton)->click();
$page->locator(self::$vaultModeSelector)->click();
$page->waitForSelector(self::$qrCode, ['timeout' => self::$defaultTimeout]);
$qrLocator = $page->locator(self::$qrCode);
// setup mfa
$qrLocator->screenshot($screenshotPath);
if (!file_exists($screenshotPath)) {
throw new Exception("Failed to save QR code screenshot to: " . $screenshotPath);
}
$otp = self::extractOtpFromQr($screenshotPath);
$page->locator(self::$totpInput)->fill((string)$otp);
$page->locator(self::$userLabel)->fill('test');
$page->locator(self::$saveTotpButton)->click();
$page->waitForSelector(self::$filesView, ['timeout' => self::$defaultTimeout]);
return $context->storageState();
} catch (\Exception $e) {
throw new Exception("Login failed for user '$username': " . $e->getMessage(), 0, $e);
} finally {
if (file_exists($screenshotPath)) {
unlink($screenshotPath);
}
$context->close();
}
}
/**
* @param string $imagePath
*
* @return string
* @throws Exception
*/
public static function extractOtpFromQr(string $imagePath): string {
$qrReader = new QrReader($imagePath);
$qrData = $qrReader->text();
if (empty($qrData)) {
throw new Exception("Could not decode QR code from image: " . $imagePath);
}
$parsedUrl = parse_url($qrData);
if (!isset($parsedUrl['query'])) {
throw new Exception("QR code data does not contain a valid otpauth URL: " . $qrData);
}
parse_str($parsedUrl['query'], $queryParams);
$secret = $queryParams['secret'] ?? null;
if ($secret === null) {
throw new Exception("No 'secret' parameter found in QR code URL: " . $qrData);
}
$totp = TOTP::createFromSecret($secret);
return $totp->now();
}
}
@@ -60,20 +60,33 @@ class CapabilitiesContext implements Context {
*
* @param string $username
* @param boolean $formatJson // if true then formats the response in json
* @param boolean $vaultMode
*
* @return ResponseInterface
* @throws GuzzleException
* @throws JsonException
*/
public function userGetsCapabilities(string $username, ?bool $formatJson = false): ResponseInterface {
public function userGetsCapabilities(
string $username,
?bool $formatJson = false,
?bool $vaultMode = false,
): ResponseInterface {
$user = $this->featureContext->getActualUsername($username);
$password = $this->featureContext->getPasswordForUser($user);
$queryParams = [];
if ($formatJson) {
$queryParams['format'] = 'json';
}
if ($vaultMode) {
$queryParams['vault'] = 'true';
}
$queryString = $queryParams ? '?' . http_build_query($queryParams) : '';
return OcsApiHelper::sendRequest(
$this->featureContext->getBaseUrl(),
$user,
$password,
'GET',
'/cloud/capabilities' . ($formatJson ? '?format=json' : ''),
'/cloud/capabilities' . $queryString,
[],
$this->featureContext->getOcsApiVersion(),
);
@@ -134,17 +147,19 @@ class CapabilitiesContext implements Context {
}
/**
* @When user :username retrieves the capabilities using the capabilities API
* @When /^user "([^"]*)" retrieves the(| vault mode)? capabilities using the capabilities API$/
*
* @param string $username
* @param string $vaultMode
*
* @return void
* @throws GuzzleException
* @throws JsonException
*/
public function userRetrievesCapabilities(string $username): void {
public function userRetrievesCapabilities(string $username, string $vaultMode): void {
$user = $this->featureContext->getActualUsername($username);
$this->featureContext->setResponse($this->userGetsCapabilities($user, true));
$vaultMode = trim($vaultMode) === "vault mode";
$this->featureContext->setResponse($this->userGetsCapabilities($user, true, $vaultMode));
}
/**
+14 -4
View File
@@ -2046,10 +2046,20 @@ class FeatureContext extends BehatVariablesContext {
if ($response === null) {
$response = $this->getResponse();
}
return \json_decode(
(string)$response->getBody(),
true,
);
$body = $response->getBody();
$body->rewind();
$bodyContent = $body->getContents();
if ($bodyContent === '') {
return [];
}
$decodedResponse = \json_decode($bodyContent, true);
if (!\is_array($decodedResponse)) {
return [];
}
return $decodedResponse;
}
/**
+39 -19
View File
@@ -19,6 +19,7 @@ use TestHelpers\GraphHelper;
use TestHelpers\WebDavHelper;
use TestHelpers\HttpRequestHelper;
use TestHelpers\BehatHelper;
use TestHelpers\KeycloakHelper;
require_once 'bootstrap.php';
@@ -293,11 +294,21 @@ class GraphContext implements Context {
*/
public function adminDeletesUserUsingTheGraphApi(string $user, ?string $byUser = null): ResponseInterface {
$credentials = $this->getAdminOrUserCredentials($byUser);
$adminUser = $credentials["username"];
$adminPass = $credentials["password"];
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($adminUser)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
$adminUser = null;
$adminPass = null;
}
$response = GraphHelper::deleteUser(
$this->featureContext->getBaseUrl(),
$credentials["username"],
$credentials["password"],
$user,
$adminUser,
$adminPass,
$headers,
);
if ($response->getStatusCode() === 204) {
$this->featureContext->rememberThatUserIsNotExpectedToExist($user);
@@ -1805,25 +1816,34 @@ class GraphContext implements Context {
*/
public function theAdministratorHasGivenTheRoleUsingTheGraphApi(string $role, string $user): void {
$userId = $this->featureContext->getAttributeOfCreatedUser($user, 'id') ?: $user;
if (KeycloakHelper::isTestingWithKeycloak()) {
$response = KeycloakHelper::assignrole($userId, $role);
Assert::assertEquals(
204,
$response->getStatusCode(),
__METHOD__
. "\nExpected status code '204' but got '" . $response->getStatusCode() . "'",
);
} else {
if (empty($this->appEntity)) {
$this->setApplicationEntity();
}
if (empty($this->appEntity)) {
$this->setApplicationEntity();
$response = GraphHelper::assignRole(
$this->featureContext->getBaseUrl(),
$this->featureContext->getAdminUsername(),
$this->featureContext->getAdminPassword(),
$this->appEntity["appRoles"][$role],
$this->appEntity["id"],
$userId,
);
Assert::assertEquals(
201,
$response->getStatusCode(),
__METHOD__
. "\nExpected status code '200' but got '" . $response->getStatusCode() . "'",
);
}
$response = GraphHelper::assignRole(
$this->featureContext->getBaseUrl(),
$this->featureContext->getAdminUsername(),
$this->featureContext->getAdminPassword(),
$this->appEntity["appRoles"][$role],
$this->appEntity["id"],
$userId,
);
Assert::assertEquals(
201,
$response->getStatusCode(),
__METHOD__
. "\nExpected status code '200' but got '" . $response->getStatusCode() . "'",
);
}
/**
@@ -23,6 +23,9 @@
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\TableNode;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
use TestHelpers\HttpRequestHelper;
use TestHelpers\KeycloakHelper;
use TestHelpers\OcisConfigHelper;
use TestHelpers\GraphHelper;
use PHPUnit\Framework\Assert;
@@ -110,11 +113,9 @@ class OcisConfigContext implements Context {
$response = OcisConfigHelper::reConfigureOcis($envs);
}
$resBody = $response->getBody()->getContents();
Assert::assertEquals(
200,
$response->getStatusCode(),
"Failed to set config $configVariable=$configValue. Response: $resBody",
$this->assertOcisRestarted(
$response,
"Failed to set config $configVariable=$configValue.",
);
}
@@ -346,11 +347,66 @@ class OcisConfigContext implements Context {
*/
public function rollbackOcis(): void {
$response = OcisConfigHelper::rollbackOcis();
$resBody = $response->getBody()->getContents();
$this->assertOcisRestarted(
$response,
"Failed to rollback ocis server. Check if oCIS is started with ociswrapper.",
);
}
/**
* Asserts that an oCIS restart triggered by ociswrapper succeeded.
* In vault mode the wrapper's admin health-check uses basic-auth which is
* disabled (OIDC role assignment only), so the wrapper always returns HTTP 500
* even after a successful restart. When Keycloak/vault mode is detected we
* poll the unauthenticated proxy debug readyz endpoint instead of failing.
*
* @param ResponseInterface $response
* @param string $errorMessage
*
* @return void
*/
private function assertOcisRestarted(ResponseInterface $response, string $errorMessage): void {
$statusCode = $response->getStatusCode();
if ($statusCode === 200) {
return;
}
if (KeycloakHelper::isTestingWithKeycloak()) {
$this->waitForOcisProxyReady();
return;
}
Assert::assertEquals(
200,
$response->getStatusCode(),
"Failed to rollback ocis server. Check if oCIS is started with ociswrapper. Response: $resBody",
$statusCode,
$errorMessage . " Response: " . $response->getBody()->getContents(),
);
}
/**
* Poll the unauthenticated proxy debug readyz endpoint until oCIS is ready.
* Used in vault/Keycloak mode where basic-auth health checks are unavailable.
*
* @param int $timeoutSeconds
*
* @return void
* @throws GuzzleException
*/
private function waitForOcisProxyReady(int $timeoutSeconds = 60): void {
$readyzUrl = 'http://localhost:9205/readyz';
$deadline = time() + $timeoutSeconds;
while (time() < $deadline) {
try {
$response = HttpRequestHelper::get($readyzUrl);
if ($response->getStatusCode() === 200) {
return;
}
echo "oCIS not ready yet. Retrying in 1s...\n";
} catch (\Exception $e) {
throw new Exception("oCIS not ready. Error: $e");
}
sleep(1);
}
throw new \RuntimeException(
"Timed out after {$timeoutSeconds}s waiting for oCIS proxy readyz at {$readyzUrl}",
);
}
+165 -29
View File
@@ -29,8 +29,10 @@ use TestHelpers\HttpRequestHelper;
use TestHelpers\OcisHelper;
use TestHelpers\WebDavHelper;
use TestHelpers\GraphHelper;
use TestHelpers\KeycloakHelper;
use Laminas\Ldap\Exception\LdapException;
use Laminas\Ldap\Ldap;
use TestHelpers\WebUIHelper;
/**
* Functions for provisioning of users and groups
@@ -44,6 +46,38 @@ trait Provisioning {
private array $startingGroups = [];
private array $createdRemoteGroups = [];
private array $createdGroups = [];
private array $userTokens = [];
/**
* @param array $user
* @param mixed $tokenData
*
* @return void
*/
public function setOcisUserToken(array $user, mixed $tokenData): void {
$userId = $user['actualUsername'] ?? null;
if (\is_object($tokenData)) {
$tokenData = (array) $tokenData;
}
$this->userTokens[$userId] = [
'user' => $user,
'token' => [
'userid' => $userId,
'accessToken' => $tokenData['access_token'],
'refreshToken' => $tokenData['refresh_token'],
],
];
}
/**
* @param string $userId
*
* @return array
*/
public function getOcisUserToken(string $userId): array {
return $this->userTokens[$userId];
}
/**
* Check if this is the admin group. That group is always a local group in
@@ -524,6 +558,97 @@ trait Provisioning {
}
}
/**
* @param array $userAttributes
*
* @return void
* @throws GuzzleException
* @throws JsonException
*/
public function createKeycloakUser(array $userAttributes): void {
$response = KeycloakHelper::createUser(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['email'],
$userAttributes['displayName'],
);
if ($response->getStatusCode() !== 201) {
$responseBody = (string)$response->getBody();
throw new Exception(
__METHOD__ .
" Unexpected failure when creating the user in keycloak '" .
$userAttributes['userid'] . "'" .
"\nHTTP status " . $response->getStatusCode() .
"\nKeycloak response " . $responseBody,
);
}
$locationHeader = explode("/", $response->getHeader("Location")[0]);
$uuid = end($locationHeader);
$this->addUserToCreatedUsersList(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['displayName'],
$userAttributes['email'],
$uuid,
);
// assign default ocisUser role to newly created user
$res = KeycloakHelper::assignRole($uuid, "User");
Assert::assertEquals(
204,
$res->getStatusCode(),
__METHOD__ . " failed to assign realm role to user '" .
$userAttributes['userid'] . "'" .
"\nHTTP status " . $res->getStatusCode() .
"\nKeycloak response " . (string)$res->getBody(),
);
}
/**
* @BeforeScenario
*
* @return void
* @throws GuzzleException
* @throws Exception
*/
public function setAccessTokenForAdmin(): void {
if (!KeycloakHelper::isTestingWithKeycloak()) {
return;
}
KeycloakHelper::resetAdminAccessToken();
$adminUser = [
"password" => "admin",
"displayname" => "Admin Admin",
"email" => "admin@example.org",
"actualUsername" => "admin",
];
$tokenData = KeycloakHelper::setAccessTokenForKeycloakOcisUser($adminUser);
$this->setOcisUserToken($adminUser, $tokenData);
}
/**
* Sets up Keycloak user in oCIS
* User is logged in via web UI and user access token is extracted
*
* @Given user :user has logged in via web UI
*
* @param string $user
*
* @return void
* @throws Exception
*/
public function userHasLoggedInViaWebUI(string $user): void {
$createdUsers = $this->getCreatedUsers();
$user = $createdUsers[strtolower($user)];
$state = WebUIHelper::setUpUser(
$this->getBaseUrl(),
$user["actualUsername"],
$user["password"],
);
$stateData = \json_decode($state['origins'][0]['localStorage'][2]['value']);
$this->setOcisUserToken($user, $stateData);
}
/**
* Creates multiple users
*
@@ -556,6 +681,8 @@ trait Provisioning {
foreach ($users as $userAttributes) {
if ($this->isTestingWithLdap()) {
$this->createLdapUser($userAttributes);
} elseif (KeycloakHelper::isTestingWithKeycloak()) {
$this->createKeycloakUser($userAttributes);
} else {
$attributesToCreateUser['userid'] = $userAttributes['userid'];
$attributesToCreateUser['password'] = $userAttributes['password'];
@@ -588,7 +715,7 @@ trait Provisioning {
}
$exceptionToThrow = null;
if (!$this->isTestingWithLdap()) {
if (!$this->isTestingWithLdap() && !KeycloakHelper::isTestingWithKeycloak()) {
$results = HttpRequestHelper::sendBatchRequest($requests, $client);
// Check all requests to inspect failures.
foreach ($results as $key => $e) {
@@ -611,38 +738,40 @@ trait Provisioning {
// Create requests for setting displayname and email for the newly created users.
// These values cannot be set while creating the user, so we have to edit the newly created user to set these values.
foreach ($users as $userAttributes) {
if (!$this->isTestingWithLdap()) {
// for graph api, we need to save the user id to be able to add it in some group
// can be fetched with the "onPremisesSamAccountName" i.e. userid
$response = $this->graphContext->adminHasRetrievedUserUsingTheGraphApi($userAttributes['userid']);
$userAttributes['id'] = $this->getJsonDecodedResponse($response)['id'];
} else {
$userAttributes['id'] = null;
if (!KeycloakHelper::isTestingWithKeycloak()) {
foreach ($users as $userAttributes) {
if (!$this->isTestingWithLdap()) {
// for graph api, we need to save the user id to be able to add it in some group
// can be fetched with the "onPremisesSamAccountName" i.e. userid
$response = $this->graphContext->adminHasRetrievedUserUsingTheGraphApi($userAttributes['userid']);
$userAttributes['id'] = $this->getJsonDecodedResponse($response)['id'];
} else {
$userAttributes['id'] = null;
}
$this->addUserToCreatedUsersList(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['displayName'],
$userAttributes['email'],
$userAttributes['id'],
);
}
$this->addUserToCreatedUsersList(
$userAttributes['userid'],
$userAttributes['password'],
$userAttributes['displayName'],
$userAttributes['email'],
$userAttributes['id'],
);
}
if (isset($exceptionToThrow)) {
throw $exceptionToThrow;
}
if (isset($exceptionToThrow)) {
throw $exceptionToThrow;
}
foreach ($users as $user) {
Assert::assertTrue(
$this->userExists($user["userid"]),
"User '" . $user["userid"] . "' should exist but does not exist",
);
}
if ($initialize) {
foreach ($users as $user) {
$this->initializeUser($user['userid'], $user['password']);
Assert::assertTrue(
$this->userExists($user["userid"]),
"User '" . $user["userid"] . "' should exist but does not exist",
);
}
if ($initialize) {
foreach ($users as $user) {
$this->initializeUser($user['userid'], $user['password']);
}
}
}
}
@@ -1944,6 +2073,7 @@ trait Provisioning {
*
* @return void
* @throws Exception
* @throws GuzzleException
*/
public function cleanupDatabaseUsers(): void {
$previousServer = $this->currentServer;
@@ -1961,6 +2091,12 @@ trait Provisioning {
$this->userExists($user),
"User '$user' should not exist but does exist",
);
// delete user from keycloak
if (KeycloakHelper::isTestingWithKeycloak()) {
$res = KeycloakHelper::deleteKeycloakUser($userData['id']);
$this->theHTTPStatusCodeShouldBe(204, "Failed to delete keycloak user '$user'", $res);
}
}
$this->usingServer($previousServer);
}
+82 -23
View File
@@ -34,6 +34,7 @@ use TestHelpers\WebDavHelper;
use TestHelpers\GraphHelper;
use TestHelpers\OcisHelper;
use TestHelpers\BehatHelper;
use TestHelpers\KeycloakHelper;
require_once 'bootstrap.php';
@@ -132,13 +133,15 @@ class SpacesContext implements Context {
/**
* @param string $user
* @param object $space
* @param boolean $isVault
*
* @return void
*/
public function addPersonalSpaceForUser(string $user, object $space): void {
public function addPersonalSpaceForUser(string $user, object $space, bool $isVault = false): void {
$spaceName = $this->featureContext->getUserDisplayName($user);
$this->personalSpaces[$spaceName] = $space;
$this->personalSpaces[$spaceName]->serverType = $this->featureContext->getCurrentServer();
$this->personalSpaces[$spaceName]->isVault = $isVault;
}
/**
@@ -189,11 +192,12 @@ class SpacesContext implements Context {
/**
* @param string $user
* @param string $spaceName
* @param boolean $isVault
*
* @return array
* @throws GuzzleException
*/
public function getSpaceByName(string $user, string $spaceName): array {
public function getSpaceByName(string $user, string $spaceName, bool $isVault = false): array {
$password = $this->featureContext->getPasswordForUser($user);
$createdSpaces = $this->getCreatedSpaces();
$personalSpaces = $this->getPersonalSpaces();
@@ -205,10 +209,16 @@ class SpacesContext implements Context {
if (isset($allSpaces[$spaceName])
&& $allSpaces[$spaceName]->serverType === $this->featureContext->getCurrentServer()
&& (!isset($allSpaces[$spaceName]->isVault) || $allSpaces[$spaceName]->isVault === $isVault)
) {
return json_decode(json_encode($allSpaces[$spaceName]), true);
}
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
}
// Sometimes listing available spaces might not return newly created/shared spaces.
// So we try again until we find the space or we reach the max number of retries (i.e. 10)
$retried = 0;
@@ -216,9 +226,12 @@ class SpacesContext implements Context {
// list 'me/drives' as given user
$response = GraphHelper::getMySpaces(
$this->featureContext->getBaseUrl(),
$user,
$password,
KeycloakHelper::isTestingWithKeycloak() ? null : $user,
KeycloakHelper::isTestingWithKeycloak() ? null : $password,
"",
[],
$headers,
$isVault,
);
// NOTE: user can be created with empty password
// so if that's the case, the user won't be able to request using empty password
@@ -254,7 +267,7 @@ class SpacesContext implements Context {
if ($space->driveType === "project") {
$this->addToCreatedSpace($user, $space);
} elseif (!($space->name === "Shares" && $space->driveType === "virtual")) {
$this->addPersonalSpaceForUser($user, $space);
$this->addPersonalSpaceForUser($user, $space, $isVault);
}
break;
}
@@ -278,12 +291,13 @@ class SpacesContext implements Context {
*
* @param string $user
* @param string $spaceName
* @param boolean $isVault
*
* @return string
* @throws GuzzleException
*/
public function getSpaceIdByName(string $user, string $spaceName): string {
$space = $this->getSpaceByName($user, $spaceName);
public function getSpaceIdByName(string $user, string $spaceName, bool $isVault = false): string {
$space = $this->getSpaceByName($user, $spaceName, $isVault);
return $space["id"];
}
@@ -797,22 +811,38 @@ class SpacesContext implements Context {
* @param string $user
* @param string $spaceName
* @param string $foldersPath
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
*/
public function propfindSpace(string $user, string $spaceName, string $foldersPath = ''): ResponseInterface {
$spaceId = $this->getSpaceIdByName($user, $spaceName);
public function propfindSpace(
string $user,
string $spaceName,
string $foldersPath = '',
bool $isVault = false,
): ResponseInterface {
$spaceId = $this->getSpaceIdByName($user, $spaceName, $isVault);
$password = $this->featureContext->getPasswordForUser($user);
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
$user = null;
$password = null;
}
return WebDavHelper::propfind(
$this->featureContext->getBaseUrl(),
$user,
$this->featureContext->getPasswordForUser($user),
$password,
$foldersPath,
[],
null,
$spaceId,
'files',
WebDavHelper::DAV_VERSION_SPACES,
null,
$headers,
);
}
@@ -888,10 +918,11 @@ class SpacesContext implements Context {
}
/**
* @Then /^for user "([^"]*)" the space "([^"]*)" should (not|)\s?contain these (?:files|entries):$/
* @Then /^for user "([^"]*)" the space "([^"]*)"(| in vault)? should (not|)\s?contain these (?:files|entries):$/
*
* @param string $user
* @param string $spaceName
* @param string $isVault
* @param string $shouldOrNot (not|)
* @param TableNode $expectedFiles
*
@@ -902,11 +933,13 @@ class SpacesContext implements Context {
public function userTheSpaceShouldContainEntries(
string $user,
string $spaceName,
string $isVault,
string $shouldOrNot,
TableNode $expectedFiles,
): void {
$space = $this->getSpaceByName($user, $spaceName);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName));
$isVault = trim($isVault) === "in vault";
$space = $this->getSpaceByName($user, $spaceName, $isVault);
$this->featureContext->setResponse($this->propfindSpace($user, $spaceName, '', $isVault));
$this->featureContext->propfindResultShouldContainEntries(
$shouldOrNot,
$expectedFiles,
@@ -1275,11 +1308,12 @@ class SpacesContext implements Context {
}
/**
* @When /^user "([^"]*)" creates a (?:folder|subfolder) "([^"]*)" in space "([^"]*)" using the WebDav Api$/
* @When /^user "([^"]*)" creates a (?:folder|subfolder) "([^"]*)" in space "([^"]*)"(| in vault)? using the WebDav Api$/
*
* @param string $user
* @param string $folder
* @param string $spaceName
* @param string $isVault
*
* @return void
*
@@ -1289,13 +1323,15 @@ class SpacesContext implements Context {
string $user,
string $folder,
string $spaceName,
string $isVault,
): void {
$folder = \trim($folder, '/');
$exploded = explode('/', $folder);
$path = '';
$isVault = trim($isVault) === "in vault";
for ($i = 0; $i < \count($exploded); $i++) {
$path = $path . $exploded[$i] . '/';
$response = $this->createFolderInSpace($user, $path, $spaceName);
$response = $this->createFolderInSpace($user, $path, $spaceName, '', $isVault);
$this->featureContext->setResponse($response);
}
}
@@ -1344,11 +1380,12 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has created a (?:folder|subfolder) "([^"]*)" in space "([^"]*)"$/
* @Given /^user "([^"]*)" has created a (?:folder|subfolder) "([^"]*)" in space "([^"]*)"(| in vault)?$/
*
* @param string $user
* @param string $folder
* @param string $spaceName
* @param string $isVault
*
* @return void
*
@@ -1358,13 +1395,15 @@ class SpacesContext implements Context {
string $user,
string $folder,
string $spaceName,
string $isVault,
): void {
$folder = \trim($folder, '/');
$paths = explode('/', $folder);
$folderPath = '';
$isVault = trim($isVault) === "in vault";
foreach ($paths as $path) {
$folderPath .= "$path/";
$response = $this->createFolderInSpace($user, $folderPath, $spaceName);
$response = $this->createFolderInSpace($user, $folderPath, $spaceName, '', $isVault);
}
$this->featureContext->theHTTPStatusCodeShouldBe(
201,
@@ -1378,6 +1417,7 @@ class SpacesContext implements Context {
* @param string $folder
* @param string $spaceName
* @param string $ownerUser
* @param boolean $isVault
*
* @return ResponseInterface
*
@@ -1388,11 +1428,12 @@ class SpacesContext implements Context {
string $folder,
string $spaceName,
string $ownerUser = '',
bool $isVault = false,
): ResponseInterface {
if ($ownerUser === '') {
$ownerUser = $user;
}
$spaceId = $this->getSpaceIdByName($ownerUser, $spaceName);
$spaceId = $this->getSpaceIdByName($ownerUser, $spaceName, $isVault);
return $this->featureContext->createFolder($user, $folder, false, null, $spaceId);
}
@@ -1419,12 +1460,13 @@ class SpacesContext implements Context {
}
/**
* @When /^user "([^"]*)" uploads a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)" using the WebDAV API$/
* @When /^user "([^"]*)" uploads a file inside space "([^"]*)" with content "([^"]*)" to "([^"]*)"(| in vault)? using the WebDAV API$/
*
* @param string $user
* @param string $spaceName
* @param string $content
* @param string $destination
* @param string $isVault
*
* @return void
* @throws GuzzleException
@@ -1435,8 +1477,10 @@ class SpacesContext implements Context {
string $spaceName,
string $content,
string $destination,
string $isVault,
): void {
$spaceId = $this->getSpaceIdByName($user, $spaceName);
$isVault = trim($isVault) === "in vault";
$spaceId = $this->getSpaceIdByName($user, $spaceName, $isVault);
if ($spaceName === "Shares" && !\str_starts_with($destination, "Shares/")) {
$destination = "Shares/" . \ltrim($destination, "/");
}
@@ -1831,10 +1875,11 @@ class SpacesContext implements Context {
}
/**
* @Given /^user "([^"]*)" has created a space "([^"]*)" with the default quota using the Graph API$/
* @Given /^user "([^"]*)" has created a space "([^"]*)"(| in vault)? with the default quota using the Graph API$/
*
* @param string $user
* @param string $spaceName
* @param string $isVault
*
* @return void
*
@@ -1844,9 +1889,11 @@ class SpacesContext implements Context {
public function theUserHasCreatedASpaceByDefaultUsingTheGraphApi(
string $user,
string $spaceName,
string $isVault,
): void {
$space = ["name" => $spaceName];
$response = $this->createSpace($user, $space);
$isVault = trim($isVault) === "in vault";
$response = $this->createSpace($user, $space, $isVault);
$this->featureContext->theHTTPStatusCodeShouldBe(
201,
"Expected response status code should be 201 (Created)",
@@ -1859,6 +1906,7 @@ class SpacesContext implements Context {
/**
* @param string $user
* @param string $space
* @param boolean $isVault
*
* @return ResponseInterface
* @throws GuzzleException
@@ -1867,13 +1915,24 @@ class SpacesContext implements Context {
public function createSpace(
string $user,
array $space,
bool $isVault = false,
): ResponseInterface {
$body = json_encode($space, JSON_THROW_ON_ERROR);
$password = $this->featureContext->getPasswordForUser($user);
$headers = [];
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->featureContext->getOcisUserToken($user)["token"]["accessToken"];
$headers['Authorization'] = 'Bearer ' . $access_token;
$user = null;
$password = null;
}
return GraphHelper::createSpace(
$this->featureContext->getBaseUrl(),
$user,
$this->featureContext->getPasswordForUser($user),
$password,
$body,
$headers,
$isVault,
);
}
+124
View File
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
/**
* ownCloud
*
* @author Prajwol Amatya <prajwol@jankaritech.com>
* @copyright Copyright (c) 2026 Prajwol Amatya prajwol@jankaritech.com
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License,
* as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use GuzzleHttp\Exception\GuzzleException;
use JsonException;
use PHPUnit\Framework\Assert;
use TestHelpers\BehatHelper;
use TestHelpers\KeycloakHelper;
require_once 'bootstrap.php';
/**
* Context for ocis vault specific steps
*/
class VaultContext implements Context {
private FeatureContext $featureContext;
private array $originalRealmAttributes = [];
/**
* @BeforeScenario
*
* @param BeforeScenarioScope $scope
*
* @return void
*
* @throws Exception
*/
public function before(BeforeScenarioScope $scope): void {
// Get the environment
$environment = $scope->getEnvironment();
// Get all the contexts you need in this context
$this->featureContext = BehatHelper::getContext($scope, $environment, 'FeatureContext');
}
/**
* @Given the administrator has set the Keycloak realm attribute :key to :value
*
* @param string $key
* @param string $value
*
* @return void
* @throws GuzzleException
* @throws JsonException
*/
public function theAdministratorHasSetTheKeycloakRealmAttributeTo(string $key, string $value): void {
$realm = KeycloakHelper::getRealm();
$this->originalRealmAttributes[$key] = $realm['attributes'][$key] ?? null;
$response = KeycloakHelper::updateRealmAttribute($key, $value);
Assert::assertEquals(
204,
$response->getStatusCode(),
"Failed to update Keycloak realm attribute $key. Response: " . $response->getBody()->getContents(),
);
}
/**
* @AfterScenario @keycloak-config
*
* @return void
* @throws GuzzleException
* @throws JsonException
*/
public function restoreKeycloakRealmAttributes(): void {
foreach ($this->originalRealmAttributes as $key => $value) {
if ($value === null) {
KeycloakHelper::deleteRealmAttribute($key);
continue;
}
KeycloakHelper::updateRealmAttribute($key, $value);
}
$this->originalRealmAttributes = [];
}
/**
* @Then user :user should have acr value :acr
*
* @param string $user
* @param string $acr
*
* @return void
* @throws Exception
*/
public function userShouldHaveAcrValue(string $user, string $acr): void {
$accessToken = $this->featureContext->getOcisUserToken($user)['token']['accessToken'];
// Decode JWT token
$parts = explode('.', $accessToken);
if (\count($parts) !== 3) {
throw new Exception("Invalid JWT token format.");
}
$payload = $parts[1];
$decodedPayload = base64_decode(strtr($payload, '-_', '+/'), true);
$payloadArray = json_decode($decodedPayload, true);
$actualAcr = $payloadArray['acr'] ?? null;
Assert::assertEquals(
$acr,
$actualAcr,
"Expected acr value to be $acr but got $actualAcr",
);
}
}
+8
View File
@@ -31,6 +31,7 @@ use TestHelpers\WebDavHelper;
use TestHelpers\HttpRequestHelper;
use TestHelpers\Asserts\WebDav as WebDavAssert;
use TestHelpers\GraphHelper;
use TestHelpers\KeycloakHelper;
/**
* WebDav functions
@@ -310,6 +311,13 @@ trait WebDav {
$password = $this->getPasswordForUser($user);
}
if (KeycloakHelper::isTestingWithKeycloak()) {
$access_token = $this->getOcisUserToken($user)["token"]["accessToken"];
$headers["Authorization"] = "Bearer " . $access_token;
$user = null;
$password = null;
}
return WebDavHelper::makeDavRequest(
$this->getBaseUrl(),
$user,
+10
View File
@@ -487,6 +487,16 @@ default:
- AuthAppContext:
- OcisConfigContext:
apiVault:
paths:
- "%paths.base%/../features/apiVault"
context: *common_ldap_suite_context
contexts:
- FeatureContext: *common_feature_context_params
- VaultContext:
- OcisConfigContext:
- CapabilitiesContext:
cliCommands:
paths:
- "%paths.base%/../features/cliCommands"
@@ -0,0 +1,184 @@
Feature: vault
As a user
I want to store resource in vault storage
So that vault resources are isolated with regular drive storage
Background:
Given using spaces DAV path
And these users have been created with default attributes:
| username |
| Alice |
Scenario: user can create folders and files in personal space in vault
Given user "Alice" has logged in via web UI
When user "Alice" creates a folder "vaultFolder" in space "Personal" in vault using the WebDav Api
Then the HTTP status code should be "201"
When user "Alice" uploads a file inside space "Personal" with content "some content" to "vaultFile.txt" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| vaultFolder |
| vaultFile.txt |
Scenario: user can create folders and files in project space in vault
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has logged in via web UI
And user "Alice" has created a space "vault-space" in vault with the default quota using the Graph API
When user "Alice" creates a folder "vaultFolder" in space "vault-space" in vault using the WebDav Api
Then the HTTP status code should be "201"
When user "Alice" uploads a file inside space "vault-space" with content "some content" to "vaultFile.txt" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "vault-space" in vault should contain these entries:
| vaultFolder |
| vaultFile.txt |
Scenario: resources in drive and vault are isolated
Given user "Alice" has logged in via web UI
And user "Alice" has created a folder "driveFolder" in space "Personal"
And user "Alice" has uploaded a file inside space "Personal" with content "some content" to "driveFile.txt"
And user "Alice" has created a folder "vaultFolder" in space "Personal" in vault
When user "Alice" uploads a file inside space "Personal" with content "some content" to "vaultFile.txt" in vault using the WebDAV API
Then the HTTP status code should be "201"
And for user "Alice" the space "Personal" in vault should contain these entries:
| vaultFolder |
| vaultFile.txt |
And for user "Alice" the space "Personal" should contain these entries:
| driveFolder |
| driveFile.txt |
And for user "Alice" the space "Personal" in vault should not contain these entries:
| driveFolder |
| driveFile.txt |
And for user "Alice" the space "Personal" should not contain these entries:
| vaultFolder |
| vaultFile.txt |
@env-config @keycloak-config
Scenario: user can set custom auth level names
Given the administrator has set the Keycloak realm attribute "acr.loa.map" to '{"regular":"1","testing":"2"}'
And the config "OCIS_MFA_AUTH_LEVEL_NAMES" has been set to "testing"
And user "Alice" has logged in via web UI
When user "Alice" uploads a file inside space "Personal" with content "some content" to "vaultFile.txt" in vault using the WebDAV API
Then the HTTP status code should be "201"
And user "Alice" should have acr value "testing"
Scenario: check capabilities endpoint for vault
Given using OCS API version "2"
And user "Alice" has logged in via web UI
When user "Alice" retrieves the vault mode capabilities using the capabilities API
Then the OCS status code should be "200"
And the HTTP status code should be "200"
And the ocs JSON data of the response should match
"""
{
"type": "object",
"required": [ "capabilities" ],
"properties": {
"capabilities": {
"type": "object",
"required": [
"core",
"files",
"files_sharing",
"auth",
"vault"
],
"properties": {
"files_sharing": {
"type": "object",
"required": [
"api_enabled",
"default_permissions",
"public",
"resharing",
"federation",
"group_sharing",
"share_with_group_members_only",
"share_with_membership_groups_only",
"auto_accept_share",
"user_enumeration"
],
"properties": {
"federation": {
"type": "object",
"required": [
"outgoing",
"incoming"
],
"properties": {
"outgoing": {
"const": false
},
"incoming": {
"const": false
}
}
},
"public": {
"type": "object",
"required": [
"enabled",
"multiple",
"upload",
"supports_upload_only",
"send_mail",
"social_share"
],
"properties": {
"enabled": {
"const": false
}
}
}
}
},
"auth": {
"type": "object",
"required": [
"mfa"
],
"properties": {
"mfa": {
"type": "object",
"required": [
"enabled",
"levelnames"
],
"properties": {
"enabled": {
"const": true
},
"levelnames": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"const": "advanced"
}
}
}
}
}
},
"vault": {
"type": "object",
"required": [
"enabled",
"vault_storage_provider"
],
"properties": {
"enabled": {
"const": true
},
"vault_storage_provider": {
"pattern": "%uuidv4_pattern%"
}
}
}
}
}
}
}
"""
+179 -3
View File
@@ -25,6 +25,9 @@ EMAIL_SMTP_PORT = "1025"
EMAIL_PORT = "8025"
EMAIL_SMTP_SENDER = "ownCloud <noreply@example.com>"
KEYCLOAK_IMAGE = "quay.io/keycloak/keycloak:26.5.6"
POSTGRES_ALPINE_IMAGE = "postgres:alpine3.18"
LOCAL_API_TESTS = {
"contractAndLock": {
"suites": ["apiContract", "apiLocks"],
@@ -135,6 +138,37 @@ LOCAL_API_TESTS = {
"GATEWAY_GRPC_ADDR": "0.0.0.0:9142",
},
},
"vault": {
"suites": ["apiVault"],
"keycloakNeeded": True,
"vaultStorage": True,
"extraEnvironment": {
"KEYCLOAK": "true",
"KC_URL": "https://localhost:8443"
},
"extraServerEnvironment": {
"OCIS_ENABLE_VAULT_MODE": "true",
"FRONTEND_ENABLE_VAULT_MODE": "true",
"OCIS_MFA_ENABLED": "true",
"SETTINGS_GRPC_ADDR": "localhost:9191",
# Keycloak as external OIDC provider — disable built-in IDP
"OCIS_EXCLUDE_RUN_SERVICES": "idp",
"OCIS_OIDC_ISSUER": "https://localhost:8443/realms/oCIS",
"PROXY_OIDC_REWRITE_WELLKNOWN": "true",
"PROXY_AUTOPROVISION_ACCOUNTS": "true",
"PROXY_ROLE_ASSIGNMENT_DRIVER": "oidc",
"PROXY_USER_OIDC_CLAIM": "preferred_username",
"PROXY_USER_CS3_CLAIM": "username",
"WEB_OIDC_CLIENT_ID": "web",
"KEYCLOAK_DOMAIN": "localhost:8443",
"OCIS_ADMIN_USER_ID": "",
"GRAPH_ASSIGN_DEFAULT_USER_ROLE": "false",
"GRAPH_USERNAME_MATCH": "none",
"IDM_CREATE_DEMO_USERS": "false",
"MICRO_REGISTRY_ADDRESS": "127.0.0.1:9233",
"WEB_OIDC_SCOPE": "openid profile email acr"
}
},
"cliCommands": {
"suites": ["cliCommands", "apiServiceAvailability"],
"antivirusNeeded": True,
@@ -182,13 +216,16 @@ def merged_config(suites: list) -> dict:
"tikaNeeded": False,
"federationServer": False,
"collaborationServiceNeeded": False,
"keycloakNeeded": False,
"vaultStorage": False,
"extraServerEnvironment": {},
"extraEnvironment": {},
}
for suite in suites:
cfg = _SUITE_TO_CONFIG.get(suite, {})
for flag in ("emailNeeded", "antivirusNeeded", "tikaNeeded",
"federationServer", "collaborationServiceNeeded"):
"federationServer", "collaborationServiceNeeded",
"keycloakNeeded", "vaultStorage"):
if cfg.get(flag):
merged[flag] = True
merged["extraServerEnvironment"].update(cfg.get("extraServerEnvironment", {}))
@@ -297,6 +334,20 @@ def ocis_healthy(ocis_url: str) -> bool:
return r.stdout.strip() == "200"
def ocis_proxy_ready() -> bool:
"""Check ocis readiness via the proxy debug port (no auth required).
In vault mode PROXY_ROLE_ASSIGNMENT_DRIVER=oidc means basic-auth users
never receive the admin role, so /graph/v1.0/users/admin returns 403.
The proxy debug readyz endpoint (PROXY_DEBUG_ADDR 0.0.0.0:9205) is
unauthenticated and becomes available once the proxy is fully started.
"""
return subprocess.run(
["curl", "-sf", "http://localhost:9205/readyz"],
capture_output=True,
).returncode == 0
def mailpit_healthy() -> bool:
return subprocess.run(
["curl", "-sf", "http://localhost:8025/api/v1/messages"],
@@ -325,6 +376,20 @@ def clamav_healthy() -> bool:
return _tcp_ready("localhost", 3310)
def keycloak_healthy() -> bool:
return subprocess.run(
["curl", "-skf", "https://localhost:9000/health/ready"],
capture_output=True,
).returncode == 0
def postgres_healthy() -> bool:
return subprocess.run(
["docker", "exec", "postgres", "pg_isready", "-U", "keycloak"],
capture_output=True,
).returncode == 0
def load_env_file(path: Path) -> dict:
"""Parse a bash-style env file (export KEY=value) into a dict."""
@@ -435,6 +500,66 @@ def main() -> int:
providers_tmp.close()
cfg["extraServerEnvironment"]["OCM_OCM_PROVIDER_AUTHORIZER_PROVIDERS_FILE"] = providers_tmp.name
if cfg["keycloakNeeded"]:
# Install Playwright runtime and browsers (required for web UI tests)
print("Installing Playwright...")
run([str(repo_root / "vendor-php/bin/playwright-install")])
run([str(repo_root / "vendor-php/bin/playwright-install"), "--browsers"])
print("Playwright ready.")
# Generate TLS certs for keycloak
print("Generating keycloak certs...")
keycloak_certs_dir = repo_root / "keycloak-certs"
keycloak_certs_dir.mkdir(parents=True, exist_ok=True)
run(["openssl", "req", "-x509", "-newkey", "rsa:2048",
"-keyout", str(keycloak_certs_dir / "keycloakkey.pem"),
"-out", str(keycloak_certs_dir / "keycloakcrt.pem"),
"-nodes", "-days", "365", "-subj", "/CN=keycloak"])
for f in keycloak_certs_dir.iterdir():
f.chmod(0o777)
# Set up postgres (keycloak backend)
print("Setting up postgres...")
# GitHub runners ship PostgreSQL pre-started on 5432; stop it to avoid conflicts.
subprocess.run(["sudo", "systemctl", "stop", "postgresql"], capture_output=True)
run(["docker", "run", "-d", "--name", "postgres", "--network", "host",
"-e", "POSTGRES_DB=keycloak",
"-e", "POSTGRES_USER=keycloak",
"-e", "POSTGRES_PASSWORD=keycloak",
POSTGRES_ALPINE_IMAGE])
wait_for(postgres_healthy, 30, "postgres", container="postgres")
print("postgres ready.")
# Patch realm and start keycloak
realm_src = repo_root / "tests/config/ci/ocis-mfa-ci-realm.dist.json"
realm_patched = Path("/tmp/ocis-realm.json")
realm_patched.write_text(
realm_src.read_text()
.replace("https://ocis:9200", "https://localhost:9200")
)
print("Starting keycloak...")
run(["docker", "run", "-d", "--name", "keycloak", "--network", "host",
"-e", "OCIS_DOMAIN=https://localhost:9200",
"-e", "KC_HOSTNAME=localhost",
"-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", f"{repo_root}/keycloak-certs:/keycloak-certs:ro",
"-v", "/tmp/ocis-realm.json:/opt/keycloak/data/import/ocis-mfa-ci-realm.dist.json:ro",
KEYCLOAK_IMAGE,
"start-dev", "--proxy-headers", "xforwarded",
"--spi-connections-http-client-default-disable-trust-manager=true",
"--import-realm", "--health-enabled=true"])
wait_for(keycloak_healthy, 300, "keycloak", container="keycloak")
print("keycloak ready.")
# init ocis
run([str(ocis_bin), "init", "--insecure", "true"])
shutil.copy(
@@ -455,6 +580,21 @@ def main() -> int:
server_env["THUMBNAILS_TXT_FONTMAP_FILE"] = fontmap_tmp.name
server_env.update(cfg["extraServerEnvironment"])
# Patch web UI config: replace container DNS name with localhost so the
# browser's 'self' CSP origin (localhost:9200) is not violated.
web_cfg_src = Path(server_env["WEB_UI_CONFIG_FILE"])
web_cfg_data = json.loads(
web_cfg_src.read_text().replace("ocis-server:9200", "localhost:9200")
)
if cfg["vaultStorage"]:
web_cfg_data.setdefault("openIdConnect", {})["scope"] = "openid profile email acr"
server_env["PROXY_CSP_CONFIG_FILE_LOCATION"] = str(repo_root / "tests/config/ci/csp.yaml")
web_cfg_tmp = tempfile.NamedTemporaryFile(
mode="w", suffix=".json", prefix="ocis-web-config-", delete=False)
json.dump(web_cfg_data, web_cfg_tmp, indent=2)
web_cfg_tmp.close()
server_env["WEB_UI_CONFIG_FILE"] = web_cfg_tmp.name
# start ociswrapper (primary ocis)
print("Starting ocis...")
wrapper_proc = subprocess.Popen(
@@ -659,13 +799,49 @@ def main() -> int:
signal.signal(signal.SIGINT, cleanup)
try:
wait_for(lambda: ocis_healthy(ocis_url), 300, "ocis")
if cfg["vaultStorage"]:
# Basic auth is blocked in vault mode (OIDC role assignment),
# use the unauthenticated proxy debug readyz endpoint instead.
wait_for(ocis_proxy_ready, 300, "ocis")
else:
wait_for(lambda: ocis_healthy(ocis_url), 300, "ocis")
print("ocis ready.")
if cfg["federationServer"]:
wait_for(lambda: ocis_healthy(ocis_fed_url), 300, "federation ocis")
print("federation ocis ready.")
if cfg["vaultStorage"]:
vault_data_dir = Path.home() / "ocis/storage/users-vault"
vault_data_dir.mkdir(parents=True, exist_ok=True)
# Inherit the full server env so the process has PATH, OCIS_JWT_SECRET,
# OCIS_CONFIG_DIR, SSL settings, etc. — then override with vault-specific values.
vault_env = {
**server_env,
"STORAGE_USERS_ENABLE_VAULT_MODE": "true",
"STORAGE_USERS_SERVICE_NAME": "storage-users-vault",
"STORAGE_USERS_GRPC_ADDR": "localhost:19285",
"STORAGE_USERS_HTTP_ADDR": "localhost:19286",
"STORAGE_USERS_DATA_SERVER_URL": "http://localhost:19286/data",
"STORAGE_USERS_DEBUG_ADDR": "localhost:19287",
"STORAGE_USERS_OCIS_ROOT": str(vault_data_dir),
"STORAGE_USERS_EVENTS_CONSUMER_GROUP": "vault-dcfs",
}
print("Starting storage-users-vault...")
vault_proc = subprocess.Popen(
[str(ocis_bin), "storage-users", "server"],
env=vault_env,
)
procs.append(vault_proc)
wait_for(
lambda: subprocess.run(
["curl", "-sf", "http://localhost:19287/healthz"],
capture_output=True,
).returncode == 0,
120, "storage-users-vault",
)
print("vault ready.")
# expected failures file
if acceptance_test_type == "core-api":
filter_tags = "~@skipOnGraph&&~@skipOnOcis-OCIS-Storage"
@@ -720,4 +896,4 @@ def main() -> int:
if __name__ == "__main__":
sys.exit(main())
sys.exit(main())
+1
View File
@@ -7,6 +7,7 @@ directives:
- 'https://raw.githubusercontent.com/owncloud/awesome-ocis/'
# In contrary to bash and docker the default is given after the | character
- 'https://${KEYCLOAK_DOMAIN|keycloak.owncloud.test}/'
- 'https://localhost:8443/'
default-src:
- '''none'''
font-src:
+37
View File
@@ -138,11 +138,48 @@ func WaitForConnection() (bool, string) {
}
log.Println("oCIS server is ready to accept requests")
// Proxy health alone causes flakiness: tests hit sharing/gateway before they finish init.
results := make(chan bool, 2)
go func() { results <- waitServiceReady("sharing") }()
go func() { results <- waitServiceReady("gateway") }()
sharingOK, gatewayOK := <-results, <-results
if !sharingOK || !gatewayOK {
return false, "Timeout waiting for sharing/gateway to become ready"
}
return true, "oCIS server is up and running"
}
}
}
// waitServiceReady polls http://localhost:<debugPort>/readyz until 200 or 30 s.
func waitServiceReady(service string) bool {
port := config.GetServiceDebugPort(service)
url := fmt.Sprintf("http://localhost:%d/readyz", port)
timeout := time.After(30 * time.Second)
client := http.Client{Timeout: 2 * time.Second}
for {
select {
case <-timeout:
log.Println(fmt.Sprintf("Timeout waiting for %s /readyz on port %d", service, port))
return false
default:
res, err := client.Get(url)
if err == nil && res.StatusCode == 200 {
res.Body.Close()
log.Println(fmt.Sprintf("%s service is ready (readyz port %d)", service, port))
return true
}
if res != nil {
res.Body.Close()
}
time.Sleep(500 * time.Millisecond)
}
}
}
func waitUntilCompleteShutdown() (bool, string) {
timeout := 30 * time.Second
startTime := time.Now()
+24
View File
@@ -1,3 +1,27 @@
Release 1.7.0
=============
**Changes**
**Breaking changes**
* To address a security issue, it was necessary to add a `MaxDepth` option to
`ReadSettings` to limit the depth of XML trees during parsing. A generous
default value of 1024 was chosen to avoid breaking most existing code.
However, if your code is processing XML hierarchies with a depth greater
than 1024, you will need to assign your `Document` a `ReadSettings` that has
a `MaxDepth` set to a higher value.
**Security Fixes**
* Limited the depth of XML trees processed by all `ReadFrom` functions during
parsing.
* Fixed a `CompilePath` index-out-of-range panic that could be caused by a
missing path filter key.
* Sanitized the contents of XML text, comment, ProcInst and Directive tokens
provided by the user.
Release 1.6.0
=============
+31 -17
View File
@@ -13,6 +13,7 @@ import (
"errors"
"io"
"iter"
"maps"
"os"
"slices"
"strings"
@@ -27,6 +28,10 @@ const (
// ErrXML is returned when XML parsing fails due to incorrect formatting.
var ErrXML = errors.New("etree: invalid XML format")
// ErrMaxDepth is returned when the depth of the XML tree being read exceeds
// the maximum depth allowed by ReadSettings.MaxDepth.
var ErrMaxDepth = errors.New("etree: XML tree exceeds maximum depth")
// cdataPrefix is used to detect CDATA text when ReadSettings.PreserveCData is
// true.
var cdataPrefix = []byte("<![CDATA[")
@@ -76,8 +81,18 @@ type ReadSettings struct {
// whether an end element is present. Commonly set to xml.HTMLAutoClose.
// Default: nil.
AutoClose []string
// MaxDepth is the maximum depth of the XML tree to parse. If the depth of
// the XML tree exceeds this value, all ReadFrom* functions return the
// error ErrMaxDepth. If MaxDepth is zero or negative, a depth limit of
// 1024 is used. Default: 0 (i.e., a limit of 1024).
MaxDepth int
}
// defaultMaxDepth is the maximum depth of an XML tree parsed by ReadFrom*
// functions when ReadSettings.MaxDepth is not set to a positive value.
const defaultMaxDepth = 1024
// defaultCharsetReader is used by the xml decoder when the ReadSettings
// CharsetReader value is nil. It behaves as a "pass-through", ignoring
// the requested charset parameter and skipping conversion altogether.
@@ -87,18 +102,9 @@ func defaultCharsetReader(charset string, input io.Reader) (io.Reader, error) {
// dup creates a duplicate of the ReadSettings object.
func (s *ReadSettings) dup() ReadSettings {
var entityCopy map[string]string
if s.Entity != nil {
entityCopy = make(map[string]string)
for k, v := range s.Entity {
entityCopy[k] = v
}
}
return ReadSettings{
CharsetReader: s.CharsetReader,
Permissive: s.Permissive,
Entity: entityCopy,
}
c := *s
c.Entity = maps.Clone(s.Entity)
return c
}
// WriteSettings determine the behavior of the Document's WriteTo* functions.
@@ -913,6 +919,11 @@ func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err er
attrCheck := make(map[xml.Name]int)
dec := newDecoder(r, settings)
maxDepth := settings.MaxDepth
if maxDepth <= 0 {
maxDepth = defaultMaxDepth
}
var stack stack[*Element]
stack.push(e)
for {
@@ -942,6 +953,9 @@ func (e *Element) readFrom(ri io.Reader, settings ReadSettings) (n int64, err er
switch t := t.(type) {
case xml.StartElement:
if len(stack.data) > maxDepth {
return r.Bytes(), ErrMaxDepth
}
e := newElement(t.Name.Space, t.Name.Local, top)
if settings.PreserveDuplicateAttrs || len(t.Attr) < 2 {
for _, a := range t.Attr {
@@ -1622,7 +1636,7 @@ func (c *CharData) Index() int {
func (c *CharData) WriteTo(w Writer, s *WriteSettings) {
if c.IsCData() {
w.WriteString(`<![CDATA[`)
w.WriteString(c.Data)
sanitizeCData(w, c.Data)
w.WriteString(`]]>`)
} else {
var m escapeMode
@@ -1704,7 +1718,7 @@ func (c *Comment) Index() int {
// WriteTo serialies the comment to the writer.
func (c *Comment) WriteTo(w Writer, s *WriteSettings) {
w.WriteString("<!--")
w.WriteString(c.Data)
sanitizeComment(w, c.Data)
w.WriteString("-->")
}
@@ -1769,7 +1783,7 @@ func (d *Directive) Index() int {
// WriteTo serializes the XML directive to the writer.
func (d *Directive) WriteTo(w Writer, s *WriteSettings) {
w.WriteString("<!")
w.WriteString(d.Data)
sanitizeDirective(w, d.Data)
w.WriteString(">")
}
@@ -1837,10 +1851,10 @@ func (p *ProcInst) Index() int {
// WriteTo serializes the processing instruction to the writer.
func (p *ProcInst) WriteTo(w Writer, s *WriteSettings) {
w.WriteString("<?")
w.WriteString(p.Target)
sanitizeProcInst(w, p.Target)
if p.Inst != "" {
w.WriteByte(' ')
w.WriteString(p.Inst)
sanitizeProcInst(w, p.Inst)
}
w.WriteString("?>")
}
+114
View File
@@ -384,6 +384,120 @@ func escapeString(w Writer, s string, m escapeMode) {
w.WriteString(s[last:])
}
// sanitizeCData writes the sanitized contents of a CDATA section to the
// writer. XML provides no way to escape the "]]>" sequence within a CDATA
// section, so any occurrence of it is split across two CDATA sections.
func sanitizeCData(w Writer, s string) {
for {
i := strings.Index(s, "]]>")
if i < 0 {
break
}
w.WriteString(s[:i+2])
w.WriteString("]]><![CDATA[")
s = s[i+2:]
}
w.WriteString(s)
}
// sanitizeComment writes the sanitized contents of a comment to the writer.
// An XML comment may not contain the string "--", and it may not end with a
// '-'. Because XML provides no way to escape these sequences, spaces are
// inserted where necessary.
func sanitizeComment(w Writer, s string) {
last, hyphen := 0, false
for i := 0; i < len(s); i++ {
if s[i] != '-' {
hyphen = false
continue
}
if hyphen {
w.WriteString(s[last:i])
w.WriteByte(' ')
last = i
}
hyphen = true
}
w.WriteString(s[last:])
if hyphen {
w.WriteByte(' ')
}
}
// sanitizeProcInst writes the contents of a sanitized processing instruction
// to the writer. XML provides no way to escape the "?>" sequence within a
// processing instruction, so a space is inserted between the two characters.
func sanitizeProcInst(w Writer, s string) {
for {
i := strings.Index(s, "?>")
if i < 0 {
break
}
w.WriteString(s[:i+1])
w.WriteByte(' ')
s = s[i+1:]
}
w.WriteString(s)
}
// sanitizeDirective writes the sanitized contents of an XML directive to the
// writer.
func sanitizeDirective(w Writer, s string) {
// The XML decoder reserves the character following "<!" for comments
// ('-') and CDATA sections ('['), and it treats "<!>" as an unterminated
// directive. Insert a space to avoid conflicts with reserved sequences.
scan := s
if s == "" || s[0] == '-' || s[0] == '[' {
w.WriteByte(' ')
} else {
scan = s[1:]
}
// A directive's contents may legitimately contain '<' and '>' characters,
// so write them without modification when they are balanced.
if isDirectiveBalanced(scan) {
w.WriteString(s)
return
}
// The contents are unbalanced, so escape every character in the string.
escapeString(w, s, escapeNormal)
}
// isDirectiveBalanced returns true if the interpreted portion of an XML
// directive's contents may be enclosed by "<!" and ">" without changing the
// extents of the resulting directive.
func isDirectiveBalanced(s string) bool {
var quote byte
var depth int
for i := 0; i < len(s); i++ {
switch c := s[i]; {
case quote != 0:
if c == quote {
quote = 0
}
case c == '\'' || c == '"':
quote = c
case c == '>':
if depth == 0 {
return false
}
depth--
case c == '<':
if !strings.HasPrefix(s[i+1:], "!--") {
depth++
break
}
j := strings.Index(s[i+4:], "-->")
if j < 0 {
return false
}
i += 4 + j + 2
}
}
return quote == 0 && depth == 0
}
func isInCharacterRange(r rune) bool {
return r == 0x09 ||
r == 0x0A ||
+14 -2
View File
@@ -281,7 +281,11 @@ func (c *compiler) parseSegment(path string) segment {
c.err = ErrPath("path has invalid filter [brackets].")
break
}
seg.filters = append(seg.filters, c.parseFilter(fpath[:len(fpath)-1]))
filter := c.parseFilter(fpath[:len(fpath)-1])
if c.err != ErrPath("") {
break
}
seg.filters = append(seg.filters, filter)
}
return seg
}
@@ -320,7 +324,11 @@ func (c *compiler) parseFilter(path string) filter {
// Filter contains [@attr='val'], [@attr="val"], [fn()='val'],
// [fn()="val"], [tag='val'] or [tag="val"]?
eqindex := strings.IndexByte(path, '=')
if eqindex >= 0 && eqindex+1 < len(path) {
if eqindex == 0 {
c.err = ErrPath("path contains a filter expression with no key.")
return nil
}
if eqindex > 0 && eqindex+1 < len(path) {
quote := path[eqindex+1]
if quote == '\'' || quote == '"' {
rindex := nextIndex(path, quote, eqindex+2)
@@ -334,6 +342,10 @@ func (c *compiler) parseFilter(path string) filter {
switch {
case key[0] == '@':
if len(key) == 1 {
c.err = ErrPath("path contains a filter expression with no key.")
return nil
}
return newFilterAttrVal(key[1:], value)
case strings.HasSuffix(key, "()"):
name := key[:len(key)-2]
+65
View File
@@ -0,0 +1,65 @@
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
//
// Construct a [Provider] and [oauth2.Config] through the identity provider's
// discovery document with [NewProvider], and construct an ID Token verifier
// with [Provider.Verifier]:
//
// provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
// if err != nil {
// // handle error
// }
//
// // Configure an OpenID Connect aware OAuth2 client.
// oauth2Config := oauth2.Config{
// ClientID: clientID,
// ClientSecret: clientSecret,
// RedirectURL: redirectURL,
// // Discovery returns the OAuth2 endpoints.
// Endpoint: provider.Endpoint(),
// // "openid" is a required scope for OpenID Connect flows.
// Scopes: []string{oidc.ScopeOpenID, oidc.ScopeProfile, oidc.ScopeEmail},
// }
//
// idTokenVerifier := provider.Verifier(&oidc.Config{ClientID: clientID})
//
// OAuth 2.0 redirects then opt into the OpenID Connect flow with [ScopeOpenID]:
//
// func handleRedirect(w http.ResponseWriter, r *http.Request) {
// http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
// }
//
// When handling an OAuth 2.0 response, an [IDTokenVerifier] can be used to
// validate the "id_token" payload, containing well-known fields such as the
// user's email, name, and picture URL:
//
// func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
// // Verify state and other OAuth 2.0 responses.
//
// // Perform standard token exchange.
// oauth2Token, err := oauth2Config.Exchange(r.Context(), r.URL.Query().Get("code"))
// if err != nil {
// // ...
// }
// // Extract the ID Token from OAuth2 token.
// rawIDToken, ok := oauth2Token.Extra("id_token").(string)
// if !ok {
// // ...
// }
// // Parse and verify ID Token payload.
// idToken, err := idTokenVerifier.Verify(r.Context(), rawIDToken)
// if err != nil {
// // ...
// }
// // Parse well-known claims from the token.
// // https://openid.net/specs/openid-connect-core-1_0.html#Claims
// var claims struct {
// Email string `json:"email"`
// EmailVerified bool `json:"email_verified"`
// Name string `json:"name"`
// Picture string `json:"picture"`
// }
// if err := idToken.Claims(&claims); err != nil {
// // ...
// }
// }
package oidc
+8
View File
@@ -30,3 +30,11 @@ var allAlgs = []jose.SignatureAlgorithm{
jose.PS512,
jose.EdDSA,
}
var supportedJOSEAlgs = map[string]bool{}
func init() {
for _, alg := range allAlgs {
supportedJOSEAlgs[string(alg)] = true
}
}
+58 -6
View File
@@ -6,6 +6,7 @@ import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"io"
@@ -17,8 +18,8 @@ import (
// StaticKeySet is a verifier that validates JWT against a static set of public keys.
type StaticKeySet struct {
// PublicKeys used to verify the JWT. Supported types are *rsa.PublicKey and
// *ecdsa.PublicKey.
// PublicKeys used to verify the JWT. Supported types are *rsa.PublicKey,
// *ecdsa.PublicKey, and ed25519.PublicKey.
PublicKeys []crypto.PublicKey
}
@@ -53,8 +54,10 @@ func (s *StaticKeySet) VerifySignature(ctx context.Context, jwt string) ([]byte,
// exposed for providers that don't support discovery or to prevent round trips to the
// discovery URL.
//
// The returned KeySet is a long lived verifier that caches keys based on any
// keys change. Reuse a common remote key set instead of creating new ones as needed.
// The returned KeySet is a long lived verifier that caches keys in memory,
// re-fetching from the remote URL when it encounters a key ID it hasn't seen.
// Reuse a single remote key set rather than creating a new one for each
// verification.
func NewRemoteKeySet(ctx context.Context, jwksURL string) *RemoteKeySet {
return newRemoteKeySet(ctx, jwksURL)
}
@@ -123,7 +126,7 @@ func (i *inflight) result() ([]jose.JSONWebKey, error) {
return i.keys, i.err
}
// paresdJWTKey is a context key that allows common setups to avoid parsing the
// parsedJWTKey is a context key that allows common setups to avoid parsing the
// JWT twice. It holds a *jose.JSONWebSignature value.
var parsedJWTKey contextKey
@@ -233,6 +236,55 @@ func (r *RemoteKeySet) keysFromRemote(ctx context.Context) ([]jose.JSONWebKey, e
}
}
// jwkJSON implements custom logic for unmarshaling JSON Web Key Sets.
type jwkJSON struct {
Keys []jose.JSONWebKey
}
func (j *jwkJSON) UnmarshalJSON(data []byte) error {
var raw struct {
Keys []json.RawMessage `json:"keys"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// For each key, attempt to determine if the algorithm is supported before
// unmarshaling the key. This allows us to ignore keys with unsupported
// algorithms, rather than failing to load the entire set.
for _, key := range raw.Keys {
var metadata struct {
Alg string `json:"alg"`
}
if err := json.Unmarshal(key, &metadata); err != nil {
return err
}
if metadata.Alg != "" {
// Algorithms are technically optional, but if the key advertises an
// algorithm we don't support, ignore it rather than failing to load
// the entire key set.
//
// https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
//
// This skip is currently implemented due to secp256k1, which some
// providers use for signing with "ES256K". While we could also
// ignore the curve, this seems like a more general check in case
// providers start throwing in post-quantum algorithims or something
// like that.
//
// https://github.com/coreos/go-oidc/issues/490
if !supportedJOSEAlgs[metadata.Alg] {
continue
}
}
var jwk jose.JSONWebKey
if err := json.Unmarshal(key, &jwk); err != nil {
return err
}
j.Keys = append(j.Keys, jwk)
}
return nil
}
func (r *RemoteKeySet) updateKeys() ([]jose.JSONWebKey, error) {
req, err := http.NewRequest("GET", r.jwksURL, nil)
if err != nil {
@@ -255,7 +307,7 @@ func (r *RemoteKeySet) updateKeys() ([]jose.JSONWebKey, error) {
return nil, fmt.Errorf("oidc: get keys failed: %s %s", resp.Status, body)
}
var keySet jose.JSONWebKeySet
var keySet jwkJSON
err = unmarshalResp(resp, body, &keySet)
if err != nil {
return nil, fmt.Errorf("oidc: failed to decode keys: %v %s", err, body)
+4 -3
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"slices"
"time"
)
@@ -37,7 +38,7 @@ type LogoutToken struct {
Expiry time.Time
// Optional session ID claim ("sid").
//
// The exact semantics of session IDs very between identity providers. Use
// The exact semantics of session IDs vary between identity providers. Use
// your provider's documentation to determine what this correlates to and
// how it should be handled.
SessionID string
@@ -98,7 +99,7 @@ type logoutTokenJSON struct {
// }
// verifier := provider.Verifier(oidcConfig)
//
// mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Reequest) {
// mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
// rawLogoutToken := r.PostFormValue("logout_token")
// if rawLogoutToken == "" {
// // ...
@@ -163,7 +164,7 @@ func (v *IDTokenVerifier) VerifyLogout(ctx context.Context, rawLogoutToken strin
if !v.config.SkipClientIDCheck {
if v.config.ClientID != "" {
if !contains(t.Audience, v.config.ClientID) {
if !slices.Contains(t.Audience, v.config.ClientID) {
return nil, fmt.Errorf("oidc: expected logout token audience %q got %q", v.config.ClientID, t.Audience)
}
} else {
+115 -12
View File
@@ -1,4 +1,3 @@
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
package oidc
import (
@@ -24,6 +23,26 @@ const (
// ScopeOpenID is the mandatory scope for all OpenID Connect OAuth2 requests.
ScopeOpenID = "openid"
// ScopeProfile can be used to request information about the user's profile,
// such as "name", "picture", etc.
//
// The exact set of claims supported by identity providers differs widely,
// though "name" and "picture" are commonly returned.
//
// See: https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
ScopeProfile = "profile"
// ScopeEmail can be used to request the user's email address through the
// "email" and "email_verified" claims.
//
// What it means to verify an email isn't well defined. Clients can
// generally throw out emails when the "emvail_verified" claim is false, but
// should consult identity provider specific docs if attempting to ensure
// that the user controls the returned email address.
//
// See: https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
ScopeEmail = "email"
// ScopeOfflineAccess is an optional scope defined by OpenID Connect for requesting
// OAuth2 refresh tokens.
//
@@ -92,7 +111,24 @@ func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
return client.Do(req.WithContext(ctx))
}
// Provider represents an OpenID Connect server's configuration.
// Provider represents an OpenID Connect server's configuration, fetched from
// the discovery document.
//
// To access fields in the discovery document that aren't exposed directly
// through this package's API, use the [Provider.Claims] method. For example, to
// access the registration or end session endpoints:
//
// p, err := oidc.NewProvider(ctx, "https://issuer.example.com")
// if err != nil {
// // ...
// }
// var metadata struct {
// EndSessionEndpoint string `json:"end_session_endpoint"`
// RegistrationEndpoint string `json:"registration_endpoint"`
// }
// if err := p.Claims(&metadata); err != nil {
// // ...
// }
type Provider struct {
issuer string
authURL string
@@ -213,6 +249,8 @@ type ProviderConfig struct {
//
// The provided context is only used for [http.Client] configuration through
// [ClientContext], not cancelation.
//
// For providers that implement discovery, use [NewProvider] instead.
func (p *ProviderConfig) NewProvider(ctx context.Context) *Provider {
return &Provider{
issuer: p.IssuerURL,
@@ -226,12 +264,36 @@ func (p *ProviderConfig) NewProvider(ctx context.Context) *Provider {
}
}
// IssuerMismatchError is returned by [NewProvider] when the "iss" value
// reported by the upstream is different than the expected value.
//
// Issuer mismatches can occur due to trailing slashes ("https://example.com"
// vs. "https://example.com/") or represent significant misconfiguration for
// multi-tenant issuers.
//
// Issuers must match exactly as they are also used to validate ID Tokens.
//
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
type IssuerMismatchError struct {
// The value provided to this package. The expected value.
Provided string
// The value advertised by the discovery document.
Discovered string
}
func (e *IssuerMismatchError) Error() string {
return fmt.Sprintf("oidc: issuer URL provided to client (%q) did not match the issuer URL returned by provider (%q)", e.Provided, e.Discovered)
}
// NewProvider uses the OpenID Connect discovery mechanism to construct a Provider.
// The issuer is the URL identifier for the service. For example: "https://accounts.google.com"
// or "https://login.salesforce.com".
//
// If the "iss" value returned in the discovery document doesn't match the value
// provided here, [IssuerMismatchError] is returned.
//
// OpenID Connect providers that don't implement discovery or host the discovery
// document at a non-spec complaint path (such as requiring a URL parameter),
// document at a non-spec compliant path (such as requiring a URL parameter),
// should use [ProviderConfig] instead.
//
// See: https://openid.net/specs/openid-connect-discovery-1_0.html
@@ -267,7 +329,10 @@ func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
issuerURL = issuer
}
if p.Issuer != issuerURL && !skipIssuerValidation {
return nil, fmt.Errorf("oidc: issuer URL provided to client (%q) did not match the issuer URL returned by provider (%q)", issuer, p.Issuer)
return nil, &IssuerMismatchError{
Provided: issuerURL,
Discovered: p.Issuer,
}
}
var algs []string
for _, a := range p.Algorithms {
@@ -301,7 +366,7 @@ func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
//
// For a list of fields defined by the OpenID Connect spec see:
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
func (p *Provider) Claims(v interface{}) error {
func (p *Provider) Claims(v any) error {
if p.rawClaims == nil {
return errors.New("oidc: claims not set")
}
@@ -340,7 +405,7 @@ type userInfoRaw struct {
}
// Claims unmarshals the raw JSON object claims into the provided object.
func (u *UserInfo) Claims(v interface{}) error {
func (u *UserInfo) Claims(v any) error {
if u.claims == nil {
return errors.New("oidc: claims not set")
}
@@ -348,6 +413,44 @@ func (u *UserInfo) Claims(v interface{}) error {
}
// UserInfo uses the token source to query the provider's user info endpoint.
//
// It's fewer round trips and better supported to validate the ID Token with
// [Provider.Verifier], rather than using the UserInfo endpoint. The ID Token
// contains all information [UserInfo] provides:
//
// p, err := oidc.NewProvider(ctx, "https://issuer.example.com")
// if err != nil {
// // ...
// }
// config := &oidc.Config{
// ClientID: clientID,
// }
// v := p.Verifier(config)
// http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
// oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
// if err != nil {
// // ...
// }
// rawIDToken, ok := oauth2Token.Extra("id_token").(string)
// if !ok {
// // ...
// }
// idToken, err := verifier.Verify(ctx, rawIDToken)
// if err != nil {
// // ...
// }
// // https://openid.net/specs/openid-connect-core-1_0.html#Claims
// var claims struct {
// Email string `json:"email"`
// EmailVerified bool `json:"email_verified"`
// Name string `json:"name"`
// Picture string `json:"picture"`
// }
// if err := idToken.Claims(&claims); err != nil {
// // ...
// }
// // Use claims...
// })
func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
if p.userInfoURL == "" {
return nil, errors.New("oidc: user info endpoint is not supported by this provider")
@@ -425,7 +528,7 @@ type IDToken struct {
// A unique string which identifies the end user.
Subject string
// Expiry of the token. Ths package will not process tokens that have
// Expiry of the token. This package will not process tokens that have
// expired unless that validation is explicitly turned off.
Expiry time.Time
// When the token was issued by the provider.
@@ -433,7 +536,7 @@ type IDToken struct {
// Initial nonce provided during the authentication redirect.
//
// This package does NOT provided verification on the value of this field
// This package does NOT provide verification on the value of this field
// and it's the user's responsibility to ensure it contains a valid value.
Nonce string
@@ -465,15 +568,15 @@ type IDToken struct {
// if err := idToken.Claims(&claims); err != nil {
// // handle error
// }
func (i *IDToken) Claims(v interface{}) error {
func (i *IDToken) Claims(v any) error {
if i.claims == nil {
return errors.New("oidc: claims not set")
}
return json.Unmarshal(i.claims, v)
}
// VerifyAccessToken verifies that the hash of the access token that corresponds to the iD token
// matches the hash in the id token. It returns an error if the hashes don't match.
// VerifyAccessToken verifies that the hash of the access token that corresponds to the ID token
// matches the hash in the ID token. It returns an error if the hashes don't match.
// It is the caller's responsibility to ensure that the optional access token hash is present for the ID token
// before calling this method. See https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
func (i *IDToken) VerifyAccessToken(accessToken string) error {
@@ -570,7 +673,7 @@ func (j *jsonTime) UnmarshalJSON(b []byte) error {
return nil
}
func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
func unmarshalResp(r *http.Response, body []byte, v any) error {
err := json.Unmarshal(body, &v)
if err == nil {
return nil
+17 -24
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"slices"
"time"
jose "github.com/go-jose/go-jose/v4"
@@ -17,10 +18,10 @@ const (
issuerGoogleAccountsNoScheme = "accounts.google.com"
)
// TokenExpiredError indicates that Verify or VerifyLogout failed because the
// token was expired. This error does NOT indicate that the token is not also
// invalid for other reasons. Other checks might have failed if the expiration
// check had not failed.
// TokenExpiredError indicates that [IDTokenVerifier.Verify] or
// [IDTokenVerifier.VerifyLogout] failed because the token was expired. This
// error does NOT indicate that the token is not also invalid for other reasons.
// Other checks might have failed if the expiration check had not failed.
type TokenExpiredError struct {
// Expiry is the time when the token expired.
Expiry time.Time
@@ -30,7 +31,7 @@ func (e *TokenExpiredError) Error() string {
return fmt.Sprintf("oidc: token is expired (Token Expiry: %v)", e.Expiry)
}
// KeySet is a set of publc JSON Web Keys that can be used to validate the signature
// KeySet is a set of public JSON Web Keys that can be used to validate the signature
// of JSON web tokens. This is expected to be backed by a remote key set through
// provider metadata discovery or an in-memory set of keys delivered out-of-band.
type KeySet interface {
@@ -55,8 +56,8 @@ type IDTokenVerifier struct {
// NewVerifier returns a verifier manually constructed from a key set and issuer URL.
//
// It's easier to use provider discovery to construct an IDTokenVerifier than creating
// one directly. This method is intended to be used with provider that don't support
// metadata discovery, or avoiding round trips when the key set URL is already known.
// one directly. This method is intended to be used with providers that don't support
// metadata discovery, or to avoid round trips when the key set URL is already known.
//
// This constructor can be used to create a verifier directly using the issuer URL and
// JSON Web Key Set URL without using discovery:
@@ -82,8 +83,8 @@ type Config struct {
ClientID string
// If specified, only this set of algorithms may be used to sign the JWT.
//
// If the IDTokenVerifier is created from a provider with (*Provider).Verifier, this
// defaults to the set of algorithms the provider supports. Otherwise this values
// If the IDTokenVerifier is created from a provider with [Provider.Verifier], this
// defaults to the set of algorithms the provider supports. Otherwise this value
// defaults to RS256.
SupportedSigningAlgs []string
@@ -92,7 +93,7 @@ type Config struct {
// If true, token expiry is not checked.
SkipExpiryCheck bool
// SkipIssuerCheck is intended for specialized cases where the the caller wishes to
// SkipIssuerCheck is intended for specialized cases where the caller wishes to
// defer issuer validation. When enabled, callers MUST independently verify the Token's
// Issuer is a known good value.
//
@@ -117,8 +118,9 @@ type Config struct {
}
// VerifierContext returns an IDTokenVerifier that uses the provider's key set to
// verify JWTs. As opposed to Verifier, the context is used to configure requests
// to the upstream JWKs endpoint. The provided context's cancellation is ignored.
// verify JWTs. As opposed to [Provider.Verifier], the context is used to configure
// requests to the upstream JWKs endpoint. The provided context's cancellation is
// ignored.
func (p *Provider) VerifierContext(ctx context.Context, config *Config) *IDTokenVerifier {
return p.newVerifier(NewRemoteKeySet(ctx, p.jwksURL), config)
}
@@ -126,7 +128,7 @@ func (p *Provider) VerifierContext(ctx context.Context, config *Config) *IDToken
// Verifier returns an IDTokenVerifier that uses the provider's key set to verify JWTs.
//
// The returned verifier uses a background context for all requests to the upstream
// JWKs endpoint. To control that context, use VerifierContext instead.
// JWKs endpoint. To control that context, use [Provider.VerifierContext] instead.
func (p *Provider) Verifier(config *Config) *IDTokenVerifier {
return p.newVerifier(p.remoteKeySet(), config)
}
@@ -142,15 +144,6 @@ func (p *Provider) newVerifier(keySet KeySet, config *Config) *IDTokenVerifier {
return NewVerifier(p.issuer, keySet, config)
}
func contains(sli []string, ele string) bool {
for _, s := range sli {
if s == ele {
return true
}
}
return false
}
// Returns the Claims from the distributed JWT token
func resolveDistributedClaim(ctx context.Context, verifier *IDTokenVerifier, src claimSource) ([]byte, error) {
req, err := http.NewRequest("GET", src.Endpoint, nil)
@@ -187,7 +180,7 @@ func resolveDistributedClaim(ctx context.Context, verifier *IDTokenVerifier, src
// Verify parses a raw ID Token, verifies it's been signed by the provider, performs
// any additional checks depending on the Config, and returns the payload.
//
// Verify does NOT do nonce validation, which is the callers responsibility.
// Verify does NOT do nonce validation, which is the caller's responsibility.
//
// See: https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
//
@@ -257,7 +250,7 @@ func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDTok
// This check DOES NOT ensure that the ClientID is the party to which the ID Token was issued (i.e. Authorized party).
if !v.config.SkipClientIDCheck {
if v.config.ClientID != "" {
if !contains(t.Audience, v.config.ClientID) {
if !slices.Contains(t.Audience, v.config.ClientID) {
return nil, fmt.Errorf("oidc: expected audience %q got %q", v.config.ClientID, t.Audience)
}
} else {
+23 -10
View File
@@ -19,6 +19,10 @@ import (
// no limit.
var MaxPacketLengthBytes int64 = math.MaxInt32
// MaxNestingDepth specifies the maximum allowed nesting depth when calling ReadPacket, DecodePacket, or
// DecodePacketErr. Set to 0 for no limit.
var MaxNestingDepth int = 1000
type Packet struct {
Identifier
Value interface{}
@@ -218,7 +222,7 @@ func printPacket(out io.Writer, p *Packet, indent int, printBytes bool) {
// ReadPacket reads a single Packet from the reader.
func ReadPacket(reader io.Reader) (*Packet, error) {
p, _, err := readPacket(reader)
p, _, err := readPacket(reader, 0)
if err != nil {
return nil, err
}
@@ -278,7 +282,7 @@ func int64Length(i int64) (numBytes int) {
// DecodePacket decodes the given bytes into a single Packet
// If a decode error is encountered, nil is returned.
func DecodePacket(data []byte) *Packet {
p, _, _ := readPacket(bytes.NewBuffer(data))
p, _, _ := readPacket(bytes.NewBuffer(data), 0)
return p
}
@@ -286,7 +290,7 @@ func DecodePacket(data []byte) *Packet {
// DecodePacketErr decodes the given bytes into a single Packet
// If a decode error is encountered, nil is returned.
func DecodePacketErr(data []byte) (*Packet, error) {
p, _, err := readPacket(bytes.NewBuffer(data))
p, _, err := readPacket(bytes.NewBuffer(data), 0)
if err != nil {
return nil, err
}
@@ -294,12 +298,20 @@ func DecodePacketErr(data []byte) (*Packet, error) {
}
// readPacket reads a single Packet from the reader, returning the number of bytes read.
func readPacket(reader io.Reader) (*Packet, int, error) {
func readPacket(reader io.Reader, depth int) (*Packet, int, error) {
if MaxNestingDepth > 0 && depth >= MaxNestingDepth {
return nil, 0, fmt.Errorf("nesting depth %d exceeds maximum %d", depth, MaxNestingDepth)
}
identifier, length, read, err := readHeader(reader)
if err != nil {
return nil, read, err
}
if length != LengthIndefinite && MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {
return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes)
}
p := &Packet{
Identifier: identifier,
}
@@ -326,13 +338,19 @@ func readPacket(reader io.Reader) (*Packet, int, error) {
}
// Read the next packet
child, r, err := readPacket(reader)
child, r, err := readPacket(reader, depth+1)
if err != nil {
return nil, read, unexpectedEOF(err)
}
contentRead += r
read += r
// Enforce the aggregate size limit for constructed packets. Indefinite length declares
// no bound up front, so the content bytes are only known as they are read.
if MaxPacketLengthBytes > 0 && int64(contentRead) > MaxPacketLengthBytes {
return nil, read, fmt.Errorf("length %d greater than maximum %d", contentRead, MaxPacketLengthBytes)
}
// Test is this is the EOC marker for our packet
if isEOCPacket(child) {
if length == LengthIndefinite {
@@ -351,11 +369,6 @@ func readPacket(reader io.Reader) (*Packet, int, error) {
return nil, read, errors.New("indefinite length used with primitive type")
}
// Read definite-length content
if MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {
return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes)
}
var content []byte
if length > 0 {
// Read the content and limit it to the parsed length.
+5 -4
View File
@@ -40,7 +40,7 @@ func readLength(reader io.Reader) (length int, read int, err error) {
}
// Accumulate into a 64-bit variable
var length64 int64
var length64 uint64
for i := 0; i < lengthBytes; i++ {
b, err = readByte(reader)
if err != nil {
@@ -53,13 +53,14 @@ func readLength(reader io.Reader) (length int, read int, err error) {
// x.600, 8.1.3.5
length64 <<= 8
length64 |= int64(b)
length64 |= uint64(b)
}
// Cast to a platform-specific integer
length = int(length64)
// Ensure we didn't overflow
if int64(length) != length64 {
// Ensure we didn't overflow or wrap negative. Length octets are unsigned
// (x.600, 8.1.3.5), so a negative result is unrepresentable, not indefinite.
if length < 0 || uint64(length) != length64 {
return 0, read, errors.New("long-form length overflow")
}
+1
View File
@@ -221,6 +221,7 @@ type Router interface {
Patch(pattern string, h http.HandlerFunc)
Post(pattern string, h http.HandlerFunc)
Put(pattern string, h http.HandlerFunc)
Query(pattern string, h http.HandlerFunc)
Trace(pattern string, h http.HandlerFunc)
// NotFound defines a handler to respond whenever a route could
+1
View File
@@ -102,6 +102,7 @@ type Router interface {
Patch(pattern string, h http.HandlerFunc)
Post(pattern string, h http.HandlerFunc)
Put(pattern string, h http.HandlerFunc)
Query(pattern string, h http.HandlerFunc)
Trace(pattern string, h http.HandlerFunc)
// NotFound defines a handler to respond whenever a route could
+2
View File
@@ -23,6 +23,8 @@ var defaultCompressibleContentTypes = []string{
"application/json",
"application/atom+xml",
"application/rss+xml",
"application/xml",
"text/xml",
"image/svg+xml",
}
+1 -1
View File
@@ -166,7 +166,7 @@ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed t
}
func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
PrintPrettyStack(v)
printPrettyStack(v, l.useColor)
}
func init() {
-1
View File
@@ -1,5 +1,4 @@
//go:build !tinygo
// +build !tinygo
package middleware
+9 -3
View File
@@ -52,9 +52,16 @@ func Recoverer(next http.Handler) http.Handler {
var recovererErrorWriter io.Writer = os.Stderr
func PrintPrettyStack(rvr interface{}) {
printPrettyStack(rvr, true)
}
// printPrettyStack prints a formatted stack trace to stderr. When useColor is
// false, ANSI colour codes are suppressed, which is useful for terminals that
// do not support them (e.g. on Windows) or when output is being captured.
func printPrettyStack(rvr interface{}, useColor bool) {
debugStack := debug.Stack()
s := prettyStack{}
out, err := s.parse(debugStack, rvr)
out, err := s.parse(debugStack, rvr, useColor)
if err == nil {
recovererErrorWriter.Write(out)
} else {
@@ -66,9 +73,8 @@ func PrintPrettyStack(rvr interface{}) {
type prettyStack struct {
}
func (s prettyStack) parse(debugStack []byte, rvr interface{}) ([]byte, error) {
func (s prettyStack) parse(debugStack []byte, rvr interface{}, useColor bool) ([]byte, error) {
var err error
useColor := true
buf := &bytes.Buffer{}
cW(buf, false, bRed, "\n")
+6 -4
View File
@@ -207,10 +207,12 @@ func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error {
}
func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) {
if f.basicWriter.tee != nil {
// Route through basicWriter.Write so that data is also written to the
// tee writer. basicWriter.Write already increments basicWriter.bytes,
// so we must NOT add n again here (that would double-count).
if f.basicWriter.tee != nil || f.basicWriter.discard {
// Route through basicWriter.Write so that the tee and discard semantics
// are honored (the fast ReaderFrom path below would bypass both, writing
// straight to the original ResponseWriter). basicWriter.Write already
// increments basicWriter.bytes, so we must NOT add n again here (that
// would double-count).
n, err := io.Copy(&f.basicWriter, r)
return n, err
}
+6
View File
@@ -186,6 +186,12 @@ func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc) {
mx.handle(mPUT, pattern, handlerFn)
}
// Query adds the route `pattern` that matches a QUERY http method to
// execute the `handlerFn` http.HandlerFunc.
func (mx *Mux) Query(pattern string, handlerFn http.HandlerFunc) {
mx.handle(mQUERY, pattern, handlerFn)
}
// Trace adds the route `pattern` that matches a TRACE http method to
// execute the `handlerFn` http.HandlerFunc.
func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc) {
+9 -1
View File
@@ -26,11 +26,17 @@ const (
mPATCH
mPOST
mPUT
mQUERY
mTRACE
)
var mALL = mCONNECT | mDELETE | mGET | mHEAD |
mOPTIONS | mPATCH | mPOST | mPUT | mTRACE
mOPTIONS | mPATCH | mPOST | mPUT | mQUERY | mTRACE
// methodQuery is the HTTP QUERY method (RFC 10008), a safe, idempotent
// method that conveys a request body. It is defined here until net/http
// provides an equivalent constant, at which point this is a 1-1 swap.
const methodQuery = "QUERY"
var methodMap = map[string]methodTyp{
http.MethodConnect: mCONNECT,
@@ -41,6 +47,7 @@ var methodMap = map[string]methodTyp{
http.MethodPatch: mPATCH,
http.MethodPost: mPOST,
http.MethodPut: mPUT,
methodQuery: mQUERY,
http.MethodTrace: mTRACE,
}
@@ -53,6 +60,7 @@ var reverseMethodMap = map[methodTyp]string{
mPATCH: http.MethodPatch,
mPOST: http.MethodPost,
mPUT: http.MethodPut,
mQUERY: methodQuery,
mTRACE: http.MethodTrace,
}
+3
View File
@@ -83,6 +83,9 @@ func (l *Conn) Add(addRequest *AddRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationAddResponse {
err := GetLDAPError(packet)
if err != nil {
+61 -16
View File
@@ -3,13 +3,13 @@ package ldap
import (
"bytes"
"crypto/md5"
"crypto/rand"
"encoding/binary"
"encoding/hex"
enchex "encoding/hex"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"strings"
"unicode/utf16"
@@ -221,12 +221,15 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
}
if len(params) > 0 {
resp := computeResponse(
resp, err := computeResponse(
params,
"ldap/"+strings.ToLower(digestMD5BindRequest.Host),
digestMD5BindRequest.Username,
digestMD5BindRequest.Password,
)
if err != nil {
return nil, fmt.Errorf("compute digest-md5 response: %s", err)
}
packet = ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
@@ -291,12 +294,22 @@ func parseParams(str string) (map[string]string, error) {
m := make(map[string]string)
var key, value string
var state int
var escaped bool
for i := 0; i <= len(str); i++ {
switch state {
case 0: // reading key
if i == len(str) {
return nil, fmt.Errorf("syntax error on %d", i)
}
// The digest-challenge is an RFC 2068 #rule (RFC 2831 section 2.1.1),
// which permits optional linear whitespace around the comma directive
// separators. Directive names are tokens that never contain
// whitespace, so skip it here; otherwise a directive following
// "..., name" is keyed with a leading space and the lookups in
// computeResponse (realm, nonce, authzid) miss it.
if str[i] == ' ' || str[i] == '\t' {
continue
}
if str[i] != '=' {
key += string(str[i])
continue
@@ -307,6 +320,14 @@ func parseParams(str string) (map[string]string, error) {
m[key] = value
break
}
// Linear whitespace outside a quoted string is not part of the
// value: an unquoted value is a token and a quoted value's content
// is read in the quoted state below. Skipping it lets a challenge
// using the whitespace the #rule allows (e.g. `nonce="n" , qop=auth`)
// parse the same as the unspaced form.
if str[i] == ' ' || str[i] == '\t' {
continue
}
switch str[i] {
case ',':
m[key] = value
@@ -325,20 +346,34 @@ func parseParams(str string) (map[string]string, error) {
if i == len(str) {
return nil, fmt.Errorf("syntax error on %d", i)
}
if str[i] != '"' {
switch {
case escaped:
// RFC 2831 section 7.1 quoted-pair: a backslash escapes the
// following character, so the next byte is taken literally
// (this is how a server sends a literal " or \ in a realm or
// nonce).
value += string(str[i])
} else {
escaped = false
case str[i] == '\\':
escaped = true
case str[i] == '"':
state = 1
default:
value += string(str[i])
}
}
}
return m, nil
}
func computeResponse(params map[string]string, uri, username, password string) string {
func computeResponse(params map[string]string, uri, username, password string) (string, error) {
nc := "00000001"
qop := "auth"
cnonce := enchex.EncodeToString(randomBytes(16))
rb, err := randomBytes(16)
if err != nil {
return "", err
}
cnonce := enchex.EncodeToString(rb)
x := username + ":" + params["realm"] + ":" + password
y := md5Hash([]byte(x))
@@ -361,14 +396,24 @@ func computeResponse(params map[string]string, uri, username, password string) s
resp := enchex.EncodeToString(md5Hash([]byte(kd)))
return fmt.Sprintf(
`username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`,
username,
params["realm"],
params["nonce"],
quotedStringEscape(username),
quotedStringEscape(params["realm"]),
quotedStringEscape(params["nonce"]),
cnonce,
qop,
uri,
quotedStringEscape(uri),
resp,
)
), nil
}
// quotedStringEscape escapes the two characters that may not appear unescaped
// inside a DIGEST-MD5 quoted string per RFC 2831 section 7.1: the backslash
// and the double quote. The backslash is replaced first so the quotes escaped
// afterwards are not doubled.
func quotedStringEscape(s string) string {
s = strings.ReplaceAll(s, `\`, `\\`)
s = strings.ReplaceAll(s, `"`, `\"`)
return s
}
func md5Hash(b []byte) []byte {
@@ -377,12 +422,12 @@ func md5Hash(b []byte) []byte {
return hasher.Sum(nil)
}
func randomBytes(len int) []byte {
b := make([]byte, len)
for i := 0; i < len; i++ {
b[i] = byte(rand.Intn(256))
func randomBytes(length int) ([]byte, error) {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return nil, err
}
return b
return b, nil
}
var externalBindRequest = requestFunc(func(envelope *ber.Packet) error {
+3
View File
@@ -46,6 +46,9 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
return false, err
}
if len(packet.Children) < 2 {
return false, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationCompareResponse {
err := GetLDAPError(packet)
+55 -11
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"net"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
@@ -112,7 +113,11 @@ type Conn struct {
outstandingRequests uint
messageMutex sync.Mutex
err error
// errMutex guards err only. It is a leaf lock: processMessages and reader
// record errors while another goroutine may hold messageMutex, so err must
// not share messageMutex or those writers could deadlock.
errMutex sync.Mutex
err error
}
var _ Client = &Conn{}
@@ -160,10 +165,18 @@ type DialContext struct {
func (dc *DialContext) dial(u *url.URL) (net.Conn, error) {
if u.Scheme == "ldapi" {
if u.Path == "" || u.Path == "/" {
u.Path = "/var/run/slapd/ldapi"
// RFC 4516 (and draft-chu-ldap-ldapi) put the socket path in the
// host component, percent-encoded; the path is an optional DN.
// parseLDAPURL has already decoded the host. Accept the older
// ldapi:///path form too so existing callers keep working.
path := u.Host
if path == "" {
path = u.Path
}
return dc.dialer.Dial("unix", u.Path)
if path == "" || path == "/" {
path = "/var/run/slapd/ldapi"
}
return dc.dialer.Dial("unix", path)
}
host, port, err := net.SplitHostPort(u.Host)
@@ -222,12 +235,33 @@ func DialTLS(network, addr string, config *tls.Config) (*Conn, error) {
return conn, nil
}
// parseLDAPURL parses an LDAP URL. It defers to net/url for the common
// ldap/ldaps/cldap schemes, but handles ldapi specially: the spec puts the
// unix socket path in the host, percent-encoded with %2F, and net/url rejects
// that as invalid. Pull the host out manually and decode it.
func parseLDAPURL(addr string) (*url.URL, error) {
const ldapi = "ldapi://"
if !strings.HasPrefix(addr, ldapi) {
return url.Parse(addr)
}
rest := addr[len(ldapi):]
host, path := rest, ""
if i := strings.IndexByte(rest, '/'); i >= 0 {
host, path = rest[:i], rest[i:]
}
decodedHost, err := url.PathUnescape(host)
if err != nil {
return nil, fmt.Errorf("ldapi: invalid host %q: %w", host, err)
}
return &url.URL{Scheme: "ldapi", Host: decodedHost, Path: path}, nil
}
// DialURL connects to the given ldap URL.
// The following schemas are supported: ldap://, ldaps://, ldapi://,
// and cldap:// (RFC1798, deprecated but used by Active Directory).
// On success a new Conn for the connection is returned.
func DialURL(addr string, opts ...DialOpt) (*Conn, error) {
u, err := url.Parse(addr)
u, err := parseLDAPURL(addr)
if err != nil {
return nil, NewError(ErrorNetwork, err)
}
@@ -338,11 +372,21 @@ func (l *Conn) nextMessageID() int64 {
// GetLastError returns the last recorded error from goroutines like processMessages and reader.
// Only the last recorded error will be returned.
func (l *Conn) GetLastError() error {
l.messageMutex.Lock()
defer l.messageMutex.Unlock()
l.errMutex.Lock()
defer l.errMutex.Unlock()
return l.err
}
// setError records the connection's last error. The background goroutines that
// call it (processMessages, reader, the per-request timeout helper and the
// SearchAsync worker) run concurrently with callers of GetLastError, so the
// write must take the mutex the getter reads under.
func (l *Conn) setError(err error) {
l.errMutex.Lock()
defer l.errMutex.Unlock()
l.err = err
}
// StartTLS sends the command to start a TLS session and then creates a new TLS Client
func (l *Conn) StartTLS(config *tls.Config) error {
if l.isTLS {
@@ -491,7 +535,7 @@ func (l *Conn) sendProcessMessage(message *messagePacket) bool {
func (l *Conn) processMessages() {
defer func() {
if err := recover(); err != nil {
l.err = fmt.Errorf("ldap: recovered panic in processMessages: %v", err)
l.setError(fmt.Errorf("ldap: recovered panic in processMessages: %v", err))
}
for messageID, msgCtx := range l.messageContexts {
// If we are closing due to an error, inform anyone who
@@ -541,7 +585,7 @@ func (l *Conn) processMessages() {
timer := time.NewTimer(time.Duration(requestTimeout))
defer func() {
if err := recover(); err != nil {
l.err = fmt.Errorf("ldap: recovered panic in RequestTimeout: %v", err)
l.setError(fmt.Errorf("ldap: recovered panic in RequestTimeout: %v", err))
}
timer.Stop()
@@ -563,7 +607,7 @@ func (l *Conn) processMessages() {
if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
msgCtx.sendResponse(&PacketResponse{message.Packet, nil}, time.Duration(l.getTimeout()))
} else {
l.err = fmt.Errorf("ldap: received unexpected message %d, %v", message.MessageID, l.IsClosing())
l.setError(fmt.Errorf("ldap: received unexpected message %d, %v", message.MessageID, l.IsClosing()))
l.Debug.PrintPacket(message.Packet)
}
case MessageTimeout:
@@ -590,7 +634,7 @@ func (l *Conn) reader() {
cleanstop := false
defer func() {
if err := recover(); err != nil {
l.err = fmt.Errorf("ldap: recovered panic in reader: %v", err)
l.setError(fmt.Errorf("ldap: recovered panic in reader: %v", err))
}
if !cleanstop {
l.Close()
+84 -27
View File
@@ -565,12 +565,20 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
case 1:
// just type, no criticality or value
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
ControlType = packet.Children[0].Value.(string)
ct, ok := packet.Children[0].Value.(string)
if !ok {
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
}
ControlType = ct
case 2:
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
if packet.Children[0].Value != nil {
ControlType = packet.Children[0].Value.(string)
ct, ok := packet.Children[0].Value.(string)
if !ok {
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
}
ControlType = ct
} else if packet.Children[0].Data != nil {
ControlType = packet.Children[0].Data.String()
} else {
@@ -579,9 +587,9 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
// Children[1] could be criticality or value (both are optional)
// duck-type on whether this is a boolean
if _, ok := packet.Children[1].Value.(bool); ok {
if crit, ok := packet.Children[1].Value.(bool); ok {
packet.Children[1].Description = "Criticality"
Criticality = packet.Children[1].Value.(bool)
Criticality = crit
} else {
packet.Children[1].Description = "Control Value"
value = packet.Children[1]
@@ -589,10 +597,18 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
case 3:
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
ControlType = packet.Children[0].Value.(string)
ct, ok := packet.Children[0].Value.(string)
if !ok {
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
}
ControlType = ct
packet.Children[1].Description = "Criticality"
Criticality = packet.Children[1].Value.(bool)
crit, ok := packet.Children[1].Value.(bool)
if !ok {
return nil, fmt.Errorf("criticality is not a bool: %T", packet.Children[1].Value)
}
Criticality = crit
packet.Children[2].Description = "Control Value"
value = packet.Children[2]
@@ -606,6 +622,9 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
case ControlTypeManageDsaIT:
return NewControlManageDsaIT(Criticality), nil
case ControlTypePaging:
if value == nil {
return nil, fmt.Errorf("paging control value is missing")
}
value.Description += " (Paging)"
c := new(ControlPaging)
if value.Value != nil {
@@ -617,11 +636,21 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
value.Value = nil
value.AppendChild(valueChildren)
}
if len(value.Children) == 0 {
return nil, fmt.Errorf("paging control value is empty")
}
value = value.Children[0]
value.Description = "Search Control Value"
if len(value.Children) < 2 {
return nil, fmt.Errorf("paging control value has %d children, expected 2", len(value.Children))
}
value.Children[0].Description = "Paging Size"
value.Children[1].Description = "Cookie"
c.PagingSize = uint32(value.Children[0].Value.(int64))
pagingSize, ok := value.Children[0].Value.(int64)
if !ok {
return nil, fmt.Errorf("paging size is not an integer: %T", value.Children[0].Value)
}
c.PagingSize = uint32(pagingSize)
c.Cookie = value.Children[1].Data.Bytes()
value.Children[1].Value = c.Cookie
return c, nil
@@ -729,7 +758,16 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
c.ControlType = ControlType
c.Criticality = Criticality
if value != nil {
c.ControlValue = value.Value.(string)
// A non-conforming or malicious server can send a non-string
// (or nil) value here; the previous unchecked cast panicked
// the calling goroutine, see #561. Fall back to the raw bytes
// when the value isn't a string so we surface an error
// instead of crashing.
if s, ok := value.Value.(string); ok {
c.ControlValue = s
} else if value.Data != nil {
c.ControlValue = value.Data.String()
}
}
return c, nil
}
@@ -921,28 +959,44 @@ func (c *ControlServerSideSorting) GetControlType() string {
}
func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error) {
sortKeys := []*SortKey{}
val, err := ber.DecodePacketErr(value.Data.Bytes())
if err != nil {
return nil, fmt.Errorf("decode packet err: %s", err)
}
val := value.Children[1].Children
if len(val) != 1 {
if len(val.Children) == 0 {
return nil, fmt.Errorf("no sequence value in packet")
}
sequences := val[0].Children
var sortKeys []*SortKey
for i, sequence := range sequences {
sortKey := new(SortKey)
if len(sequence.Children) < 2 {
return nil, fmt.Errorf("attributeType or matchingRule is missing from sequence %d", i)
for i, sequence := range val.Children {
if len(sequence.Children) < 1 || len(sequence.Children) > 3 {
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
}
sortKey.AttributeType = sequence.Children[0].Value.(string)
sortKey.MatchingRule = sequence.Children[1].Value.(string)
sortKey := new(SortKey)
if len(sequence.Children) == 3 {
sortKey.Reverse = sequence.Children[2].Value.(bool)
for _, child := range sequence.Children {
switch {
case child.ClassType == ber.ClassUniversal && child.Tag == ber.TagOctetString:
// A constructed-form OCTET STRING matches this case but leaves
// Value nil; guard the assertion so a malformed attributeType is
// rejected below rather than panicking.
if attrType, ok := child.Value.(string); ok {
sortKey.AttributeType = attrType
}
case child.ClassType == ber.ClassContext && child.Tag == 0:
sortKey.MatchingRule = child.Data.String()
case child.ClassType == ber.ClassContext && child.Tag == 1:
b := child.Data.Bytes()
sortKey.Reverse = len(b) > 0 && b[0] != 0
}
}
if sortKey.AttributeType == "" {
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
}
sortKeys = append(sortKeys, sortKey)
@@ -959,7 +1013,6 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
control := ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, c.GetControlType(), "Control Type")
value := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Control Value")
seqs := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "SortKeyList")
for _, f := range c.SortKeys {
@@ -968,9 +1021,11 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
seq.AppendChild(
ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, f.AttributeType, "attributeType"),
)
seq.AppendChild(
ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, f.MatchingRule, "orderingRule"),
)
if f.MatchingRule != "" {
seq.AppendChild(
ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, f.MatchingRule, "orderingRule"),
)
}
if f.Reverse {
seq.AppendChild(
ber.NewBoolean(ber.ClassContext, ber.TypePrimitive, 1, f.Reverse, "reverseOrder"),
@@ -980,7 +1035,7 @@ func (c *ControlServerSideSorting) Encode() *ber.Packet {
seqs.AppendChild(seq)
}
value.AppendChild(seqs)
value := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, string(seqs.Bytes()), "Control Value")
packet.AppendChild(control)
packet.AppendChild(value)
@@ -1060,6 +1115,8 @@ func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSorti
return nil, err
}
control.Result = ControlServerSideSortingCode(codeInt)
return control, nil
}
+3
View File
@@ -52,6 +52,9 @@ func (l *Conn) Del(delRequest *DelRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationDelResponse {
err := GetLDAPError(packet)
if err != nil {
+54 -7
View File
@@ -1,14 +1,16 @@
package ldap
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
ber "github.com/go-asn1-ber/asn1-ber"
"sort"
"strings"
"unicode"
"unicode/utf8"
ber "github.com/go-asn1-ber/asn1-ber"
)
// AttributeTypeAndValue represents an attributeTypeAndValue from https://tools.ietf.org/html/rfc4514
@@ -94,9 +96,21 @@ func (d *DN) String() string {
func stripLeadingAndTrailingSpaces(inVal string) string {
noSpaces := strings.Trim(inVal, " ")
// Re-add the trailing space if it was an escaped space
if len(noSpaces) > 0 && noSpaces[len(noSpaces)-1] == '\\' && inVal[len(inVal)-1] == ' ' {
noSpaces = noSpaces + " "
// Re-add the trailing space only if it was escaped. A trailing space is
// escaped when it is preceded by an odd number of backslashes; an even
// number leaves the space unescaped (each "\\" is a literal backslash), so
// the space is insignificant and stays stripped. Counting only the final
// backslash treated "\\ " (a literal backslash plus an insignificant
// space) as an escaped space, keeping a spurious trailing space in the
// decoded value.
if len(noSpaces) > 0 && inVal[len(inVal)-1] == ' ' {
backslashes := 0
for i := len(noSpaces) - 1; i >= 0 && noSpaces[i] == '\\'; i-- {
backslashes++
}
if backslashes%2 == 1 {
noSpaces = noSpaces + " "
}
}
return noSpaces
@@ -116,6 +130,16 @@ func decodeString(str string) (string, error) {
// If the character is not an escape character, just add it to the
// builder and continue
if char != '\\' {
// RFC 4514 section 2.4: these characters must appear escaped
// (either as "\X" or as "\XX" hex) when present in an AttributeValue.
// Reject the raw form here so that callers don't silently accept
// input that violates the grammar.
switch char {
case '"', ';', '<', '>':
return "", fmt.Errorf("got unescaped character: '%s'", string(char))
case 0:
return "", fmt.Errorf("got unescaped NULL character")
}
builder.WriteRune(char)
continue
}
@@ -233,10 +257,18 @@ func decodeEncodedString(str string) (string, error) {
return "", fmt.Errorf("failed to decode BER encoding: %w", err)
}
packet, err := ber.DecodePacketErr(decoded)
// RFC 4514 section 2.4: the value following '#' is the hex encoding of the
// BER encoding of a single AttributeValue. Read exactly one element and
// reject any leftover octets, otherwise bytes appended after the value are
// silently dropped and two different DN strings decode to the same value.
reader := bytes.NewBuffer(decoded)
packet, err := ber.ReadPacket(reader)
if err != nil {
return "", fmt.Errorf("failed to decode BER encoding: %w", err)
}
if reader.Len() != 0 {
return "", errors.New("failed to decode BER encoding: trailing bytes after value")
}
return packet.Data.String(), nil
}
@@ -352,10 +384,19 @@ func (r *RelativeDN) Equal(other *RelativeDN) bool {
}
func (r *RelativeDN) hasAllAttributes(attrs []*AttributeTypeAndValue) bool {
// Each candidate attribute must match a distinct attribute of the receiver.
// Without consuming matches this is a set containment test, so a multi-valued
// RDN that repeats an attributeTypeAndValue would compare equal to one that
// repeats a different pair the same number of times.
matched := make([]bool, len(r.Attributes))
for _, attr := range attrs {
found := false
for _, myattr := range r.Attributes {
for i, myattr := range r.Attributes {
if matched[i] {
continue
}
if myattr.Equal(attr) {
matched[i] = true
found = true
break
}
@@ -415,10 +456,16 @@ func (r *RelativeDN) EqualFold(other *RelativeDN) bool {
}
func (r *RelativeDN) hasAllAttributesFold(attrs []*AttributeTypeAndValue) bool {
// See hasAllAttributes: matches are consumed so multiplicity is respected.
matched := make([]bool, len(r.Attributes))
for _, attr := range attrs {
found := false
for _, myattr := range r.Attributes {
for i, myattr := range r.Attributes {
if matched[i] {
continue
}
if myattr.EqualFold(attr) {
matched[i] = true
found = true
break
}
+8
View File
@@ -89,6 +89,14 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
}
for _, child := range extResp.Children {
// responseName [10] and responseValue [11] are context-class and
// optional. The preceding resultCode is a universal ENUMERATED whose
// tag number (10) is the same as responseName, so a child must be
// matched on its class as well, otherwise the resultCode is read as
// the responseName whenever the server omits the latter.
if child.ClassType != ber.ClassContext {
continue
}
switch child.Tag {
case ber.TagEnumerated:
response.Name = child.Data.String()
+8 -8
View File
@@ -131,7 +131,7 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
buf.WriteString(childStr)
case FilterSubstrings:
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
buf.WriteByte('=')
for i, child := range packet.Children[1].Children {
if i == 0 && child.Tag != FilterSubstringsInitial {
@@ -143,22 +143,22 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
}
}
case FilterEqualityMatch:
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
buf.WriteByte('=')
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
case FilterGreaterOrEqual:
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
buf.WriteString(">=")
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
case FilterLessOrEqual:
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
buf.WriteString("<=")
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
case FilterPresent:
buf.WriteString(ber.DecodeString(packet.Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Data.Bytes())))
buf.WriteString("=*")
case FilterApproxMatch:
buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[0].Data.Bytes())))
buf.WriteString("~=")
buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
case FilterExtensibleMatch:
@@ -181,14 +181,14 @@ func DecompileFilter(packet *ber.Packet) (_ string, err error) {
}
if len(attr) > 0 {
buf.WriteString(attr)
buf.WriteString(EscapeFilter(attr))
}
if dnAttributes {
buf.WriteString(":dn")
}
if len(matchingRule) > 0 {
buf.WriteString(":")
buf.WriteString(matchingRule)
buf.WriteString(EscapeFilter(matchingRule))
}
buf.WriteString(":=")
buf.WriteString(EscapeFilter(value))
+3
View File
@@ -89,6 +89,9 @@ func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationModifyDNResponse {
err := GetLDAPError(packet)
if err != nil {
+7
View File
@@ -121,6 +121,9 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationModifyResponse {
err := GetLDAPError(packet)
if err != nil {
@@ -159,6 +162,10 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
return nil, err
}
if len(packet.Children) < 2 {
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
switch packet.Children[1].Tag {
case ApplicationModifyResponse:
if err = GetLDAPError(packet); err != nil {
+7 -1
View File
@@ -93,6 +93,9 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
result := &PasswordModifyResult{}
if len(packet.Children) < 2 {
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
}
if packet.Children[1].Tag == ApplicationExtendedResponse {
if err = GetLDAPError(packet); err != nil {
result.Referral = getReferral(err, packet)
@@ -106,7 +109,10 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
extendedResponse := packet.Children[1]
for _, child := range extendedResponse.Children {
if child.Tag == ber.TagEmbeddedPDV {
passwordModifyResponseValue := ber.DecodePacket(child.Data.Bytes())
passwordModifyResponseValue, err := ber.DecodePacketErr(child.Data.Bytes())
if err != nil {
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %s", err)
}
if len(passwordModifyResponseValue.Children) == 1 {
if passwordModifyResponseValue.Children[0].Tag == ber.TagEOC {
result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
+8
View File
@@ -101,6 +101,14 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
continue
}
// A Referral is a SEQUENCE SIZE (1..MAX) OF uri, but a non-conforming or
// malicious server can send an empty SEQUENCE. Skip it instead of indexing
// child.Children[0], which would panic the goroutine that called Modify or
// PasswordModify.
if len(child.Children) == 0 {
continue
}
if referral, ok = child.Children[0].Value.(string); ok {
return referral
}
+40 -16
View File
@@ -66,12 +66,28 @@ func (r *searchResponse) Next() bool {
return true
}
// send enqueues a result on the result channel, giving up when ctx is
// cancelled so an abandoned consumer cannot block the search goroutine
// forever on a full buffer. It reports whether the result was handed off to
// the channel; a true return does not mean the consumer received it. The
// give-up is best-effort: if ctx is already cancelled but buffer space is
// available, the result may still be enqueued. Callers that terminate the
// stream regardless of the outcome may ignore the return value.
func (r *searchResponse) send(ctx context.Context, res *SearchSingleResult) bool {
select {
case r.ch <- res:
return true
case <-ctx.Done():
return false
}
}
func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest) {
go func() {
defer func() {
close(r.ch)
if err := recover(); err != nil {
r.conn.err = fmt.Errorf("ldap: recovered panic in searchResponse: %v", err)
r.conn.setError(fmt.Errorf("ldap: recovered panic in searchResponse: %v", err))
}
}()
@@ -84,14 +100,14 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
// encode search request
err := searchRequest.appendTo(packet)
if err != nil {
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
r.conn.Debug.PrintPacket(packet)
msgCtx, err := r.conn.sendMessage(packet)
if err != nil {
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
defer r.conn.finishMessage(msgCtx)
@@ -106,19 +122,19 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
case packetResponse, ok := <-msgCtx.responses:
if !ok {
err := NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
packet, err = packetResponse.ReadPacket()
r.conn.Debug.Printf("%d: got response %p", msgCtx.id, packet)
if err != nil {
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
if r.conn.Debug {
if err := addLDAPDescriptions(packet); err != nil {
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
ber.PrintPacket(packet)
@@ -133,22 +149,26 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
},
}
if len(packet.Children) != 3 {
r.ch <- result
if !r.send(ctx, result) {
return
}
continue
}
decoded, err := DecodeControl(packet.Children[2].Children[0])
if err != nil {
werr := fmt.Errorf("failed to decode search result entry: %w", err)
result.Error = werr
r.ch <- result
r.send(ctx, result)
return
}
result.Controls = append(result.Controls, decoded)
r.ch <- result
if !r.send(ctx, result) {
return
}
case ApplicationSearchResultDone:
if err := GetLDAPError(packet); err != nil {
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
if len(packet.Children) == 3 {
@@ -157,33 +177,37 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
decodedChild, err := DecodeControl(child)
if err != nil {
werr := fmt.Errorf("failed to decode child control: %w", err)
r.ch <- &SearchSingleResult{Error: werr}
r.send(ctx, &SearchSingleResult{Error: werr})
return
}
result.Controls = append(result.Controls, decodedChild)
}
r.ch <- result
r.send(ctx, result)
}
foundSearchSingleResultDone = true
case ApplicationSearchResultReference:
ref := packet.Children[1].Children[0].Value.(string)
r.ch <- &SearchSingleResult{Referral: ref}
if !r.send(ctx, &SearchSingleResult{Referral: ref}) {
return
}
case ApplicationIntermediateResponse:
decoded, err := DecodeControl(packet.Children[1])
if err != nil {
werr := fmt.Errorf("failed to decode intermediate response: %w", err)
r.ch <- &SearchSingleResult{Error: werr}
r.send(ctx, &SearchSingleResult{Error: werr})
return
}
result := &SearchSingleResult{}
result.Controls = append(result.Controls, decoded)
r.ch <- result
if !r.send(ctx, result) {
return
}
default:
err := fmt.Errorf("unknown tag: %d", packet.Children[1].Tag)
r.ch <- &SearchSingleResult{Error: err}
r.send(ctx, &SearchSingleResult{Error: err})
return
}
}
+6 -2
View File
@@ -624,7 +624,10 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
// SearchAsync performs a search request and returns all search results asynchronously.
// This means you get all results until an error happens (or the search successfully finished),
// e.g. for size / time limited requests all are received until the limit is reached.
// To stop the search, call cancel function of the context.
// To stop the search, call the cancel function of the context; Next may
// still deliver a few results received before the cancellation took effect.
// Cancellation is not reported as an error: Err returns nil, same as a
// successfully completed search.
func (l *Conn) SearchAsync(
ctx context.Context, searchRequest *SearchRequest, bufferSize int) Response {
r := newSearchResponse(l, bufferSize)
@@ -635,7 +638,8 @@ func (l *Conn) SearchAsync(
// Syncrepl is a short name for LDAP Sync Replication engine that works on the
// consumer-side. This can perform a persistent search and returns an entry
// when the entry is updated on the server side.
// To stop the search, call cancel function of the context.
// To stop the search, call the cancel function of the context; cancellation
// is not reported as an error, Err returns nil.
func (l *Conn) Syncrepl(
ctx context.Context, searchRequest *SearchRequest, bufferSize int,
mode ControlSyncRequestMode, cookie []byte, reloadHint bool,
+8 -1
View File
@@ -24,11 +24,18 @@ func (l *Conn) Unbind() error {
return ErrConnUnbound
}
_, err := l.doRequest(unbindRequest{})
msgCtx, err := l.doRequest(unbindRequest{})
if err != nil {
return err
}
// Finish the message context so its done channel is closed. Without
// this, a server-initiated disconnect racing with Close can deadlock:
// processMessages cleanup tries to deliver closeErr to the orphaned
// context via sendResponse, which blocks forever on the unclosed done
// channel, preventing chanConfirm from being signalled.
l.finishMessage(msgCtx)
// Sending an unbindRequest will make the connection unusable.
// Pending requests will fail with:
// LDAP Result Code 200 "Network Error": ldap: response channel closed
+7 -1
View File
@@ -19,5 +19,11 @@ func (l *Conn) WhoAmI(controls []Control) (*WhoAmIResult, error) {
return nil, err
}
return &WhoAmIResult{AuthzID: resp.Value.Data.String()}, nil
// responseValue is OPTIONAL (RFC 4532); Extended leaves Value nil when the
// server omits it. Guard the dereference and report an empty authzId.
result := &WhoAmIResult{}
if resp.Value != nil {
result.AuthzID = resp.Value.Data.String()
}
return result, nil
}
+1 -1
View File
@@ -5,7 +5,7 @@ import os
import subprocess
VERSION = "1.8.22"
VERSION = "1.8.23"
def run(*args: str):
+30 -6
View File
@@ -5,6 +5,7 @@
package webp
import (
"bufio"
"bytes"
"errors"
"image"
@@ -123,16 +124,39 @@ func decode(r io.Reader, configOnly bool) (image.Image, image.Config, error) {
c, err := vp8l.DecodeConfig(chunkData)
return nil, c, err
}
if seenVP8X {
// Verify the VP8L chunk dimensions match before
// calling vp8l.Decode, to catch malicious images
// following a small VP8X header with a huge VP8L chunk.
//
// Peek the VP8L header.
//
// chunkData is always an unbuffered riff.chunkReader.
// Creating a bufio.Reader here doesn't add any
// inefficiency, since the vp8l package will do it
// if we don't.
bufReader := bufio.NewReader(chunkData)
chunkData = bufReader
const vp8lHeaderSize = 5
vp8lHeader, err := bufReader.Peek(vp8lHeaderSize)
if err != nil {
if err == io.EOF {
err = errInvalidFormat
}
return nil, image.Config{}, err
}
c, err := vp8l.DecodeConfig(bytes.NewReader(vp8lHeader))
if err != nil {
return nil, image.Config{}, err
}
if c.Width != int(widthMinusOne)+1 || c.Height != int(heightMinusOne)+1 {
return nil, image.Config{}, errInvalidFormat
}
}
m, err := vp8l.Decode(chunkData)
if err != nil {
return nil, image.Config{}, err
}
if seenVP8X {
bounds := m.Bounds()
if bounds.Dx() != int(widthMinusOne)+1 || bounds.Dy() != int(heightMinusOne)+1 {
return nil, image.Config{}, errInvalidFormat
}
}
return m, image.Config{}, nil
case fccVP8X:
if seenVP8X {
@@ -452,6 +452,8 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
st = status.NewFailedPrecondition(ctx, err, "failed precondition")
case errtypes.Locked:
st = status.NewLocked(ctx, "locked")
case errtypes.IsTooEarly:
st = status.NewTooEarly(ctx, err.Error())
default:
st = status.NewInternal(ctx, "error getting upload id: "+err.Error())
}
@@ -275,6 +275,9 @@ func handleError(w http.ResponseWriter, log *zerolog.Logger, err error, action s
case errtypes.Aborted:
log.Debug().Err(err).Str("action", action).Msg("etags do not match")
w.WriteHeader(http.StatusPreconditionFailed)
case errtypes.IsResourceProcessing, errtypes.IsTooEarly:
log.Debug().Err(err).Str("action", action).Msg("resource is processing")
w.WriteHeader(http.StatusTooEarly)
default:
log.Error().Err(err).Str("action", action).Msg("unexpected error")
w.WriteHeader(http.StatusInternalServerError)
@@ -100,7 +100,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer unlock()
if _, ok := c.ReceivedSpaces.Load(userID); !ok {
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return err
}
@@ -110,7 +110,7 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -125,56 +125,12 @@ func (c *Cache) Add(ctx context.Context, userID, spaceID string, rs *collaborati
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -187,7 +143,7 @@ func (c *Cache) Get(ctx context.Context, userID, spaceID, shareID string) (*Stat
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -206,11 +162,11 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
span.SetAttributes(attribute.String("cs3.userid", userID))
defer unlock()
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Add")
ctx, span = appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Remove")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID), attribute.String("cs3.spaceid", spaceID))
persistFunc := func() error {
err := c.retryPersist(ctx, userID, spaceID, func() error {
c.initializeIfNeeded(userID, spaceID)
rss, _ := c.ReceivedSpaces.Load(userID)
@@ -224,56 +180,12 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
}
return c.persist(ctx, userID)
}
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
span.SetStatus(codes.Ok, "")
return nil
case errtypes.Aborted:
log.Debug().Msg("aborted when persisting added received share: etag changed. retrying...")
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
case errtypes.PreconditionFailed:
log.Debug().Msg("precondition failed when persisting added received share: etag changed. retrying...")
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
case errtypes.AlreadyExists:
log.Debug().Msg("already exists when persisting added received share. retrying...")
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
default:
span.SetStatus(codes.Error, fmt.Sprintf("persisting added received share failed. giving up: %s", err.Error()))
log.Error().Err(err).Msg("persisting added received share failed")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if err := c.syncWithLock(ctx, userID); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
log.Error().Err(err).Msg("persisting added received share failed. giving up.")
return err
}
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
@@ -281,13 +193,14 @@ func (c *Cache) Remove(ctx context.Context, userID, spaceID, shareID string) err
// List returns a list of received shares for a given user
// The return list is guaranteed to be thread-safe
func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, error) {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Grab lock")
unlock := c.lockUser(userID)
span.End()
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "List")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
unlock := c.lockUser(userID)
defer unlock()
err := c.syncWithLock(ctx, userID)
err := c.syncIfStale(ctx, userID)
if err != nil {
return nil, err
}
@@ -310,8 +223,71 @@ func (c *Cache) List(ctx context.Context, userID string) (map[string]*Space, err
return spaces, nil
}
func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "Sync")
func isSyncTransient(err error) bool {
_, isTooEarly := err.(errtypes.IsTooEarly)
_, isInternal := err.(errtypes.IsInternalError)
return isTooEarly || isInternal
}
func (c *Cache) retryPersist(ctx context.Context, userID, spaceID string, persistFunc func() error) error {
log := appctx.GetLogger(ctx).With().
Str("hostname", os.Getenv("HOSTNAME")).
Str("userID", userID).
Str("spaceID", spaceID).Logger()
var err error
for attempt := 0; attempt < 20; attempt++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err = persistFunc()
switch err.(type) {
case nil:
return nil
case errtypes.Aborted:
// this is the expected status code from the server when the if-match etag check fails
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: Aborted (etag changed), retrying")
case errtypes.PreconditionFailed:
// actually, this is the wrong status code and we treat it like errtypes.Aborted because of inconsistencies on the server side
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: PreconditionFailed (etag changed), retrying")
case errtypes.AlreadyExists:
// CS3 uses an already exists error instead of precondition failed when using an If-None-Match=* header / IfExists flag in the InitiateFileUpload call.
// Thas happens when the cache thinks there is no file.
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: AlreadyExists (file created concurrently), retrying")
case errtypes.TooEarly:
// storage-system has an upload in progress for this node; wait for it to finish
// continue with sync below
log.Debug().Int("attempt", attempt).Msg("CAS failed: TooEarly (upload in progress), retrying")
default:
log.Error().Int("attempt", attempt).Err(err).Msg("persisting received share failed, giving up")
return err
}
timer := time.NewTimer(expBackoff(attempt))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
return ctx.Err()
}
if serr := c.syncIfStale(ctx, userID); serr != nil {
if !isSyncTransient(serr) {
log.Error().Int("attempt", attempt).Err(serr).Msg("lost update: re-read failed, aborting")
return serr
}
log.Warn().Int("attempt", attempt).Err(serr).Msg("lost update: re-read before retry")
}
}
return err
}
// syncIfStale pulls the authoritative state from storage when the local replica is stale; caller must hold the user lock.
func (c *Cache) syncIfStale(ctx context.Context, userID string) error {
ctx, span := appctx.GetTracerProvider(ctx).Tracer(tracerName).Start(ctx, "SyncIfStale")
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
@@ -340,8 +316,12 @@ func (c *Cache) syncWithLock(ctx context.Context, userID string) error {
span.SetStatus(codes.Ok, "")
return nil
default:
span.SetStatus(codes.Error, fmt.Sprintf("Failed to download the received share: %s", err.Error()))
log.Error().Err(err).Msg("Failed to download the received share")
span.SetStatus(codes.Error, err.Error())
if isSyncTransient(err) {
log.Warn().Err(err).Msg("lost update: re-read transient error")
} else {
log.Error().Err(err).Msg("lost update: re-read failed")
}
return err
}
@@ -365,6 +345,9 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
defer span.End()
span.SetAttributes(attribute.String("cs3.userid", userID))
log := appctx.GetLogger(ctx)
log.Debug().Str("user", userID).Msg("receivedsharecache.persist.start")
rss, ok := c.ReceivedSpaces.Load(userID)
if !ok {
span.SetStatus(codes.Ok, "no received shares")
@@ -395,6 +378,7 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
ur.IfNoneMatch = []string{"*"}
}
log.Debug().Str("user", userID).Str("path", jsonPath).Str("etag", ur.IfMatchEtag).Msg("receivedsharecache.persist.upload")
res, err := c.storage.Upload(ctx, ur)
if err != nil {
span.RecordError(err)
@@ -403,6 +387,7 @@ func (c *Cache) persist(ctx context.Context, userID string) error {
}
rss.etag = res.Etag
log.Debug().Str("user", userID).Str("etag", res.Etag).Msg("receivedsharecache.persist.done")
span.SetStatus(codes.Ok, "")
return nil
}
@@ -706,6 +706,9 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
subspan.End()
if err != nil {
if errors.Is(err, fs.ErrExist) {
return unlock, errtypes.AlreadyExists(n.Name)
}
return unlock, err
}
h.Close()
@@ -136,6 +136,7 @@ func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Refere
_, span := tracer.Start(ctx, "InitiateUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Interface("ref", ref).Msg("decomposedfs:InitiateUpload:start")
// remember the path from the reference
refpath := ref.GetPath()
@@ -336,6 +337,7 @@ func (fs *Decomposedfs) InitiateUpload(ctx context.Context, ref *provider.Refere
}
}
log.Debug().Str("uploadid", session.ID()).Msg("decomposedfs:InitiateUpload:complete")
return map[string]string{
"simple": session.ID(),
"tus": session.ID(),
@@ -377,9 +379,6 @@ func (fs *Decomposedfs) MarkProcessing(ctx context.Context, ref *provider.Refere
return n.RemoveXattr(ctx, prefixes.StatusPrefix, false)
}
if n.IsProcessing(ctx) {
return errtypes.ResourceProcessing(ref.String())
}
return n.SetXattrsWithContext(ctx, node.Attributes{
prefixes.StatusPrefix: []byte(node.ProcessingStatus + sessionID),
}, false) // acquireLock=false, because outer lock already held
@@ -114,12 +114,13 @@ func (session *OcisSession) GetReader(ctx context.Context) (io.ReadCloser, error
// implements tusd.DataStore interface
// returns tusd errors
func (session *OcisSession) FinishUpload(ctx context.Context) error {
log := appctx.GetLogger(ctx)
log.Debug().Msg("decomposedfs:FinishUpload:start")
err := session.FinishUploadDecomposed(ctx)
if err != nil {
// this is part of the tusd integration and we might be able to
// log the error in another place
log := appctx.GetLogger(ctx)
log.Error().Err(err).Msg("failed to finish upload")
}
@@ -140,6 +141,7 @@ func (session *OcisSession) FinishUploadDecomposed(ctx context.Context) error {
ctx, span := tracer.Start(session.Context(ctx), "FinishUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("session", session.ID()).Msg("decomposedfs:FinishUploadDecomposed:start")
ctx = ctxpkg.ContextSetInitiator(ctx, session.InitiatorID())
@@ -246,6 +248,7 @@ func (session *OcisSession) FinishUploadDecomposed(ctx context.Context) error {
metrics.UploadSessionsFinalized.Inc()
}
log.Debug().Str("session", session.ID()).Msg("decomposedfs:FinishUploadDecomposed:complete")
return session.store.tp.Propagate(ctx, n, session.SizeDiff())
}
+11
View File
@@ -39,6 +39,7 @@ import (
"google.golang.org/grpc/metadata"
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/owncloud/reva/v2/pkg/appctx"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
@@ -64,6 +65,7 @@ type CS3 struct {
dataGatewayClient *http.Client
}
// NewCS3 returns a new CS3 instance. Use an authenticated context and be sure to define SpaceRoot manually.
func NewCS3(gwAddr, providerAddr string) (s *CS3) {
return &CS3{
@@ -162,6 +164,8 @@ func (cs3 *CS3) SimpleUpload(ctx context.Context, uploadpath string, content []b
ctx, span := tracer.Start(ctx, "SimpleUpload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("path", uploadpath).Msg("cs3.SimpleUpload.start")
_, err := cs3.Upload(ctx, UploadRequest{
Path: uploadpath,
Content: content,
@@ -174,6 +178,9 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
ctx, span := tracer.Start(ctx, "Upload")
defer span.End()
log := appctx.GetLogger(ctx)
log.Debug().Str("path", req.Path).Msg("cs3.Upload.start")
client, err := cs3.providerClient()
if err != nil {
return nil, err
@@ -238,6 +245,8 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
return nil, errors.New("metadata storage doesn't support the simple upload protocol")
}
log.Debug().Str("path", req.Path).Str("endpoint", endpoint).Msg("cs3.Upload.initiate_done")
httpReq, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewReader(req.Content))
if err != nil {
return nil, err
@@ -253,6 +262,7 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
return nil, err
}
defer resp.Body.Close()
log.Debug().Str("path", req.Path).Int("status", resp.StatusCode).Msg("cs3.Upload.put_done")
if err := errtypes.NewErrtypeFromHTTPStatusCode(resp.StatusCode, httpReq.URL.Path); err != nil {
return nil, err
}
@@ -260,6 +270,7 @@ func (cs3 *CS3) Upload(ctx context.Context, req UploadRequest) (*UploadResponse,
if ocEtag := resp.Header.Get("OC-ETag"); ocEtag != "" {
etag = ocEtag
}
log.Debug().Str("path", req.Path).Str("etag", etag).Msg("cs3.Upload.complete")
return &UploadResponse{
Etag: etag,
FileID: resp.Header.Get("OC-Fileid"),
+18 -17
View File
@@ -17,8 +17,8 @@
// It uses data-independent memory access, which is preferred for password
// hashing and password-based key derivation. Argon2i requires more passes over
// memory than Argon2id to protect from trade-off attacks. The recommended
// parameters (taken from [RFC 9106 Section 7.3]) for non-interactive operations are time=3 and to
// use the maximum available memory.
// parameters (taken from [RFC 9106 Section 7.3]) for non-interactive
// operations are time=3 and to use the maximum available memory.
//
// # Argon2id
//
@@ -26,11 +26,14 @@
// Argon2i and Argon2d. It uses data-independent memory access for the first
// half of the first iteration over the memory and data-dependent memory access
// for the rest. Argon2id is side-channel resistant and provides better brute-
// force cost savings due to time-memory tradeoffs than Argon2i. The recommended
// parameters for non-interactive operations (taken from [RFC 9106 Section 7.3]) are time=1 and to
// use the maximum available memory.
// force cost savings due to time-memory tradeoffs than Argon2i. [RFC 9106
// Section 4] recommends time=1, memory=2*1024*1024 KiB (2 GiB), and threads=4
// as the first recommended option. If much less memory is available, it
// recommends time=3, memory=64*1024 KiB (64 MiB), and threads=4 as the second
// recommended option.
//
// [argon2-specs.pdf]: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
// [RFC 9106 Section 4]: https://www.rfc-editor.org/rfc/rfc9106.html#section-4
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
package argon2
@@ -59,9 +62,9 @@ const (
//
// key := argon2.Key([]byte("some password"), salt, 3, 32*1024, 4, 32)
//
// [RFC 9106 Section 7.3] recommends time=3, and memory=32*1024 as a sensible number.
// If using that amount of memory (32 MB) is not possible in some contexts then
// the time parameter can be increased to compensate.
// The example above uses time=3 and memory=32*1024. Argon2i generally
// requires more passes over memory than Argon2id. If in doubt, prefer IDKey
// and its Argon2id parameter recommendations.
//
// The time parameter specifies the number of passes over the memory and the
// memory parameter specifies the size of the memory in KiB. For example
@@ -69,8 +72,6 @@ const (
// adjusted to the number of available CPUs. The cost parameters should be
// increased as memory latency and CPU parallelism increases. Remember to get a
// good random salt.
//
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
return deriveKey(argon2i, password, salt, nil, nil, time, memory, threads, keyLen)
}
@@ -83,20 +84,20 @@ func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint3
// For example, you can get a derived key for e.g. AES-256 (which needs a
// 32-byte key) by doing:
//
// key := argon2.IDKey([]byte("some password"), salt, 1, 64*1024, 4, 32)
// key := argon2.IDKey([]byte("some password"), salt, 1, 2*1024*1024, 4, 32)
//
// [RFC 9106 Section 7.3] recommends time=1, and memory=64*1024 as a sensible number.
// If using that amount of memory (64 MB) is not possible in some contexts then
// the time parameter can be increased to compensate.
// The example above uses the first [RFC 9106 Section 4] recommended option.
// If much less memory is available, the second recommended option is time=3,
// memory=64*1024 KiB (64 MiB), and threads=4.
//
// The time parameter specifies the number of passes over the memory and the
// memory parameter specifies the size of the memory in KiB. For example
// memory=64*1024 sets the memory cost to ~64 MB. The number of threads can be
// adjusted to the numbers of available CPUs. The cost parameters should be
// memory=2*1024*1024 sets the memory cost to ~2 GiB. The number of threads can
// be adjusted to the numbers of available CPUs. The cost parameters should be
// increased as memory latency and CPU parallelism increases. Remember to get a
// good random salt.
//
// [RFC 9106 Section 7.3]: https://www.rfc-editor.org/rfc/rfc9106.html#section-7.3
// [RFC 9106 Section 4]: https://www.rfc-editor.org/rfc/rfc9106.html#section-4
func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte {
return deriveKey(argon2id, password, salt, nil, nil, time, memory, threads, keyLen)
}
+2
View File
@@ -41,6 +41,7 @@ func ForwardToAgent(client *ssh.Client, keyring Agent) error {
continue
}
go ssh.DiscardRequests(reqs)
go io.Copy(io.Discard, channel.Stderr())
go func() {
ServeAgent(keyring, channel)
channel.Close()
@@ -72,6 +73,7 @@ func ForwardToRemote(client *ssh.Client, addr string) error {
continue
}
go ssh.DiscardRequests(reqs)
go io.Copy(io.Discard, channel.Stderr())
go forwardUnixSocket(channel, addr)
}
}()
+47 -6
View File
@@ -304,19 +304,60 @@ func parseEd25519Key(req []byte) (*AddedKey, error) {
return addedKey, nil
}
func checkDSAParams(param *dsa.Parameters) error {
// SSH specifies FIPS 186-2, which only provided a single size
// (1024 bits) DSA key. FIPS 186-3 allows for larger key
// sizes, which would confuse SSH.
if l := param.P.BitLen(); l != 1024 {
return fmt.Errorf("ssh: unsupported DSA key size %d", l)
}
// FIPS 186-2 specifies that Q must be exactly 160 bits. We must enforce
// this to prevent DoS attacks where an attacker sends a huge Q which makes
// verification slow.
if l := param.Q.BitLen(); l != 160 {
return fmt.Errorf("ssh: unsupported DSA sub-prime size %d", l)
}
// The generator G is an element of the group, so it must be strictly less
// than the modulus P.
if param.G.Cmp(param.P) >= 0 {
return errors.New("ssh: DSA generator larger than modulus")
}
// G must be positive.
if param.G.Sign() <= 0 {
return errors.New("ssh: DSA generator must be positive")
}
return nil
}
func parseDSAKey(req []byte) (*AddedKey, error) {
var k dsaKeyMsg
if err := ssh.Unmarshal(req, &k); err != nil {
return nil, err
}
params := dsa.Parameters{
P: k.P,
Q: k.Q,
G: k.G,
}
if err := checkDSAParams(&params); err != nil {
return nil, err
}
// The public value Y must be a non-zero element of the group, i.e. strictly
// between 0 and P, to prevent a maliciously oversized Y from slowing
// signature operations.
if k.Y.Sign() <= 0 || k.Y.Cmp(k.P) >= 0 {
return nil, errors.New("agent: DSA public value Y out of range")
}
priv := &dsa.PrivateKey{
PublicKey: dsa.PublicKey{
Parameters: dsa.Parameters{
P: k.P,
Q: k.Q,
G: k.G,
},
Y: k.Y,
Parameters: params,
Y: k.Y,
},
X: k.X,
}
+26 -10
View File
@@ -182,14 +182,19 @@ func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey
}
hosts := string(keyFields[0])
// keyFields[1] contains the key type (e.g. “ssh-rsa”).
// However, that information is duplicated inside the
// base64-encoded key and so is ignored here.
// keyFields[1] contains the key type (e.g. "ssh-rsa"). This information
// is duplicated within the base64-encoded key blob. As OpenSSH's
// sshkey_read does, we verify that the declared key type matches the
// type embedded in the key blob.
wantType := string(keyFields[1])
key := bytes.Join(keyFields[2:], []byte(" "))
if pubKey, comment, err = parseAuthorizedKey(key); err != nil {
return "", nil, nil, "", nil, err
}
if pubKey.Type() != wantType {
return "", nil, nil, "", nil, fmt.Errorf("ssh: known hosts key type mismatch: human-readable type %q, encoded type %q", wantType, pubKey.Type())
}
return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil
}
@@ -228,10 +233,17 @@ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []str
}
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
return out, comment, options, rest, nil
} else {
lastErr = err
// The first field contains the declared key type. As OpenSSH's
// sshkey_read does, we verify that it matches the type embedded in
// the key blob. Without this check, a single-token option (e.g.
// "restrict") appearing in the key type position could be silently
// discarded along with its intended effect.
if string(in[:i]) == out.Type() {
return out, comment, options, rest, nil
}
err = fmt.Errorf("ssh: authorized keys key type mismatch: human-readable type %q, encoded type %q", in[:i], out.Type())
}
lastErr = err
// No key type recognised. Maybe there's an options field at
// the beginning.
@@ -271,11 +283,15 @@ func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []str
}
if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
options = candidateOptions
return out, comment, options, rest, nil
} else {
lastErr = err
// As above, the declared key type (here following the options
// field) must match the type embedded in the key blob.
if string(in[:i]) == out.Type() {
options = candidateOptions
return out, comment, options, rest, nil
}
err = fmt.Errorf("ssh: authorized keys key type mismatch: human-readable type %q, encoded type %q", in[:i], out.Type())
}
lastErr = err
in = rest
continue
+10 -1
View File
@@ -44,7 +44,16 @@ type disconnectMsg struct {
}
func (d *disconnectMsg) Error() string {
return fmt.Sprintf("ssh: disconnect, reason %d: %s", d.Reason, d.Message)
return fmt.Sprintf("ssh: disconnect, reason %d: %q", d.Reason, sanitizeString(d.Message))
}
func sanitizeString(s string) string {
return strings.Map(func(r rune) rune {
if r == '\t' || (r >= ' ' && r < 0x7f) {
return r
}
return -1
}, s)
}
// See RFC 4253, section 7.1.
+7
View File
@@ -9,6 +9,13 @@
// implementing the golang.org/x/image/font.Face interface.
//
// The sibling golang.org/x/image/font/sfnt package provides a low-level API.
//
// # Security Considerations
//
// This package is not hardened against malicious inputs.
// Crashes, excessive CPU or memory consumption, or similar misbehavior
// caused by malicious or corrupt inputs will be handled as ordinary bugs,
// not vulnerabilities.
package opentype // import "golang.org/x/image/font/opentype"
import (
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more