Compare commits

...
Author SHA1 Message Date
Prajwol Amatya b6ca549b0e test: run oidc test suite with k8s
Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-10-12 14:16:58 +05:45
Roman PerekhodandClaude Sonnet 5 2e377bde67 fix: [OCISDEV-1476] fix AuthApp requests failing with a custom PROXY_… (#13078) (#13107)
* fix: [OCISDEV-1476] fix AuthApp requests failing with a custom PROXY_USER_OIDC_CLAIM

* fix: [OCISDEV-1476] map ErrAccountNotFound to 401 in verifyUser

AccountResolver.verifyUser only mapped ErrAccountDisabled to 401 before
falling through to a generic 500. The identity backend excludes disabled
accounts from by-username lookups and returns ErrAccountNotFound instead,
so a disabled user authenticating via AppAuth or basic auth got a 500
instead of a 401, caught by the acceptance test suite.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-09 13:37:34 +00:00
Roman PerekhodandClaude Sonnet 5 703bbe1113 fix: [OCISDEV-1523] fix the LDAP master-ID filter for an empty base filter (#13100)
* fix: [OCISDEV-1523] fix the LDAP master-ID filter for an empty base filter

EnhanceFilterWithMasterID replaced an empty LDAP filter with a master-ID-only
filter. This action restricted an unrestricted search to master-ID users
only. The bug broke the cross-instance user search in multi-instance
deployments. The function now keeps an empty filter unchanged.

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

* fix: [OCISDEV-1523] require an explicit LDAP user filter with a master ID

EnhanceFilterWithMasterID in ocis-pkg/ldap/filter.go now keeps an empty
LDAP filter unchanged instead of restricting it to master-ID users only.
The auth-basic, users, groups, and graph services reuse this function to
compute their default LDAP user filter at startup.

An unset filter now means these services resolve or authenticate every
user in the shared LDAP directory, not only master-ID users. This action
is a behavior change for a deployment that sets
OCIS_MULTI_INSTANCE_MASTER_ID without an explicit OCIS_LDAP_USER_FILTER.

Each service now rejects startup when OCIS_MULTI_INSTANCE_MASTER_ID is
set and its own user filter is empty. This action keeps a multi-instance
deployment scoped to its own users by default.

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

* refactor: [OCISDEV-1523] simplify EnhanceFilterWithMasterID guard clauses

The function collapses three early-return guards into one condition.
This action removes a duplicated rationale comment between filter.go
and filter_test.go.

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

* docs: [OCISDEV-1523] point the changelog entry at the master backport PR

The changelog entry pointed at PR 13096, the stable-8.2 backport. This
commit points the entry at the master-branch PR number instead.

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

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-09 15:27:27 +02:00
Paul FaureandClaude Opus 5.5 1347e3607d fix(proxy): don't log an error when create-home finds no user (#13102)
Requests on unprotected routes can carry a reva token without a resolved
user: reva's internal downloads to the data gateway (/data) are sent with
the caller's token. create_home logged "no user in context" at error level
for each of them, so every download added an error line. Log at debug with
the path instead; the request is passed on unchanged, as before.

Fixes #13101


Claude-Session: https://claude.ai/code/session_01WpoeSoKYEdgQcWjEzTVKpT

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:50:55 +02:00
isha 9e2a79d0f2 [full-ci][tests-only][k8s] test: run part-2 e2e suites on k8s deployment (#13037)
test: run e2e suites on k8s deployment
2026-10-09 17:08:00 +05:45
Matteo 841dd9b948 fix(web): [OCISDEV-1509] show error instead of empty message when space trash is not accessible (#13105) 2026-10-09 13:22:28 +02:00
887796c36d fix(audit): record the acting user in the audit log's User field (#13051)
The file and folder converters filled User from the event's Owner, which
reva does not set, so the field was empty on every upload, download, move,
delete, restore and version restore; where Owner was set it named the owner
instead of the actor. Space, user and group converters hard-coded User to
an empty string although every one of those events carries the Executant.

User now comes from the event's Executant everywhere an actor exists. The
Owner field of file events is unchanged; the failed public-link access
event has no actor and keeps an empty User.

Tests give the fixtures different owner and actor ids so they can tell the
two apart (they fail on the previous code), and add cases for the user and
group converters. The group member added/removed messages passed the user
and group ids in swapped order; fixed.

Fixes #4789

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Juan Pablo Villafañez <jpvillafanez@izertis.com>
2026-10-09 11:44:39 +02:00
owncloud-translations-bot[bot] 02c52130bb chore: update translations from transifex (#13103)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-09 08:25:48 +00:00
kobergjandClaude Opus 5 76a9cb8042 docs: replace envvar introductionVersion 8.3.0 with 9.0.0 (#13106)
The next oCIS release is 9.0.0, so all envvars that were annotated with
the previously planned 8.3.0 introduction version need to be updated.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-09 10:20:09 +02:00
Paul FaureandClaude Opus 5.5 b5f843e99b feat(search): add a --timeout flag to the index command (#13053)
* feat(search): add a --timeout flag to the index command

ocis search index called the search service with a hard-coded 10 minute
request timeout. The service walks the whole space inside that request, so
when the timeout expired the walk was cancelled (error walking the tree:
context canceled) and everything after that point stayed unindexed. A space
whose walk takes longer than ten minutes could never be fully indexed from
the command line.

The timeout is now a flag: --timeout takes a duration, default 10m so the
behaviour is unchanged out of the box; 0 waits indefinitely (go-micro treats
a zero RequestTimeout as an already-expired deadline, so a far-off one is
substituted).

Fixes #13052

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

* docs(search): say the index command needs the running search service

The index command is a gRPC client of the search service and never opens
the Bleve index, so it works with the default exclusive lock
(SEARCH_ENGINE_BLEVE_SCALE=false) but needs the service running.

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

---------

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 09:54:38 +02:00
Paul FaureandClaude Opus 5.5 be21f76688 feat(audit): record tag changes in the audit log (#13055)
* feat(audit): record tag changes in the audit log

Graph publishes TagsAdded and TagsRemoved on every tag assign and unassign,
but only the search service listened, so a tag change left no trace in the
audit log.

The audit service now registers both events and logs them as file_tags_add
and file_tags_remove, with the acting user (Executant), the space owner, the
file id and path, and the comma-separated tags. Graph sets the Timestamp on
both events, which it left unset. Two test cases use different owner and
actor ids; the audit README documents the two actions.

Fixes #13054

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

* fix(audit): record only the tags that actually changed; skip no-op tag events

Review follow-up for #13055:
- graph: TagsAdded/TagsRemoved now carry the tags that were actually added
  or removed (requesting an existing tag, or removing an absent one, is not
  a change). Search only uses the event's Ref, so it is unaffected.
- audit: skip tag events whose tag list is empty. Graph still publishes
  TagsRemoved for search when nothing was present; that is not an audit event.
- audit: document why User is the executant for tag events; describe Tags
  as carried by the event; remove a stray copy-pasted doc comment.

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

* fix(audit): carry the requested tags in tag events, as before

Per review: TagsAdded/TagsRemoved go back to carrying the tags as
requested, and the audit log records every request, including tags that
were already present (or absent, for a removal), so repeated requests stay
visible. Computing the actual delta belongs in the tags package, not here.

Removes the graph-side tagsDiff helper and its test, and the audit
service's skip for empty tag lists. The other review fixes stay.

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

---------

Signed-off-by: Paul Faure <paul@faure.ca>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-09 09:54:17 +02:00
Firas Frikha d90dfa7085 refactor(storage-users): [OCISDEV-1382] list upload sessions through the coordinator (#13098)
* refactor(storage-users): [OCISDEV-1382] list upload sessions through the coordinator

Signed-off-by: Firas Frikha <firas.frikha@kiteworks.com>

* fix(storage-users): [OCISDEV-1382] use a safe type assertion for the driver config

Signed-off-by: Firas Frikha <firas.frikha@kiteworks.com>

---------

Signed-off-by: Firas Frikha <firas.frikha@kiteworks.com>
2026-10-09 08:58:54 +02:00
Matteo f7453530f6 chore(web): [OCISDEV-1501] remove vault MFA session extension popup (#13085)
Remove the "Session expiring" extend/dismiss popup and its expiry
worker. Drop the frontend session_duration capability and config;
OCIS_MFA_SESSION_DURATION stays in use by the proxy.
2026-10-08 18:54:57 +02:00
Prajwol Amatya 29c01920f8 [tests-only][full-ci] test: fix flakiness in e2e-part-2 (#13092)
test: wait for password input field before A11y scan

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-10-08 14:44:02 +05:45
owncloud-translations-bot[bot] 0ffb415e89 chore: update translations from transifex (#13091)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-08 08:51:49 +02:00
LarsJurgensenandFiras Frikha cc8c1c883f ci: [k6-test] [OCISDEV-900] Extract upload coordinator out of decomposedfs (#12913)
* chore(OCISDEV-900): bump reva to pr7-switchover, add upload_directory and mount_id to revaconfig

* chore(OCISDEV-900): bump reva to the switchover rebased on the upload write fix

* chore(OCISDEV-900): bump reva to main with the upload coordinator switchover

---------

Co-authored-by: Firas Frikha <firas.frikha@kiteworks.com>
2026-10-07 18:28:34 +02:00
Michal Klos 90d58ae47d feat: [OCISDEV-1437] show suggested expiry date of 30 days (#12988) 2026-10-07 16:03:09 +02:00
145 changed files with 4167 additions and 964 deletions

No files matched your search

+36 -3
View File
@@ -447,7 +447,7 @@ jobs:
e2e-tests:
name: e2e-${{ matrix.suite }}-k8s
runs-on: ubuntu-latest
timeout-minutes: 60
timeout-minutes: 120
if: >-
github.event_name == 'schedule' ||
@@ -459,7 +459,38 @@ jobs:
fail-fast: false
matrix:
include:
- suite: smoke
# - suite: part-1
# args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc,vault-storage --run-part 1"
- suite: part-2
args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc,vault-storage --run-part 2"
# - suite: part-3
# args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc,vault-storage --run-part 3"
# - suite: part-4
# args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc,vault-storage --run-part 4"
# - suite: search
# args: "--type playwright --suites search"
# tika: true
# - suite: keycloak
# args: "--type playwright --suites journeys,keycloak"
# keycloak: true
# - suite: mfa
# args: "--type playwright --suites mfa"
# mfa: true
- suite: oidc
args: "--type playwright specs/oidc/refreshToken.spec.ts"
oidc: true
- suite: oidc-iframe
args: "--type playwright specs/oidc/iframeTokenRenewal.spec.ts"
oidc_iframe: true
# - suite: app-provider
# args: "--type playwright --suites app-provider"
# collaboration: true
# - suite: ocm
# args: "--type playwright --suites ocm"
# federated: true
# - suite: vault-storage
# args: "--type playwright --suites vault-storage"
# vault_storage: true
steps:
- name: Checkout
@@ -584,9 +615,11 @@ jobs:
- name: Run e2e ${{ matrix.suite }} tests
env:
E2E_ARGS: "--suites ${{ matrix.suite }}"
E2E_ARGS: "${{ matrix.args }}"
K8S: ${{ env.K8S }}
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
OIDC_NEEDED: ${{ matrix.oidc == true && 'true' || 'false' }}
OIDC_IFRAME_NEEDED: ${{ matrix.oidc_iframe == true && 'true' || 'false' }}
run: python3 tests/acceptance/run-e2e.py
- name: Upload Playwright traces
@@ -0,0 +1,13 @@
Bugfix: Fix AuthApp and basic auth requests with custom PROXY_USER_OIDC_CLAIM
We fixed AuthApp (app password) and HTTP basic auth requests returning an
internal server error whenever PROXY_USER_OIDC_CLAIM was set to anything
other than its default value. Both authenticators put the already
authenticated user directly into the request context instead of faking
incomplete claims for the account resolver to re-resolve. We also made sure
a user who only ever authenticates this way still gets a default role
assigned, and that these requests keep getting rejected on deployments with
multiple instances enabled, since neither carries tenant-membership
information.
https://github.com/owncloud/ocis/pull/13107
@@ -0,0 +1,20 @@
Bugfix: Record the acting user in the audit log's User field
The audit log's `User` field is documented as the UID of the user performing
the action, but the file and folder converters filled it from the event's
`Owner`, which reva does not set, so the field was empty on every upload,
download, move, delete, restore and version restore. Where an event did carry
an owner, `User` named the owner rather than the person acting, for example a
share recipient uploading into a shared folder. Space, user and group events
hard-coded the field to an empty string although every one of those events
carries the actor.
`User` is now taken from the event's `Executant` for all of these events. The
`Owner` field of file events is unchanged. The failed public-link access event
still has no actor and keeps an empty `User`.
While adding tests for the user and group events, the group member added and
removed messages turned out to pass the user and group ids in the wrong order,
naming the group as the user and the user as the group; that is fixed too.
https://github.com/owncloud/ocis/issues/4789
@@ -0,0 +1,25 @@
Bugfix: Fix the LDAP master-ID filter when the base filter is empty
The function `EnhanceFilterWithMasterID` in `ocis-pkg/ldap/filter.go` adds a
master-ID clause to an LDAP filter with OR. An empty filter means "no
restriction". Before this fix, the function replaced an empty filter with a
master-ID-only filter. This action restricted an unrestricted search to
master-ID users only.
The bug broke the search for a user on another instance in multi-instance
deployments. This search uses the Graph API endpoint `/graph/v1.0/users`.
Multi-instance deployments use this search to find a user to share a resource
with.
Now the function keeps an empty filter unchanged. The function still adds a
master-ID clause to a filter that is not empty.
The `graph`, `auth-basic`, `users`, and `groups` services also use this
function to compute their default LDAP user filter when
`OCIS_MULTI_INSTANCE_MASTER_ID` is set. An empty user filter now means these
services resolve or authenticate every user in the shared LDAP directory,
not only master-ID users. Each of these services now rejects startup when
`OCIS_MULTI_INSTANCE_MASTER_ID` is set and its own user filter is empty.
Set an explicit `OCIS_LDAP_USER_FILTER` for every multi-instance deployment.
https://github.com/owncloud/ocis/pull/13100
@@ -0,0 +1,8 @@
Bugfix: Stop logging "no user in context" for data gateway requests
The proxy's create-home middleware logged an error for every request that
carried a reva token but no user. reva's internal downloads through the data
gateway (`/data`) are such requests, so every file download added an
error-level line. These requests are now passed on with a debug-level log.
https://github.com/owncloud/ocis/issues/13101
@@ -0,0 +1,10 @@
Bugfix: Show an error instead of "no deleted files" for inaccessible trash
Members of a space who are not allowed to list its trash, for example members
with the "Can edit" role, were told that the space has no deleted files, even
though files had been deleted. The trash view now tells the user that the
deleted files could not be loaded and that they might lack the permission to
view them. A trash that is really empty still shows the "no deleted files"
message.
https://github.com/owncloud/ocis/pull/13105
@@ -0,0 +1,13 @@
Change: Remove the MFA session extension popup in vault mode
In vault mode, the web UI showed a popup shortly before the multi-factor
authentication session was about to expire, offering to extend or dismiss it.
Extending only reset a timer in the browser and did not renew anything on the
server, so the popup has been removed.
The frontend service no longer exposes the MFA session duration in its
capabilities, and its `session_duration` setting has been removed. The
`OCIS_MFA_SESSION_DURATION` environment variable is still used by the proxy
service.
https://github.com/owncloud/ocis/pull/13085
@@ -0,0 +1,12 @@
Enhancement: Record tag changes in the audit log
Adding or removing tags on a file or folder left no trace in the audit log.
The graph service already publishes `TagsAdded` and `TagsRemoved` events for
every change, but only the search service listened to them.
The audit service now records both: `file_tags_add` and `file_tags_remove`
entries carry the acting user, the file id and path, the space owner and the
tags concerned. The graph service also sets the timestamp on the two events,
which it left empty before.
https://github.com/owncloud/ocis/issues/13054
@@ -0,0 +1,11 @@
Enhancement: Default 30-day expiration for vault shares
When a user or group share of a vault file or folder is created without an
expiration date, the server now preconfigures a default expiration (30 days
by default, configurable via `GRAPH_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS`) to
encourage data minimization. The sharer can override or shorten this value.
Non-vault shares and space memberships are exempt and stay unbounded, as
space memberships represent a permanent organizational role.
https://github.com/owncloud/ocis/pull/12988
@@ -0,0 +1,13 @@
Enhancement: Add a --timeout flag to the search index command
`ocis search index` called the search service with a fixed 10 minute request
timeout. The service walks the whole space inside that request, so once the
timeout expired the walk was cancelled with "error walking the tree: context
canceled" and everything after that point stayed unindexed. A space whose
walk takes longer than ten minutes, for example because the content extractor
is slow on a few files, could never be fully indexed from the command line.
The timeout is now a flag. `--timeout` takes a duration (default `10m`, so the
behaviour is unchanged out of the box); `0` waits indefinitely.
https://github.com/owncloud/ocis/issues/13052
+1 -1
View File
@@ -67,7 +67,7 @@ require (
github.com/open-policy-agent/opa v1.21.1
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20261006170644-bac0e1ee144a
github.com/owncloud/reva/v2 v2.0.0-20261007144855-b8082819aa39
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.24.1
+2 -2
View File
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20261006170644-bac0e1ee144a h1:gUe35SzqPHF+xkEUlyqnN9ZVwTVBBQQ0fmzV/1dLHjQ=
github.com/owncloud/reva/v2 v2.0.0-20261006170644-bac0e1ee144a/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/owncloud/reva/v2 v2.0.0-20261007144855-b8082819aa39 h1:lC5Y4C3/i0uDhMLA53+kfDJg919gNbjSe2+FiViP3XM=
github.com/owncloud/reva/v2 v2.0.0-20261007144855-b8082819aa39/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
+6 -11
View File
@@ -7,14 +7,13 @@ import (
"github.com/go-ldap/ldap/v3"
)
// EnhanceFilterWithMasterID OR's the given LDAP filter with master-id match clauses.
// Returns filter unchanged when masterID is empty or both attributes are empty.
// EnhanceFilterWithMasterID adds master-ID match clauses to the given LDAP filter with OR.
// An empty filter means "no restriction". Do not OR an empty filter with a master-ID clause.
// This action would restrict an unrestricted search to the master ID only.
// The function returns the filter without a change when masterID is empty, when both
// attributes are empty, or when filter is empty.
func EnhanceFilterWithMasterID(filter, masterID, memberAttr, guestAttr string) string {
if masterID == "" {
return filter
}
if memberAttr == "" && guestAttr == "" {
if masterID == "" || (memberAttr == "" && guestAttr == "") || filter == "" {
return filter
}
@@ -35,9 +34,5 @@ func EnhanceFilterWithMasterID(filter, masterID, memberAttr, guestAttr string) s
masterIDFilter = fmt.Sprintf("(|%s)", strings.Join(masterIDParts, ""))
}
if filter == "" {
return masterIDFilter
}
return fmt.Sprintf("(|%s%s)", filter, masterIDFilter)
}
+2 -2
View File
@@ -54,12 +54,12 @@ func TestEnhanceFilterWithMasterID(t *testing.T) {
expectedFilter: "(|(ownCloudGuestOf=instance-1)(ownCloudGuestOf=0000-0000-000-0000))",
},
{
name: "empty existing filter",
name: "empty existing filter stays unrestricted",
filter: "",
masterID: "0000-0000-000-0000",
memberAttr: "ownCloudMemberOf",
guestAttr: "ownCloudGuestOf",
expectedFilter: "(|(ownCloudMemberOf=0000-0000-000-0000)(ownCloudGuestOf=0000-0000-000-0000))",
expectedFilter: "",
},
{
name: "LDAP injection protection",
+7
View File
@@ -46,6 +46,13 @@ func MissingLDAPBindPassword(service string) error {
service, defaults.BaseConfigPath())
}
func MissingLDAPUserFilterForMasterID(service string) error {
return fmt.Errorf("The ldap user_filter has not been set for %s, but OCIS_MULTI_INSTANCE_MASTER_ID is set. "+
"Set an explicit user_filter to scope this instance to its own users. "+
"Without a user_filter, every user in the shared LDAP directory can access this instance.",
service)
}
func MissingServiceUserPassword(service, serviceUser string) error {
return fmt.Errorf("The password of service user %s has not been set properly in your config for %s. "+
"Make sure your %s config contains the proper values "+
+5 -5
View File
@@ -54,8 +54,8 @@ type GRPCClientOptions struct {
// which read them independently of each other but apply the same rules, so both behave
// identically for every input. Keepalive is off unless the time is set to a duration that
// parses; a value without a unit suffix leaves the clients without pings.
GRPCClientKeepaliveTime time.Duration `yaml:"grpc_client_keepalive_time" env:"GRPC_CLIENT_KEEPALIVE_TIME" desc:"How long a grpc client connection with an ongoing request may stay silent before the server is pinged to check whether it is still answering. Set a duration like '20s' to enable detection of unresponsive peers. Leaving it unset, or at '0', sends no pings at all, which is grpc's own default. Values below '10s' are raised to '10s' by grpc. Make sure to include the unit suffix, a bare number is not a valid duration." introductionVersion:"8.3.0"`
GRPCClientKeepaliveTimeout time.Duration `yaml:"grpc_client_keepalive_timeout" env:"GRPC_CLIENT_KEEPALIVE_TIMEOUT" desc:"How long a grpc client waits for the answer to a keepalive ping before it considers the connection dead and fails all requests on it. Defaults to '10s'. Has no effect unless GRPC_CLIENT_KEEPALIVE_TIME is set. See GRPC_CLIENT_KEEPALIVE_TIME." introductionVersion:"8.3.0"`
GRPCClientKeepaliveTime time.Duration `yaml:"grpc_client_keepalive_time" env:"GRPC_CLIENT_KEEPALIVE_TIME" desc:"How long a grpc client connection with an ongoing request may stay silent before the server is pinged to check whether it is still answering. Set a duration like '20s' to enable detection of unresponsive peers. Leaving it unset, or at '0', sends no pings at all, which is grpc's own default. Values below '10s' are raised to '10s' by grpc. Make sure to include the unit suffix, a bare number is not a valid duration." introductionVersion:"9.0.0"`
GRPCClientKeepaliveTimeout time.Duration `yaml:"grpc_client_keepalive_timeout" env:"GRPC_CLIENT_KEEPALIVE_TIMEOUT" desc:"How long a grpc client waits for the answer to a keepalive ping before it considers the connection dead and fails all requests on it. Defaults to '10s'. Has no effect unless GRPC_CLIENT_KEEPALIVE_TIME is set. See GRPC_CLIENT_KEEPALIVE_TIME." introductionVersion:"9.0.0"`
}
type GRPCServiceTLS struct {
@@ -80,9 +80,9 @@ type Cache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"auth_username" env:"OCIS_CACHE_AUTH_USERNAME" desc:"The username to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"pre5.0"`
AuthPassword string `yaml:"auth_password" env:"OCIS_CACHE_AUTH_PASSWORD" desc:"The password to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"pre5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the NATS store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the NATS store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate used to validate the NATS store TLS certificate. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the NATS store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the NATS store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate used to validate the NATS store TLS certificate. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// Commons holds configuration that are common to all extensions. Each extension can then decide whether
+3 -3
View File
@@ -55,9 +55,9 @@ type Store struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;ACTIVITYLOG_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;ACTIVITYLOG_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;ACTIVITYLOG_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;ACTIVITYLOG_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;ACTIVITYLOG_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;ACTIVITYLOG_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;ACTIVITYLOG_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;ACTIVITYLOG_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;ACTIVITYLOG_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// ServiceAccount is the configuration for the used service account
+2
View File
@@ -2,6 +2,8 @@
The audit service logs all events of the system as an audit log. Per default, it will be logged to standard out, but can also be configured to a file output. Supported log formats are json or a minimal human-readable format.
Besides shares, links, files, spaces, users and groups, tag changes are recorded: adding tags to a file or folder is logged as `file_tags_add` and removing them as `file_tags_remove`, each with the acting user, the file id and the tags as requested. The request is recorded as made: a tag that was already present (or, for a removal, absent) is still listed, so repeated requests remain visible.
With audit logs, you are able to prove compliance with corporate guidelines as well as to enable reporting and auditing of operations. The audit service takes note of actions conducted by users and administrators.
Example minimal format:
+4
View File
@@ -83,6 +83,10 @@ func StartAuditLogger(ctx context.Context, ch <-chan events.Event, log log.Logge
auditEvent = types.ItemRestored(ev)
case events.FileVersionRestored:
auditEvent = types.FileVersionRestored(ev)
case events.TagsAdded:
auditEvent = types.TagsAdded(ev)
case events.TagsRemoved:
auditEvent = types.TagsRemoved(ev)
case events.SpaceCreated:
auditEvent = types.SpaceCreated(ev)
case events.SpaceRenamed:
+108 -22
View File
@@ -325,7 +325,7 @@ var testCases = []struct {
Event: events.FileUploaded{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -335,7 +335,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' created file 'pro-1$sto-123!iid-123/item'", "file_create")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
},
}, {
Alias: "File read",
@@ -343,7 +343,7 @@ var testCases = []struct {
Event: events.FileDownloaded{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -353,7 +353,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' read file 'pro-1$sto-123!iid-123/item'", "file_read")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
},
}, {
Alias: "File trashed",
@@ -361,7 +361,7 @@ var testCases = []struct {
Event: events.ItemTrashed{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -371,7 +371,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' trashed file 'pro-1$sto-123!iid-123/item'", "file_delete")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
},
}, {
Alias: "File renamed",
@@ -380,7 +380,7 @@ var testCases = []struct {
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
OldReference: reference("pro-1", "sto-123", "iid-123", "./anotheritem"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -390,7 +390,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' moved file 'pro-1$sto-123!iid-123/item' from './anotheritem' to './item'", "file_rename")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
// AuditEventFileRenamed fields
require.Equal(t, "./anotheritem", ev.OldPath)
@@ -401,7 +401,7 @@ var testCases = []struct {
Event: events.ItemPurged{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
@@ -411,7 +411,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' removed file 'pro-1$sto-123!iid-123/item' from trashbin", "file_trash_delete")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
},
}, {
Alias: "File restored",
@@ -419,7 +419,7 @@ var testCases = []struct {
Event: events.ItemRestored{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
OldReference: reference("pro-1", "sto-123", "sto-123!iid-123/item", "./oldpath"),
Key: "",
},
@@ -431,7 +431,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' restored file 'pro-1$sto-123!iid-123/item' from trashbin to './item'", "file_trash_restore")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
// AuditEventFileRestored fields
require.Equal(t, "./oldpath", ev.OldPath)
@@ -442,7 +442,7 @@ var testCases = []struct {
Event: events.FileVersionRestored{
Executant: userID("uid-123"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Owner: userID("uid-123"), // NOTE: owner not yet implemented in reva
Owner: userID("uid-owner"),
Key: "v1",
},
},
@@ -453,7 +453,7 @@ var testCases = []struct {
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' restored file 'pro-1$sto-123!iid-123/item' in version 'v1'", "file_version_restore")
// AuditEventSharing fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-123", "./item")
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
// AuditEventFileRestored fields
require.Equal(t, "v1", ev.Key)
@@ -464,7 +464,7 @@ var testCases = []struct {
Event: events.SpaceCreated{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
Owner: userID("uid-123"),
Owner: userID("uid-owner"),
Root: resourceID("pro-1", "sto-123", "iid-123"),
Name: "test-space",
Type: "project",
@@ -477,11 +477,11 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "2286-11-20T17:46:40Z", "user 'uid-123' created a space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_created")
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "2286-11-20T17:46:40Z", "user 'uid-123' created a space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_created")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
// AuditEventFileRestored fields
require.Equal(t, "uid-123", ev.Owner)
require.Equal(t, "uid-owner", ev.Owner)
require.Equal(t, "pro-1$sto-123!iid-123", ev.RootItem)
require.Equal(t, "test-space", ev.Name)
require.Equal(t, "project", ev.Type)
@@ -492,7 +492,7 @@ var testCases = []struct {
Event: events.SpaceRenamed{
Executant: userID("uid-123"),
ID: &provider.StorageSpaceId{OpaqueId: "storage-1$space-123"},
Owner: userID("uid-123"),
Owner: userID("uid-owner"),
Name: "new-name",
},
},
@@ -501,7 +501,7 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "", "user 'uid-123' renamed space 'space-123' to 'new-name' (storage: 'storage-1')", "space_renamed")
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' renamed space 'space-123' to 'new-name' (storage: 'storage-1')", "space_renamed")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
// AuditEventSpaceRenamed fields
@@ -520,7 +520,7 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' disabled the space 'space-123' (storage: 'storage-1')", "space_disabled")
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "0001-01-01T00:00:00Z", "user 'uid-123' disabled the space 'space-123' (storage: 'storage-1')", "space_disabled")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
@@ -537,7 +537,7 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "", "user 'uid-123' (re-) enabled the space 'space-123' (storage: 'storage-1')", "space_enabled")
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "", "user 'uid-123' (re-) enabled the space 'space-123' (storage: 'storage-1')", "space_enabled")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
@@ -555,7 +555,7 @@ var testCases = []struct {
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields
checkBaseAuditEvent(t, ev.AuditEvent, "", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_deleted")
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "0001-01-01T00:00:00Z", "user 'uid-123' deleted the space 'space-123' with name 'test-space' (storage: 'storage-1')", "space_deleted")
// AuditEventSpaces fields
checkSpacesAuditEvent(t, ev.AuditEventSpaces, "storage-1$space-123")
},
@@ -587,6 +587,92 @@ var testCases = []struct {
require.Equal(t, "http://ocis.test/invite", ev.InviteLink)
},
},
{
Alias: "User created",
SystemEvent: events.Event{
Event: events.UserCreated{
Executant: userID("uid-admin"),
UserID: "uid-new",
Timestamp: timestamp(10e8),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventUserCreated{}
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields: User is the actor, not the affected user
checkBaseAuditEvent(t, ev.AuditEvent, "uid-admin", "2001-09-09T01:46:40Z", "user 'uid-admin' created the user 'uid-new'", "user_created")
// AuditEventUserCreated fields
require.Equal(t, "uid-new", ev.UserID)
},
},
{
Alias: "Group member added",
SystemEvent: events.Event{
Event: events.GroupMemberAdded{
Executant: userID("uid-admin"),
GroupID: "gid-123",
UserID: "uid-member",
Timestamp: timestamp(10e8),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventGroupMemberAdded{}
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields: User is the actor, not the member
checkBaseAuditEvent(t, ev.AuditEvent, "uid-admin", "2001-09-09T01:46:40Z", "user 'uid-admin' added user 'uid-member' was added to group 'gid-123'", "group_member_added")
// AuditEventGroupMemberAdded fields
require.Equal(t, "gid-123", ev.GroupID)
require.Equal(t, "uid-member", ev.UserID)
},
},
{
Alias: "Tags added",
SystemEvent: events.Event{
Event: events.TagsAdded{
Executant: userID("uid-123"),
SpaceOwner: userID("uid-owner"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Tags: "holiday,family",
Timestamp: timestamp(10e8),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventTagsAdded{}
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields: User is the actor, Owner the space owner
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "2001-09-09T01:46:40Z", "user 'uid-123' added tags 'holiday,family' to file 'pro-1$sto-123!iid-123/item'", "file_tags_add")
// AuditEventFiles fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
// AuditEventTagsAdded fields
require.Equal(t, "holiday,family", ev.Tags)
},
},
{
Alias: "Tags removed",
SystemEvent: events.Event{
Event: events.TagsRemoved{
Executant: userID("uid-123"),
SpaceOwner: userID("uid-owner"),
Ref: reference("pro-1", "sto-123", "iid-123", "./item"),
Tags: "holiday",
Timestamp: timestamp(10e8),
},
},
CheckAuditEvent: func(t *testing.T, b []byte) {
ev := types.AuditEventTagsRemoved{}
require.NoError(t, json.Unmarshal(b, &ev))
// AuditEvent fields: User is the actor, Owner the space owner
checkBaseAuditEvent(t, ev.AuditEvent, "uid-123", "2001-09-09T01:46:40Z", "user 'uid-123' removed tags 'holiday' from file 'pro-1$sto-123!iid-123/item'", "file_tags_remove")
// AuditEventFiles fields
checkFilesAuditEvent(t, ev.AuditEventFiles, "pro-1$sto-123!iid-123/item", "uid-owner", "./item")
// AuditEventTagsRemoved fields
require.Equal(t, "holiday", ev.Tags)
},
},
}
func TestAuditLogging(t *testing.T) {
+49 -25
View File
@@ -247,7 +247,7 @@ func FilesAuditEvent(base AuditEvent, itemid, owner, path string) AuditEventFile
// ContainerCreated converts a ContainerCreated event to an AuditEventContainerCreated
func ContainerCreated(ev events.ContainerCreated) AuditEventContainerCreated {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageContainerCreated(ev.Executant.GetOpaqueId(), iid), ActionContainerCreated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageContainerCreated(ev.Executant.GetOpaqueId(), iid), ActionContainerCreated)
return AuditEventContainerCreated{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
}
@@ -256,7 +256,7 @@ func ContainerCreated(ev events.ContainerCreated) AuditEventContainerCreated {
// FileUploaded converts a FileUploaded event to an AuditEventFileCreated
func FileUploaded(ev events.FileUploaded) AuditEventFileCreated {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileCreated(ev.Executant.GetOpaqueId(), iid), ActionFileCreated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileCreated(ev.Executant.GetOpaqueId(), iid), ActionFileCreated)
return AuditEventFileCreated{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
}
@@ -265,7 +265,7 @@ func FileUploaded(ev events.FileUploaded) AuditEventFileCreated {
// FileDownloaded converts a FileDownloaded event to an AuditEventFileRead
func FileDownloaded(ev events.FileDownloaded) AuditEventFileRead {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileRead(ev.Executant.GetOpaqueId(), iid), ActionFileRead)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileRead(ev.Executant.GetOpaqueId(), iid), ActionFileRead)
return AuditEventFileRead{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
}
@@ -280,7 +280,7 @@ func ItemMoved(ev events.ItemMoved) AuditEventFileRenamed {
oldpath = ev.OldReference.GetPath()
}
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileRenamed(ev.Executant.GetOpaqueId(), iid, oldpath, path), ActionFileRenamed)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileRenamed(ev.Executant.GetOpaqueId(), iid, oldpath, path), ActionFileRenamed)
return AuditEventFileRenamed{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
OldPath: oldpath,
@@ -290,7 +290,7 @@ func ItemMoved(ev events.ItemMoved) AuditEventFileRenamed {
// ItemTrashed converts a ItemTrashed event to an AuditEventFileDeleted
func ItemTrashed(ev events.ItemTrashed) AuditEventFileDeleted {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileTrashed(ev.Executant.GetOpaqueId(), iid), ActionFileTrashed)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileTrashed(ev.Executant.GetOpaqueId(), iid), ActionFileTrashed)
return AuditEventFileDeleted{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
}
@@ -299,7 +299,7 @@ func ItemTrashed(ev events.ItemTrashed) AuditEventFileDeleted {
// ItemPurged converts a ItemPurged event to an AuditEventFilePurged
func ItemPurged(ev events.ItemPurged) AuditEventFilePurged {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFilePurged(ev.Executant.GetOpaqueId(), iid), ActionFilePurged)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFilePurged(ev.Executant.GetOpaqueId(), iid), ActionFilePurged)
return AuditEventFilePurged{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
}
@@ -314,7 +314,7 @@ func ItemRestored(ev events.ItemRestored) AuditEventFileRestored {
oldpath = ev.OldReference.GetPath()
}
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileRestored(ev.Executant.GetOpaqueId(), iid, path), ActionFileRestored)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileRestored(ev.Executant.GetOpaqueId(), iid, path), ActionFileRestored)
return AuditEventFileRestored{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
OldPath: oldpath,
@@ -324,13 +324,37 @@ func ItemRestored(ev events.ItemRestored) AuditEventFileRestored {
// FileVersionRestored converts a FileVersionRestored event to an AuditEventFileVersionRestored
func FileVersionRestored(ev events.FileVersionRestored) AuditEventFileVersionRestored {
iid, path, uid := extractFileDetails(ev.Ref, ev.Owner)
base := BasicAuditEvent(uid, formatTime(ev.Timestamp), MessageFileVersionRestored(ev.Executant.GetOpaqueId(), iid, ev.Key), ActionFileVersionRestored)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageFileVersionRestored(ev.Executant.GetOpaqueId(), iid, ev.Key), ActionFileVersionRestored)
return AuditEventFileVersionRestored{
AuditEventFiles: FilesAuditEvent(base, iid, uid, path),
Key: ev.Key,
}
}
// TagsAdded converts a TagsAdded event to an AuditEventTagsAdded.
// Unlike the other file events, User is the executant (who changed the tags), not the
// space owner: tags are usually changed by someone other than the owner, and the
// owner is still recorded in the Owner field.
func TagsAdded(ev events.TagsAdded) AuditEventTagsAdded {
iid, path, owner := extractFileDetails(ev.Ref, ev.SpaceOwner)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageTagsAdded(ev.Executant.GetOpaqueId(), ev.Tags, iid), ActionTagsAdded)
return AuditEventTagsAdded{
AuditEventFiles: FilesAuditEvent(base, iid, owner, path),
Tags: ev.Tags,
}
}
// TagsRemoved converts a TagsRemoved event to an AuditEventTagsRemoved.
// User is the executant, as in TagsAdded.
func TagsRemoved(ev events.TagsRemoved) AuditEventTagsRemoved {
iid, path, owner := extractFileDetails(ev.Ref, ev.SpaceOwner)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageTagsRemoved(ev.Executant.GetOpaqueId(), ev.Tags, iid), ActionTagsRemoved)
return AuditEventTagsRemoved{
AuditEventFiles: FilesAuditEvent(base, iid, owner, path),
Tags: ev.Tags,
}
}
// SpacesAuditEvent creates an AuditEventSpaces from the given values
func SpacesAuditEvent(base AuditEvent, spaceID string) AuditEventSpaces {
return AuditEventSpaces{
@@ -343,7 +367,7 @@ func SpacesAuditEvent(base AuditEvent, spaceID string) AuditEventSpaces {
func SpaceCreated(ev events.SpaceCreated) AuditEventSpaceCreated {
sid := ev.ID.GetOpaqueId()
iid, _, owner := extractFileDetails(&provider.Reference{ResourceId: ev.Root}, ev.Owner)
base := BasicAuditEvent("", formatTime(ev.MTime), MessageSpaceCreated(ev.Executant.GetOpaqueId(), sid, ev.Name), ActionSpaceCreated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.MTime), MessageSpaceCreated(ev.Executant.GetOpaqueId(), sid, ev.Name), ActionSpaceCreated)
return AuditEventSpaceCreated{
AuditEventSpaces: SpacesAuditEvent(base, sid),
Owner: owner,
@@ -356,7 +380,7 @@ func SpaceCreated(ev events.SpaceCreated) AuditEventSpaceCreated {
// SpaceRenamed converts a SpaceRenamed event to an AuditEventSpaceRenamed
func SpaceRenamed(ev events.SpaceRenamed) AuditEventSpaceRenamed {
sid := ev.ID.GetOpaqueId()
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageSpaceRenamed(ev.Executant.GetOpaqueId(), sid, ev.Name), ActionSpaceRenamed)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageSpaceRenamed(ev.Executant.GetOpaqueId(), sid, ev.Name), ActionSpaceRenamed)
return AuditEventSpaceRenamed{
AuditEventSpaces: SpacesAuditEvent(base, sid),
NewName: ev.Name,
@@ -366,7 +390,7 @@ func SpaceRenamed(ev events.SpaceRenamed) AuditEventSpaceRenamed {
// SpaceDisabled converts a SpaceDisabled event to an AuditEventSpaceDisabled
func SpaceDisabled(ev events.SpaceDisabled) AuditEventSpaceDisabled {
sid := ev.ID.GetOpaqueId()
base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDisabled(ev.Executant.GetOpaqueId(), sid), ActionSpaceDisabled)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDisabled(ev.Executant.GetOpaqueId(), sid), ActionSpaceDisabled)
return AuditEventSpaceDisabled{
AuditEventSpaces: SpacesAuditEvent(base, sid),
}
@@ -375,7 +399,7 @@ func SpaceDisabled(ev events.SpaceDisabled) AuditEventSpaceDisabled {
// SpaceEnabled converts a SpaceEnabled event to an AuditEventSpaceEnabled
func SpaceEnabled(ev events.SpaceEnabled) AuditEventSpaceEnabled {
sid := ev.ID.GetOpaqueId()
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageSpaceEnabled(ev.Executant.GetOpaqueId(), sid), ActionSpaceEnabled)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageSpaceEnabled(ev.Executant.GetOpaqueId(), sid), ActionSpaceEnabled)
return AuditEventSpaceEnabled{
AuditEventSpaces: SpacesAuditEvent(base, sid),
}
@@ -384,7 +408,7 @@ func SpaceEnabled(ev events.SpaceEnabled) AuditEventSpaceEnabled {
// SpaceDeleted converts a SpaceDeleted event to an AuditEventSpaceDeleted
func SpaceDeleted(ev events.SpaceDeleted) AuditEventSpaceDeleted {
sid := ev.ID.GetOpaqueId()
base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid, ev.SpaceName), ActionSpaceDeleted)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceDeleted(ev.Executant.GetOpaqueId(), sid, ev.SpaceName), ActionSpaceDeleted)
return AuditEventSpaceDeleted{
AuditEventSpaces: SpacesAuditEvent(base, sid),
}
@@ -403,7 +427,7 @@ func SpaceShared(ev events.SpaceShared) AuditEventSpaceShared {
sse.GranteeGroupID = ev.GranteeGroupID.OpaqueId
grantee = "group:" + ev.GranteeGroupID.OpaqueId
}
base := BasicAuditEvent("", "", MessageSpaceShared(ev.Executant.GetOpaqueId(), sid, grantee), ActionSpaceShared)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), "", MessageSpaceShared(ev.Executant.GetOpaqueId(), sid, grantee), ActionSpaceShared)
sse.AuditEventSpaces = SpacesAuditEvent(base, sid)
return sse
@@ -422,7 +446,7 @@ func SpaceUnshared(ev events.SpaceUnshared) AuditEventSpaceUnshared {
sue.GranteeGroupID = ev.GranteeGroupID.OpaqueId
grantee = "group:" + ev.GranteeGroupID.OpaqueId
}
base := BasicAuditEvent("", formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceUnshared(ev.Executant.GetOpaqueId(), sid, grantee), ActionSpaceUnshared)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(utils.TimeToTS(ev.Timestamp)), MessageSpaceUnshared(ev.Executant.GetOpaqueId(), sid, grantee), ActionSpaceUnshared)
sue.AuditEventSpaces = SpacesAuditEvent(base, sid)
return sue
@@ -437,7 +461,7 @@ func SpaceUpdated(ev events.SpaceUpdated) AuditEventSpaceUpdated {
Opaque: opaqueMap,
}
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageSpaceUpdated(ev.Executant.GetOpaqueId(), sid, ev.Space.Name, ev.Space.Quota.QuotaMaxBytes, opaqueMap), ActionSpaceUpdated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageSpaceUpdated(ev.Executant.GetOpaqueId(), sid, ev.Space.Name, ev.Space.Quota.QuotaMaxBytes, opaqueMap), ActionSpaceUpdated)
sue.AuditEventSpaces = SpacesAuditEvent(base, sid)
return sue
@@ -445,7 +469,7 @@ func SpaceUpdated(ev events.SpaceUpdated) AuditEventSpaceUpdated {
// UserCreated converts a UserCreated event to an AuditEventUserCreated
func UserCreated(ev events.UserCreated) AuditEventUserCreated {
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageUserCreated(ev.Executant.GetOpaqueId(), ev.UserID), ActionUserCreated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageUserCreated(ev.Executant.GetOpaqueId(), ev.UserID), ActionUserCreated)
return AuditEventUserCreated{
AuditEvent: base,
UserID: ev.UserID,
@@ -454,7 +478,7 @@ func UserCreated(ev events.UserCreated) AuditEventUserCreated {
// UserDeleted converts a UserDeleted event to an AuditEventUserDeleted
func UserDeleted(ev events.UserDeleted) AuditEventUserDeleted {
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageUserDeleted(ev.Executant.GetOpaqueId(), ev.UserID), ActionUserDeleted)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageUserDeleted(ev.Executant.GetOpaqueId(), ev.UserID), ActionUserDeleted)
return AuditEventUserDeleted{
AuditEvent: base,
UserID: ev.UserID,
@@ -464,7 +488,7 @@ func UserDeleted(ev events.UserDeleted) AuditEventUserDeleted {
// UserFeatureChanged converts a UserFeatureChanged event to an AuditEventUserFeatureChanged
func UserFeatureChanged(ev events.UserFeatureChanged) AuditEventUserFeatureChanged {
msg := MessageUserFeatureChanged(ev.Executant.GetOpaqueId(), ev.UserID, ev.Features)
base := BasicAuditEvent("", formatTime(ev.Timestamp), msg, ActionUserFeatureChanged)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), msg, ActionUserFeatureChanged)
return AuditEventUserFeatureChanged{
AuditEvent: base,
UserID: ev.UserID,
@@ -474,7 +498,7 @@ func UserFeatureChanged(ev events.UserFeatureChanged) AuditEventUserFeatureChang
// GroupCreated converts a GroupCreated event to an AuditEventGroupCreated
func GroupCreated(ev events.GroupCreated) AuditEventGroupCreated {
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageGroupCreated(ev.Executant.GetOpaqueId(), ev.GroupID), ActionGroupCreated)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageGroupCreated(ev.Executant.GetOpaqueId(), ev.GroupID), ActionGroupCreated)
return AuditEventGroupCreated{
AuditEvent: base,
GroupID: ev.GroupID,
@@ -483,7 +507,7 @@ func GroupCreated(ev events.GroupCreated) AuditEventGroupCreated {
// GroupDeleted converts a GroupDeleted event to an AuditEventGroupDeleted
func GroupDeleted(ev events.GroupDeleted) AuditEventGroupDeleted {
base := BasicAuditEvent("", formatTime(ev.Timestamp), MessageGroupDeleted(ev.Executant.GetOpaqueId(), ev.GroupID), ActionGroupDeleted)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), MessageGroupDeleted(ev.Executant.GetOpaqueId(), ev.GroupID), ActionGroupDeleted)
return AuditEventGroupDeleted{
AuditEvent: base,
GroupID: ev.GroupID,
@@ -492,8 +516,8 @@ func GroupDeleted(ev events.GroupDeleted) AuditEventGroupDeleted {
// GroupMemberAdded converts a GroupMemberAdded event to an AuditEventGroupMemberAdded
func GroupMemberAdded(ev events.GroupMemberAdded) AuditEventGroupMemberAdded {
msg := MessageGroupMemberAdded(ev.Executant.GetOpaqueId(), ev.GroupID, ev.UserID)
base := BasicAuditEvent("", formatTime(ev.Timestamp), msg, ActionGroupMemberAdded)
msg := MessageGroupMemberAdded(ev.Executant.GetOpaqueId(), ev.UserID, ev.GroupID)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), msg, ActionGroupMemberAdded)
return AuditEventGroupMemberAdded{
AuditEvent: base,
GroupID: ev.GroupID,
@@ -503,8 +527,8 @@ func GroupMemberAdded(ev events.GroupMemberAdded) AuditEventGroupMemberAdded {
// GroupMemberRemoved converts a GroupMemberRemoved event to an AuditEventGroupMemberRemove
func GroupMemberRemoved(ev events.GroupMemberRemoved) AuditEventGroupMemberRemoved {
msg := MessageGroupMemberRemoved(ev.Executant.GetOpaqueId(), ev.GroupID, ev.UserID)
base := BasicAuditEvent("", formatTime(ev.Timestamp), msg, ActionGroupMemberRemoved)
msg := MessageGroupMemberRemoved(ev.Executant.GetOpaqueId(), ev.UserID, ev.GroupID)
base := BasicAuditEvent(ev.Executant.GetOpaqueId(), formatTime(ev.Timestamp), msg, ActionGroupMemberRemoved)
return AuditEventGroupMemberRemoved{
AuditEvent: base,
GroupID: ev.GroupID,
+2
View File
@@ -24,6 +24,8 @@ func RegisteredEvents() []events.Unmarshaller {
events.ItemPurged{},
events.ItemRestored{},
events.FileVersionRestored{},
events.TagsAdded{},
events.TagsRemoved{},
events.SpaceCreated{},
events.SpaceRenamed{},
events.SpaceEnabled{},
+13 -1
View File
@@ -32,6 +32,8 @@ const (
ActionFilePurged = "file_trash_delete"
ActionFileRestored = "file_trash_restore"
ActionFileVersionRestored = "file_version_restore"
ActionTagsAdded = "file_tags_add"
ActionTagsRemoved = "file_tags_remove"
// Spaces
ActionSpaceCreated = "space_created"
@@ -124,7 +126,17 @@ func MessageFileRead(executant, item string) string {
return fmt.Sprintf("user '%s' read file '%s'", executant, item)
}
// MessageFileTrashed returns the human-readable string that describes the action
// MessageTagsAdded returns a human readable string that describes the action
func MessageTagsAdded(executant, tags, item string) string {
return fmt.Sprintf("user '%s' added tags '%s' to file '%s'", executant, tags, item)
}
// MessageTagsRemoved returns a human readable string that describes the action
func MessageTagsRemoved(executant, tags, item string) string {
return fmt.Sprintf("user '%s' removed tags '%s' from file '%s'", executant, tags, item)
}
// MessageFileTrashed returns a human readable string that describes the action
func MessageFileTrashed(executant, item string) string {
return fmt.Sprintf("user '%s' trashed file '%s'", executant, item)
}
+14
View File
@@ -149,6 +149,20 @@ type AuditEventFileRestored struct {
OldPath string
}
// AuditEventTagsAdded is the event logged when tags are added to a file or folder
type AuditEventTagsAdded struct {
AuditEventFiles
Tags string // the tags the request asked to add, as carried by the event (ev.Tags); some may already have been present
}
// AuditEventTagsRemoved is the event logged when tags are removed from a file or folder
type AuditEventTagsRemoved struct {
AuditEventFiles
Tags string // the tags the request asked to remove, as carried by the event (ev.Tags); some may not have been present
}
// AuditEventFileVersionRestored is the event logged when a file version is restored
type AuditEventFileVersionRestored struct {
AuditEventFiles
+1 -1
View File
@@ -82,7 +82,7 @@ type LDAPProvider struct {
IDP string `yaml:"idp" env:"OCIS_URL;OCIS_OIDC_ISSUER;AUTH_BASIC_IDP_URL" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;AUTH_BASIC_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Valid options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed." introductionVersion:"pre5.0"`
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;AUTH_BASIC_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance allows login for every user in the shared LDAP directory." introductionVersion:"7.0"`
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
UserSchema LDAPUserSchema `yaml:"user_schema"`
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
return shared.MissingLDAPBindPassword(cfg.Service.Name)
}
if cfg.AuthProvider == "ldap" && cfg.AuthProviders.LDAP.MasterID != "" && cfg.AuthProviders.LDAP.UserFilter == "" {
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
}
return nil
}
@@ -0,0 +1,63 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/auth-basic/pkg/config"
)
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "auth-basic"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
AuthProvider: "ldap",
AuthProviders: config.AuthProviders{
LDAP: config.LDAPProvider{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.Error(t, err)
}
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "auth-basic"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
AuthProvider: "ldap",
AuthProviders: config.AuthProviders{
LDAP: config.LDAPProvider{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "(ownCloudMemberOf=instance-1)",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "auth-basic"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
AuthProvider: "ldap",
AuthProviders: config.AuthProviders{
LDAP: config.LDAPProvider{
BindPassword: "secret",
MasterID: "",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
+3 -3
View File
@@ -11,7 +11,7 @@ type Store struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;COLLABORATION_STORE_TTL" desc:"Time to live for events in the store. Defaults to '30m' (30 minutes). See the Environment Variable Types description for more details." introductionVersion:"7.0.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;COLLABORATION_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"7.0.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;COLLABORATION_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"7.0.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;COLLABORATION_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;COLLABORATION_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;COLLABORATION_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;COLLABORATION_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;COLLABORATION_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;COLLABORATION_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+3 -3
View File
@@ -45,9 +45,9 @@ type Store struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;EVENTHISTORY_STORE_TTL" desc:"Time to live for events in the store. Defaults to '336h' (2 weeks). See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;EVENTHISTORY_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;EVENTHISTORY_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;EVENTHISTORY_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;EVENTHISTORY_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;EVENTHISTORY_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;EVENTHISTORY_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;EVENTHISTORY_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;EVENTHISTORY_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// Events combines the configuration options for the event bus.
+7 -6
View File
@@ -71,6 +71,8 @@ type Config struct {
EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;FRONTEND_ENABLE_VAULT_MODE" desc:"Enable vault mode. When enabled, the capabilities endpoint will report vault as enabled and the capabilities?vault=true endpoint will return capabilities with public sharing and federation disabled." introductionVersion:"8.1.0"`
DefaultVaultShareExpirationDays int `yaml:"default_vault_share_expiration_days" env:"OCIS_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS;FRONTEND_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS" desc:"The default expiration, in days, applied to a vault user or group share created without an explicit expiration date. Reported via the vault capability so clients can reflect the admin-configured value. Must match the graph service's GRAPH_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS." introductionVersion:"9.0.0"`
Context context.Context `yaml:"-"`
}
@@ -148,9 +150,9 @@ type OCS struct {
StatCacheDisablePersistence bool `yaml:"stat_cache_disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE" desc:"Disable persistence of the cache. Only applies when using the 'nats-js-kv' store type. Defaults to false." introductionVersion:"5.0" deprecationVersion:"7.0.0" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The use of OCIS_CACHE_DISABLE_PERSISTENCE in the frontend service is deprecated because the OCS API is deprecated" deprecationReplacement:""`
StatCacheAuthUsername string `yaml:"stat_cache_auth_username" env:"OCIS_CACHE_AUTH_USERNAME" desc:"The username to use for authentication. Only applies when using the 'nats-js-kv' store type." introductionVersion:"5.0" deprecationVersion:"7.0.0" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The use of OCIS_CACHE_AUTH_USERNAME in the frontend service is deprecated because the OCS API is deprecated OCS API is deprecated" deprecationReplacement:""`
StatCacheAuthPassword string `yaml:"stat_cache_auth_password" env:"OCIS_CACHE_AUTH_PASSWORD" desc:"The password to use for authentication. Only applies when using the 'nats-js-kv' store type." introductionVersion:"5.0" deprecationVersion:"7.0.0" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The use of OCIS_CACHE_AUTH_PASSWORD in the frontend service is deprecated because the OCS API is deprecated OCS API is deprecated" deprecationReplacement:""`
StatCacheEnableTLS bool `yaml:"stat_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the stat cache store. Only applies when using the 'nats-js-kv' store type." introductionVersion:"8.3.0"`
StatCacheTLSInsecure bool `yaml:"stat_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the stat cache store connection. Only applies when using the 'nats-js-kv' store type. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
StatCacheTLSRootCACertificate string `yaml:"stat_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the stat cache store TLS connection. Only applies when using the 'nats-js-kv' store type." introductionVersion:"8.3.0"`
StatCacheEnableTLS bool `yaml:"stat_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the stat cache store. Only applies when using the 'nats-js-kv' store type." introductionVersion:"9.0.0"`
StatCacheTLSInsecure bool `yaml:"stat_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the stat cache store connection. Only applies when using the 'nats-js-kv' store type. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
StatCacheTLSRootCACertificate string `yaml:"stat_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the stat cache store TLS connection. Only applies when using the 'nats-js-kv' store type." introductionVersion:"9.0.0"`
CacheWarmupDriver string `yaml:"cache_warmup_driver,omitempty"` // not supported by the oCIS product, therefore not part of docs
CacheWarmupDrivers CacheWarmupDrivers `yaml:"cache_warmup_drivers,omitempty"` // not supported by the oCIS product, therefore not part of docs
@@ -213,7 +215,6 @@ type Validation struct {
// MFAConfig configures multi factor multifactor authentication
type MFAConfig struct {
Enabled bool `yaml:"enabled" env:"OCIS_MFA_ENABLED" desc:"Set to true to enable multi factor authentication. See the documentation for more details." introductionVersion:"7.3.0"`
AuthLevelNames []string `yaml:"auth_level_names" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"This authentication level name indicates that multi-factor authentication was performed. The name must match the ACR claim in the access token received. Note: If multiple names are required, use a comma-separated list. The front-end service will use the first name in the list when requesting multi-factor authentication (MFA)." introductionVersion:"7.3.0"`
SessionDuration int `yaml:"session_duration" env:"OCIS_MFA_SESSION_DURATION" desc:"The duration in seconds that a multi-factor authentication session is valid. After this time the user will be prompted to re-authenticate. Defaults to 3600 (1 hour)." introductionVersion:"8.1.0"`
Enabled bool `yaml:"enabled" env:"OCIS_MFA_ENABLED" desc:"Set to true to enable multi factor authentication. See the documentation for more details." introductionVersion:"7.3.0"`
AuthLevelNames []string `yaml:"auth_level_names" env:"OCIS_MFA_AUTH_LEVEL_NAMES" desc:"This authentication level name indicates that multi-factor authentication was performed. The name must match the ACR claim in the access token received. Note: If multiple names are required, use a comma-separated list. The front-end service will use the first name in the list when requesting multi-factor authentication (MFA)." introductionVersion:"7.3.0"`
}
@@ -144,9 +144,9 @@ func DefaultConfig() *config.Config {
MaxTagLength: 100,
},
MultiFactorAuthentication: config.MFAConfig{
AuthLevelNames: []string{"advanced"},
SessionDuration: 3600,
AuthLevelNames: []string{"advanced"},
},
DefaultVaultShareExpirationDays: 30,
}
}
+4 -4
View File
@@ -361,13 +361,13 @@ func FrontendConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string
},
"auth": map[string]interface{}{
"mfa": map[string]interface{}{
"enabled": cfg.MultiFactorAuthentication.Enabled,
"levelnames": cfg.MultiFactorAuthentication.AuthLevelNames,
"session_duration": cfg.MultiFactorAuthentication.SessionDuration,
"enabled": cfg.MultiFactorAuthentication.Enabled,
"levelnames": cfg.MultiFactorAuthentication.AuthLevelNames,
},
},
"vault": map[string]interface{}{
"enabled": cfg.EnableVaultMode,
"enabled": cfg.EnableVaultMode,
"default_share_expiration_days": cfg.DefaultVaultShareExpirationDays,
},
},
"version": map[string]interface{}{
+3 -3
View File
@@ -95,7 +95,7 @@ type Cache struct {
ProviderCacheDisablePersistence bool `yaml:"provider_cache_disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;GATEWAY_PROVIDER_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the provider cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
ProviderCacheAuthUsername string `yaml:"provider_cache_auth_username" env:"OCIS_CACHE_AUTH_USERNAME;GATEWAY_PROVIDER_CACHE_AUTH_USERNAME" desc:"The username to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
ProviderCacheAuthPassword string `yaml:"provider_cache_auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;GATEWAY_PROVIDER_CACHE_AUTH_PASSWORD" desc:"The password to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
ProviderCacheEnableTLS bool `yaml:"provider_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GATEWAY_PROVIDER_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
ProviderCacheTLSInsecure bool `yaml:"provider_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GATEWAY_PROVIDER_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
ProviderCacheTLSRootCACertificate string `yaml:"provider_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GATEWAY_PROVIDER_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
ProviderCacheEnableTLS bool `yaml:"provider_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GATEWAY_PROVIDER_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
ProviderCacheTLSInsecure bool `yaml:"provider_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GATEWAY_PROVIDER_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
ProviderCacheTLSRootCACertificate string `yaml:"provider_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GATEWAY_PROVIDER_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+3 -3
View File
@@ -12,7 +12,7 @@ type Cache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;GRAPH_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;GRAPH_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;GRAPH_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GRAPH_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GRAPH_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GRAPH_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GRAPH_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GRAPH_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GRAPH_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+5 -3
View File
@@ -45,6 +45,8 @@ type Config struct {
EnableVaultMode bool `yaml:"enable_vault_mode" env:"OCIS_ENABLE_VAULT_MODE;GRAPH_ENABLE_VAULT_MODE" desc:"Enable vault mode in addition to the regular graph service. This only applies when the additional storage-users-vault service is running, which is a special configured storage-users service." introductionVersion:"8.1.0"`
DefaultVaultShareExpirationDays int `yaml:"default_vault_share_expiration_days" env:"OCIS_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS;GRAPH_DEFAULT_VAULT_SHARE_EXPIRATION_DAYS" desc:"The default expiration, in days, applied to a vault user or group share created without an explicit expiration date. Space memberships are exempt." introductionVersion:"9.0.0"`
EnableUserSharing bool `yaml:"enable_user_sharing" env:"OCIS_ENABLE_USER_SHARING" desc:"Enables direct sharing with users and groups. When disabled, creating new user, group or federated shares via the drive item invite endpoints is rejected. Public link sharing and space membership are not affected." introductionVersion:"8.2.0"`
Context context.Context `yaml:"-"`
@@ -123,7 +125,7 @@ type LDAP struct {
InstanceMapperIDAttribute string `yaml:"instance_mapper_id_attribute" env:"OCIS_LDAP_INSTANCE_MAPPER_ID_ATTRIBUTE" desc:"LDAP Attribute of the instance ID. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
CrossInstanceReferenceTemplate string `yaml:"cross_instance_reference_template" env:"OCIS_LDAP_CROSS_INSTANCE_REFERENCE_TEMPLATE" desc:"Template for the users unique reference across oCIS instances. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceURLTemplate string `yaml:"instance_url_template" env:"OCIS_LDAP_INSTANCE_URL_TEMPLATE" desc:"Template for the instance URL. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.0.0"`
InstanceMapperCacheTTL int `yaml:"instance_mapper_cache_ttl" env:"OCIS_LDAP_INSTANCE_MAPPER_CACHE_TTL" desc:"Max TTL in seconds for the LDAP instance mapper cache. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"8.3.0"`
InstanceMapperCacheTTL int `yaml:"instance_mapper_cache_ttl" env:"OCIS_LDAP_INSTANCE_MAPPER_CACHE_TTL" desc:"Max TTL in seconds for the LDAP instance mapper cache. Requires OCIS_MULTI_INSTANCE_ENABLED." introductionVersion:"9.0.0"`
}
// LDAPEducationConfig represents the LDAP configuration for education related resources
@@ -192,13 +194,13 @@ type ServiceAccount struct {
type Validation struct {
MaxTagLength int `yaml:"max_tag_length" env:"OCIS_MAX_TAG_LENGTH" desc:"Define the maximum tag length. Defaults to 100 if not set. Set to 0 to not limit the tag length. Changes only impact the validation of new tags." introductionVersion:"7.2.0"`
MaxImageFileSize string `yaml:"max_image_file_size" env:"GRAPH_MAX_IMAGE_FILE_SIZE" desc:"The maximum file size of an image which can be set as a space image. Must be less than or equal to 'THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE' of the thumbnails service, otherwise images between the two values are accepted but cannot be rendered. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB, TB, TiB, PB, PiB, EB, EiB], example: 2GB. Set to 0 to not limit the file size." introductionVersion:"8.3.0"`
MaxImageFileSize string `yaml:"max_image_file_size" env:"GRAPH_MAX_IMAGE_FILE_SIZE" desc:"The maximum file size of an image which can be set as a space image. Must be less than or equal to 'THUMBNAILS_MAX_INPUT_IMAGE_FILE_SIZE' of the thumbnails service, otherwise images between the two values are accepted but cannot be rendered. Usable common abbreviations: [KB, KiB, MB, MiB, GB, GiB, TB, TiB, PB, PiB, EB, EiB], example: 2GB. Set to 0 to not limit the file size." introductionVersion:"9.0.0"`
}
// MultiInstanceConfig holds configuration for multi-instance-ocis
type MultiInstanceConfig struct {
Enabled bool `yaml:"enabled" env:"OCIS_MULTI_INSTANCE_ENABLED" desc:"Enable multiple instances of Infinite Scale." introductionVersion:"8.0.0"`
InstanceID string `yaml:"instanceid" env:"OCIS_MULTI_INSTANCE_INSTANCEID" desc:"The unique ID of this instance." introductionVersion:"8.0.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable." introductionVersion:"8.1.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable. Also set 'OCIS_LDAP_USER_FILTER'. Without an explicit user filter, this instance resolves every user in the shared LDAP directory." introductionVersion:"8.1.0"`
QueryRegexp string `yaml:"query_regexp" env:"OCIS_MULTI_INSTANCE_QUERY_TEMPLATE" desc:"The regular expression extracting username and instancename from a user provided search." introductionVersion:"8.0.0"`
}
@@ -134,9 +134,10 @@ func DefaultConfig() *config.Config {
Cluster: "ocis-cluster",
EnableTLS: false,
},
MaxConcurrency: 20,
ReceivedSharesStatTimeout: 10 * time.Second,
EnableUserSharing: true,
MaxConcurrency: 20,
ReceivedSharesStatTimeout: 10 * time.Second,
EnableUserSharing: true,
DefaultVaultShareExpirationDays: 30,
UnifiedRoles: config.UnifiedRoles{
AvailableRoles: nil, // will be populated with defaults in EnsureDefaults
},
@@ -98,6 +98,10 @@ func validateLDAPSettings(cfg *config.Config) error {
return shared.MissingLDAPBindPassword(cfg.Service.Name)
}
if cfg.MultiInstance.MasterID != "" && cfg.Identity.LDAP.UserFilter == "" {
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
}
// ensure that "GroupBaseDN" is below "GroupBaseDN"
if cfg.Identity.LDAP.WriteEnabled && cfg.Identity.LDAP.GroupCreateBaseDN != cfg.Identity.LDAP.GroupBaseDN {
baseDN, err := ldap.ParseDN(cfg.Identity.LDAP.GroupBaseDN)
@@ -0,0 +1,63 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
)
func TestValidateLDAPSettingsMasterIDRequiresUserFilter(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "graph"},
Identity: config.Identity{
LDAP: config.LDAP{
BindPassword: "secret",
UserFilter: "",
},
},
MultiInstance: config.MultiInstanceConfig{
MasterID: "master-1",
},
}
err := validateLDAPSettings(cfg)
assert.Error(t, err)
}
func TestValidateLDAPSettingsMasterIDWithUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "graph"},
Identity: config.Identity{
LDAP: config.LDAP{
BindPassword: "secret",
UserFilter: "(ownCloudMemberOf=instance-1)",
},
},
MultiInstance: config.MultiInstanceConfig{
MasterID: "master-1",
},
}
err := validateLDAPSettings(cfg)
assert.NoError(t, err)
}
func TestValidateLDAPSettingsNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "graph"},
Identity: config.Identity{
LDAP: config.LDAP{
BindPassword: "secret",
UserFilter: "",
},
},
MultiInstance: config.MultiInstanceConfig{
MasterID: "",
},
}
err := validateLDAPSettings(cfg)
assert.NoError(t, err)
}
@@ -7,6 +7,7 @@ import (
"net/url"
"slices"
"strings"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
@@ -177,6 +178,18 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
var shareid string
var expiration *types.Timestamp
var cTime *types.Timestamp
// use the client-supplied expiration, else default vault shares to DefaultVaultShareExpirationDays;
// space memberships and non-vault shares are exempt
resourceID := statResponse.GetInfo().GetId()
var shareExpiration *types.Timestamp
switch {
case invite.ExpirationDateTime != nil:
shareExpiration = utils.TimeToTS(*invite.ExpirationDateTime)
case !IsSpaceRoot(resourceID) && IsVaultResource(resourceID):
shareExpiration = utils.TimeToTS(time.Now().UTC().AddDate(0, 0, s.config.DefaultVaultShareExpirationDays))
}
switch driveRecipient.GetLibreGraphRecipientType() {
case "group":
group, err := s.identityCache.GetGroup(ctx, objectID)
@@ -192,8 +205,8 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
},
}
createShareRequest := createShareRequestToGroup(group, statResponse.GetInfo(), cs3ResourcePermissions)
if invite.ExpirationDateTime != nil {
createShareRequest.GetGrant().Expiration = utils.TimeToTS(*invite.ExpirationDateTime)
if shareExpiration != nil {
createShareRequest.GetGrant().Expiration = shareExpiration
}
createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest)
if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil {
@@ -246,8 +259,8 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
}
createShareRequest := createShareRequestToFederatedUser(user, statResponse.GetInfo().GetId(), providerInfoResp.ProviderInfo, cs3ResourcePermissions)
if invite.ExpirationDateTime != nil {
createShareRequest.Expiration = utils.TimeToTS(*invite.ExpirationDateTime)
if shareExpiration != nil {
createShareRequest.Expiration = shareExpiration
}
createShareResponse, err := gatewayClient.CreateOCMShare(ctx, createShareRequest)
if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil {
@@ -259,8 +272,8 @@ func (s DriveItemPermissionsService) Invite(ctx context.Context, resourceId *sto
expiration = createShareResponse.GetShare().GetExpiration()
} else {
createShareRequest := createShareRequestToUser(user, statResponse.GetInfo(), cs3ResourcePermissions)
if invite.ExpirationDateTime != nil {
createShareRequest.GetGrant().Expiration = utils.TimeToTS(*invite.ExpirationDateTime)
if shareExpiration != nil {
createShareRequest.GetGrant().Expiration = shareExpiration
}
createShareResponse, err := gatewayClient.CreateShare(ctx, createShareRequest)
if err := errorcode.FromCS3Status(createShareResponse.GetStatus(), err); err != nil {
@@ -174,6 +174,121 @@ var _ = Describe("DriveItemPermissionsService", func() {
Expect(permission.GrantedToV2.Group.GetId()).To(Equal("2"))
})
It("applies a default 30-day expiration to a vault user share created without one", func() {
statResponse.Info.Id = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: driveItemId.SpaceId,
OpaqueId: driveItemId.OpaqueId,
}
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")},
}
driveItemInvite.ExpirationDateTime = nil
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
expectedDefault := time.Now().UTC().AddDate(0, 0, 30)
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(capturedReq.GetGrant().GetExpiration()).ToNot(BeNil())
Expect(utils.TSToTime(capturedReq.GetGrant().GetExpiration())).To(BeTemporally("~", expectedDefault, time.Minute))
})
It("applies a default 30-day expiration to a vault group share created without one", func() {
statResponse.Info.Id = &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: driveItemId.SpaceId,
OpaqueId: driveItemId.OpaqueId,
}
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(getGroupResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("2"), LibreGraphRecipientType: libregraph.PtrString("group")},
}
driveItemInvite.ExpirationDateTime = nil
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
expectedDefault := time.Now().UTC().AddDate(0, 0, 30)
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(capturedReq.GetGrant().GetExpiration()).ToNot(BeNil())
Expect(utils.TSToTime(capturedReq.GetGrant().GetExpiration())).To(BeTemporally("~", expectedDefault, time.Minute))
})
It("does not apply a default expiration to a non-vault user share created without one", func() {
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")},
}
driveItemInvite.ExpirationDateTime = nil
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(capturedReq.GetGrant().GetExpiration()).To(BeNil())
})
It("does not apply a default expiration to a non-vault group share created without one", func() {
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("GetGroup", mock.Anything, mock.Anything).Return(getGroupResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("2"), LibreGraphRecipientType: libregraph.PtrString("group")},
}
driveItemInvite.ExpirationDateTime = nil
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(capturedReq.GetGrant().GetExpiration()).To(BeNil())
})
It("keeps a client-provided expiration instead of the default", func() {
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")},
}
explicit := time.Now().Add(time.Hour)
driveItemInvite.ExpirationDateTime = libregraph.PtrTime(explicit)
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
_, err := driveItemPermissionsService.Invite(context.Background(), driveItemId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(utils.TSToTime(capturedReq.GetGrant().GetExpiration())).To(BeTemporally("~", explicit, time.Second))
})
It("succeeds with file roles (happy path)", func() {
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).Return(createShareResponse, nil)
@@ -349,6 +464,37 @@ var _ = Describe("DriveItemPermissionsService", func() {
Expect(permission.GrantedToV2.User.GetDisplayName()).To(Equal(getUserResponse.User.DisplayName))
Expect(permission.GrantedToV2.User.GetId()).To(Equal("1"))
})
It("does not apply a default expiration to a space membership created without one", func() {
root := &provider.ResourceId{
StorageId: utils.VaultStorageProviderID,
SpaceId: "2",
OpaqueId: "2", // space root: OpaqueId == SpaceId
}
listSpacesResponse.StorageSpaces[0].SpaceType = "project"
listSpacesResponse.StorageSpaces[0].Root = root
statResponse.Info.Id = root
statResponse.Info.Space = &provider.StorageSpace{Root: root}
var capturedReq *collaboration.CreateShareRequest
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil)
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(getUserResponse, nil)
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(statResponse, nil)
gatewayClient.On("CreateShare", mock.Anything, mock.Anything).
Run(func(args mock.Arguments) {
capturedReq = args.Get(1).(*collaboration.CreateShareRequest)
}).Return(createShareResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
{ObjectId: libregraph.PtrString("1"), LibreGraphRecipientType: libregraph.PtrString("user")},
}
driveItemInvite.ExpirationDateTime = nil
createShareResponse.Share = &collaboration.Share{
Id: &collaboration.ShareId{OpaqueId: "123"},
}
_, err := driveItemPermissionsService.SpaceRootInvite(context.Background(), driveId, driveItemInvite)
Expect(err).ToNot(HaveOccurred())
Expect(capturedReq.GetGrant().GetExpiration()).To(BeNil())
})
It("rejects to add a user to a personal space", func() {
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(listSpacesResponse, nil)
driveItemInvite.Recipients = []libregraph.DriveRecipient{
+5
View File
@@ -16,6 +16,7 @@ import (
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/tags"
"github.com/owncloud/reva/v2/pkg/utils"
"go-micro.dev/v4/metadata"
)
@@ -141,6 +142,7 @@ func (g Graph) AssignTags(w http.ResponseWriter, r *http.Request) {
if g.eventsPublisher != nil {
ev := events.TagsAdded{
// The tags as requested, including any that were already present.
Tags: strings.Join(assignment.Tags, ","),
Ref: &provider.Reference{
ResourceId: &rid,
@@ -148,6 +150,7 @@ func (g Graph) AssignTags(w http.ResponseWriter, r *http.Request) {
},
SpaceOwner: sres.Info.Owner,
Executant: revaCtx.ContextMustGetUser(r.Context()).Id,
Timestamp: utils.TSNow(),
}
if err := events.Publish(r.Context(), g.eventsPublisher, ev); err != nil {
g.logger.Error().Err(err).Msg("Failed to publish TagsAdded event")
@@ -239,6 +242,7 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) {
// Always publish the event so the search index gets updated,
// even if the tag was already absent from file metadata.
ev := events.TagsRemoved{
// The tags as requested, including any that were not present.
Tags: strings.Join(unassignment.Tags, ","),
Ref: &provider.Reference{
ResourceId: &rid,
@@ -246,6 +250,7 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) {
},
SpaceOwner: sres.Info.Owner,
Executant: revaCtx.ContextMustGetUser(ctx).Id,
Timestamp: utils.TSNow(),
}
if g.publishTagsRemoved(ctx, client, ev, tagsChanged, currentTags) != nil {
w.WriteHeader(http.StatusInternalServerError)
+1 -1
View File
@@ -79,7 +79,7 @@ type LDAPDriver struct {
UserObjectClass string `yaml:"user_object_class" env:"OCIS_LDAP_USER_OBJECTCLASS;GROUPS_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
GroupObjectClass string `yaml:"group_object_class" env:"OCIS_LDAP_GROUP_OBJECTCLASS;GROUPS_LDAP_GROUP_OBJECTCLASS" desc:"The object class to use for groups in the default group search filter ('groupOfNames')." introductionVersion:"pre5.0"`
IDP string `yaml:"idp" env:"OCIS_URL;OCIS_OIDC_ISSUER;GROUPS_IDP_URL" desc:"The identity provider value to set in the group IDs of the CS3 group objects for groups returned by this group provider." introductionVersion:"pre5.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance resolves every user in the shared LDAP directory." introductionVersion:"7.0"`
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
UserSchema LDAPUserSchema `yaml:"user_schema"`
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
return shared.MissingLDAPBindPassword(cfg.Service.Name)
}
if cfg.Driver == "ldap" && cfg.Drivers.LDAP.MasterID != "" && cfg.Drivers.LDAP.UserFilter == "" {
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
}
return nil
}
@@ -0,0 +1,63 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/groups/pkg/config"
)
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "groups"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.Error(t, err)
}
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "groups"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "(ownCloudMemberOf=instance-1)",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "groups"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
+1 -1
View File
@@ -32,5 +32,5 @@ type Keycloak struct {
ClientRealm string `yaml:"client_realm" env:"OCIS_KEYCLOAK_CLIENT_REALM;INVITATIONS_KEYCLOAK_CLIENT_REALM" desc:"The realm the client is defined in." introductionVersion:"pre5.0"`
UserRealm string `yaml:"user_realm" env:"OCIS_KEYCLOAK_USER_REALM;INVITATIONS_KEYCLOAK_USER_REALM" desc:"The realm users are defined." introductionVersion:"pre5.0"`
InsecureSkipVerify bool `yaml:"insecure_skip_verify" env:"OCIS_KEYCLOAK_INSECURE_SKIP_VERIFY;INVITATIONS_KEYCLOAK_INSECURE_SKIP_VERIFY" desc:"Disable TLS certificate validation for Keycloak connections. Do not set this in production environments." introductionVersion:"pre5.0"`
ExecuteActions []string `yaml:"execute_actions" env:"INVITATIONS_KEYCLOAK_EXECUTE_ACTIONS" desc:"A comma-separated list of Keycloak required actions sent to invited guests via the execute-actions email. Values are passed to Keycloak as-is. Defaults to 'UPDATE_PASSWORD,VERIFY_EMAIL'. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
ExecuteActions []string `yaml:"execute_actions" env:"INVITATIONS_KEYCLOAK_EXECUTE_ACTIONS" desc:"A comma-separated list of Keycloak required actions sent to invited guests via the execute-actions email. Values are passed to Keycloak as-is. Defaults to 'UPDATE_PASSWORD,VERIFY_EMAIL'. See the Environment Variable Types description for more details." introductionVersion:"9.0.0"`
}
+3 -3
View File
@@ -79,7 +79,7 @@ type Store struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;NOTIFICATIONS_STORE_TTL" desc:"Time to live for notifications in the store. Defaults to '336h' (2 weeks). See the Environment Variable Types description for more details." introductionVersion:"7.1.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;NOTIFICATIONS_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"7.1.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;NOTIFICATIONS_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"7.1.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;NOTIFICATIONS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;NOTIFICATIONS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;NOTIFICATIONS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;NOTIFICATIONS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;NOTIFICATIONS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;NOTIFICATIONS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+1 -1
View File
@@ -39,7 +39,7 @@ type Config struct {
AllowPropfindDepthInfinity bool `yaml:"allow_propfind_depth_infinity" env:"OCDAV_ALLOW_PROPFIND_DEPTH_INFINITY" desc:"Allow the use of depth infinity in PROPFINDS. When enabled, a propfind will traverse through all subfolders. If many subfolders are expected, depth infinity can cause heavy server load and/or delayed response times." introductionVersion:"pre5.0"`
DisablePropfindPublicLinkResolution bool `yaml:"disable_propfind_public_link_resolution" env:"OCDAV_DISABLE_PROPFIND_PUBLIC_LINK_RESOLUTION" desc:"Disable the resolution of public link shares when answering PROPFIND requests. When disabled, the oc:share-type property will not be populated with public link share information, which can reduce load on services for large collections." introductionVersion:"8.3.0"`
DisablePropfindPublicLinkResolution bool `yaml:"disable_propfind_public_link_resolution" env:"OCDAV_DISABLE_PROPFIND_PUBLIC_LINK_RESOLUTION" desc:"Disable the resolution of public link shares when answering PROPFIND requests. When disabled, the oc:share-type property will not be populated with public link share information, which can reduce load on services for large collections." introductionVersion:"9.0.0"`
}
type Log struct {
+6 -3
View File
@@ -3,6 +3,7 @@ package revaconfig
import (
"math"
"net/url"
"path/filepath"
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
@@ -100,8 +101,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
"service_account_secret": cfg.ServiceAccount.Secret,
},
"dataprovider": map[string]interface{}{
"prefix": "data",
"driver": "ocmreceived",
"prefix": "data",
"driver": "ocmreceived",
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
@@ -190,7 +192,8 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
},
},
"storageprovider": map[string]interface{}{
"driver": "ocmreceived",
"driver": "ocmreceived",
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
+3 -3
View File
@@ -38,7 +38,7 @@ type SigningKeys struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;OCS_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"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the signing key store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the signing key store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the signing key store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the signing key store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the signing key store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;OCS_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the signing key store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+3 -3
View File
@@ -64,7 +64,7 @@ type Store struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;POSTPROCESSING_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;POSTPROCESSING_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;POSTPROCESSING_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;POSTPROCESSING_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;POSTPROCESSING_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;POSTPROCESSING_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;POSTPROCESSING_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;POSTPROCESSING_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;POSTPROCESSING_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+8 -4
View File
@@ -287,15 +287,19 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
if cfg.EnableBasicAuth {
logger.Warn().Msg("basic auth enabled, use only for testing or development")
authenticators = append(authenticators, middleware.BasicAuthenticator{
Logger: logger,
UserProvider: userProvider,
Logger: logger,
UserProvider: userProvider,
UserRoleAssigner: roleAssigner,
MultiInstanceEnabled: cfg.MultiInstance.Enabled,
})
}
if cfg.AuthMiddleware.AllowAppAuth {
authenticators = append(authenticators, middleware.AppAuthAuthenticator{
Logger: logger,
RevaGatewaySelector: gatewaySelector,
Logger: logger,
RevaGatewaySelector: gatewaySelector,
UserRoleAssigner: roleAssigner,
MultiInstanceEnabled: cfg.MultiInstance.Enabled,
})
}
+6 -6
View File
@@ -147,9 +147,9 @@ type Cache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;PROXY_OIDC_USERINFO_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"pre5.0"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;PROXY_OIDC_USERINFO_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;PROXY_OIDC_USERINFO_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;PROXY_OIDC_USERINFO_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;PROXY_OIDC_USERINFO_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;PROXY_OIDC_USERINFO_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;PROXY_OIDC_USERINFO_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;PROXY_OIDC_USERINFO_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;PROXY_OIDC_USERINFO_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// RoleAssignment contains the configuration for how to assign roles to users during login
@@ -205,9 +205,9 @@ type SigningKeys struct {
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"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the signing key store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the signing key store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the signing key store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the signing key store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the signing key store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;PROXY_PRESIGNEDURL_SIGNING_KEYS_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the signing key store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// ClaimsSelectorConf is the config for the claims-selector
@@ -105,6 +105,15 @@ func (m accountResolver) verifyUser(w http.ResponseWriter, req *http.Request, us
return
}
if errors.Is(err, backend.ErrAccountNotFound) {
// the identity backend excludes disabled accounts from by-claim
// lookups, so a disabled account also ends up here, not just a
// genuinely unknown username.
m.logger.Debug().Interface("user", user).Msg("Not found")
w.WriteHeader(http.StatusUnauthorized)
return
}
if err != nil {
m.logger.Error().Err(err).Msg("Could not get user by claim")
w.WriteHeader(http.StatusInternalServerError)
@@ -472,3 +472,35 @@ func TestResolveUserType(t *testing.T) {
})
}
}
// TestVerifyUserUnauthorizedOnUserNotFound covers the verifyUser fast path
// (user already in context, e.g. via AppAuthAuthenticator/BasicAuthenticator),
// as opposed to TestUnauthorizedOnUserNotFound which covers the claims-based
// resolveUserFromClaims path. A disabled account is looked up by username and
// comes back as ErrAccountNotFound (the identity backend excludes disabled
// accounts from by-claim lookups), which must map to 401, not 500.
func TestVerifyUserUnauthorizedOnUserNotFound(t *testing.T) {
user := &userv1beta1.User{
Id: &userv1beta1.UserId{Idp: "https://idx.example.com", OpaqueId: "123"},
Username: "alice",
}
ub := mocks.UserBackend{}
ub.On("GetUserByClaims", mock.Anything, "username", "alice").Return(nil, "", backend.ErrAccountNotFound)
ra := userRoleMocks.UserRoleAssigner{}
sut := AccountResolver(
Logger(log.NewLogger()),
UserProvider(&ub),
UserRoleAssigner(&ra),
)(mockHandler{})
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
req = req.WithContext(revactx.ContextSetUser(context.Background(), user))
rw := httptest.NewRecorder()
sut.ServeHTTP(rw, req)
assert.Equal(t, http.StatusUnauthorized, rw.Code)
}
+26 -13
View File
@@ -6,15 +6,17 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
cs3rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
)
// AppAuthAuthenticator defines the app auth authenticator
type AppAuthAuthenticator struct {
Logger log.Logger
RevaGatewaySelector pool.Selectable[gateway.GatewayAPIClient]
Logger log.Logger
RevaGatewaySelector pool.Selectable[gateway.GatewayAPIClient]
UserRoleAssigner userroles.UserRoleAssigner
MultiInstanceEnabled bool
}
// Authenticate implements the authenticator interface to authenticate requests via app auth.
@@ -26,6 +28,15 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, erro
return nil, ErrAuthenticationFailed
}
if m.MultiInstanceEnabled {
// App passwords carry no OIDC claims, so there is no way to verify
// tenant membership (OCIS_MULTI_INSTANCE_MEMBER_CLAIM/GUEST_CLAIM)
// for them. Reject rather than let the request bypass the tenant
// check in services/proxy/pkg/middleware/account_resolver.go's
// resolveUserType.
return nil, ErrAuthenticationFailed
}
username, password, ok := r.BasicAuth()
if !ok {
return nil, ErrAuthenticationFailed
@@ -48,17 +59,19 @@ func (m AppAuthAuthenticator) Authenticate(r *http.Request) (*http.Request, erro
return nil, ErrAuthenticationFailed
}
r.Header.Set(revactx.TokenHeader, authenticateResponse.GetToken())
user := authenticateResponse.GetUser()
// fake oidc claims for the account resolver
claims := map[string]interface{}{
oidc.Iss: user.GetId().GetIdp(),
oidc.PreferredUsername: user.GetUsername(),
oidc.Email: user.GetMail(),
oidc.OwncloudUUID: user.GetId().GetOpaqueId(),
user, err := m.UserRoleAssigner.ApplyUserRole(r.Context(), authenticateResponse.GetUser())
if err != nil {
m.Logger.Error().Err(err).Msg("could not apply user role")
return nil, ErrAuthenticationFailed
}
r = r.WithContext(oidc.NewContext(r.Context(), claims))
// only mutate the request once we know we're returning success, so a
// failed authentication attempt can't leave a stale access token behind
// for a later authenticator in the chain to build on.
r.Header.Set(revactx.TokenHeader, authenticateResponse.GetToken())
// the user is already authenticated, put it into the context directly
// instead of faking oidc claims for the account resolver to re-resolve.
r = r.WithContext(revactx.ContextSetUser(r.Context(), user))
return r, nil
}
+91 -8
View File
@@ -1,27 +1,41 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
backendmocks "github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
"github.com/owncloud/reva/v2/pkg/auth/scope"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/token/manager/jwt"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
)
var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func() {
var authenticator Authenticator
var roleAssigner *mocks.UserRoleAssigner
BeforeEach(func() {
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
roleAssigner = &mocks.UserRoleAssigner{}
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
).Maybe()
authenticator = AppAuthAuthenticator{
Logger: log.NewLogger(),
Logger: log.NewLogger(),
UserRoleAssigner: roleAssigner,
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
@@ -68,12 +82,81 @@ var _ = Describe("Authenticating requests", Label("AppAuthAuthenticator"), func(
Expect(req2).ToNot(BeNil())
Expect(req2.Header.Get("x-access-token")).To(Equal("reva-token"))
claims := oidc.FromContext(req2.Context())
Expect(claims).ToNot(BeNil())
Expect(claims[oidc.Iss]).To(Equal("testIDP"))
Expect(claims[oidc.PreferredUsername]).To(Equal("alice"))
Expect(claims[oidc.Email]).To(Equal("alice@example.prv"))
Expect(claims[oidc.OwncloudUUID]).To(Equal("abcd-1234"))
user, ok := revactx.ContextGetUser(req2.Context())
Expect(ok).To(Equal(true))
Expect(user.GetId().GetIdp()).To(Equal("testIDP"))
Expect(user.GetId().GetOpaqueId()).To(Equal("abcd-1234"))
Expect(user.GetUsername()).To(Equal("alice"))
Expect(user.GetMail()).To(Equal("alice@example.prv"))
})
})
When("multi-instance mode is enabled", func() {
It("rejects the request, since app passwords carry no tenant-membership claims", func() {
multiInstanceAuthenticator := AppAuthAuthenticator{
Logger: log.NewLogger(),
UserRoleAssigner: roleAssigner,
MultiInstanceEnabled: true,
RevaGatewaySelector: pool.GetSelector[gateway.GatewayAPIClient](
"GatewaySelector",
"com.owncloud.api.gateway",
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
return mockGatewayClient{
AuthenticateFunc: func(authType, clientID, clientSecret string) *gateway.AuthenticateResponse {
return &gateway.AuthenticateResponse{Status: &rpcv1beta1.Status{Code: rpcv1beta1.Code_CODE_OK}}
},
}
},
),
}
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
req.SetBasicAuth("test-user", "AppPassword")
req2, err := multiInstanceAuthenticator.Authenticate(req)
Expect(err).To(HaveOccurred())
Expect(req2).To(BeNil())
})
})
When("the account resolver is configured with a non-default PROXY_USER_OIDC_CLAIM", func() {
It("still resolves the already-authenticated user, bypassing claim-based lookup", func() {
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me", http.NoBody)
req.SetBasicAuth("test-user", "AppPassword")
authenticatedReq, err := authenticator.Authenticate(req)
Expect(err).ToNot(HaveOccurred())
resolvedUser := &userv1beta1.User{
Id: &userv1beta1.UserId{Idp: "testIDP", OpaqueId: "abcd-1234"},
Username: "alice",
}
tokenManager, err := jwt.New(map[string]interface{}{"secret": "change-me", "expires": int64(60)})
Expect(err).ToNot(HaveOccurred())
s, err := scope.AddOwnerScope(nil)
Expect(err).ToNot(HaveOccurred())
token, err := tokenManager.MintToken(context.Background(), resolvedUser, s)
Expect(err).ToNot(HaveOccurred())
ub := backendmocks.UserBackend{}
// services/proxy/pkg/middleware/account_resolver.go's verifyUser always looks
// up the user by "username", regardless of the configured PROXY_USER_OIDC_CLAIM,
// because the user arrives already authenticated via the request context.
ub.On("GetUserByClaims", mock.Anything, "username", "alice", mock.Anything).Return(resolvedUser, token, nil)
resolver := AccountResolver(
Logger(log.NewLogger()),
UserProvider(&ub),
UserRoleAssigner(roleAssigner),
UserOIDCClaim("sub"),
UserCS3Claim("userid"),
)(mockHandler{})
rw := httptest.NewRecorder()
resolver.ServeHTTP(rw, authenticatedReq)
Expect(rw.Code).To(Equal(http.StatusOK))
})
})
@@ -20,6 +20,8 @@ import (
"github.com/owncloud/ocis/v2/services/proxy/pkg/router"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
userRoleMocks "github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/stretchr/testify/mock"
"go-micro.dev/v4/store"
@@ -81,10 +83,17 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
logger := log.NewLogger()
roleAssigner := &userRoleMocks.UserRoleAssigner{}
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
).Maybe()
authenticators = []Authenticator{
BasicAuthenticator{
Logger: logger,
UserProvider: &ub,
Logger: logger,
UserProvider: &ub,
UserRoleAssigner: roleAssigner,
},
&OIDCAuthenticator{
OIDCIss: "http://idp.example.com",
@@ -151,7 +160,7 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
testHandler.ServeHTTP(rr, req)
Expect(rr).To(HaveHTTPStatus(http.StatusOK))
})
It("ensures the context oidc data when user the Basic authentication is successful", func() {
It("ensures the authenticated user is in the context when the Basic authentication is successful", func() {
req := httptest.NewRequest("PROPFIND", "http://example.com/remote.php/dav/public-files/", http.NoBody)
req = req.WithContext(router.SetRoutingInfo(context.Background(), router.RoutingInfo{}))
req.SetBasicAuth("testuser", "testpassword")
@@ -160,12 +169,12 @@ var _ = Describe("Authenticating requests", Label("Authentication"), func() {
EnableBasicAuth(true),
)
testHandler := handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expect(oidc.FromContext(r.Context())).To(Equal(map[string]interface{}{
"email": "testuser@example.com",
"ownclouduuid": "OpaqueId",
"iss": "IdpId",
"preferred_username": "testuser",
}))
user, ok := revactx.ContextGetUser(r.Context())
Expect(ok).To(Equal(true))
Expect(user.GetId().GetIdp()).To(Equal("IdpId"))
Expect(user.GetId().GetOpaqueId()).To(Equal("OpaqueId"))
Expect(user.GetUsername()).To(Equal("testuser"))
Expect(user.GetMail()).To(Equal("testuser@example.com"))
}))
rr := httptest.NewRecorder()
testHandler.ServeHTTP(rr, req)
+26 -18
View File
@@ -4,16 +4,17 @@ import (
"net/http"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
"github.com/owncloud/ocis/v2/services/proxy/pkg/userroles"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
)
// BasicAuthenticator is the authenticator responsible for HTTP Basic authentication.
type BasicAuthenticator struct {
Logger log.Logger
UserProvider backend.UserBackend
UserCS3Claim string
UserOIDCClaim string
Logger log.Logger
UserProvider backend.UserBackend
UserRoleAssigner userroles.UserRoleAssigner
MultiInstanceEnabled bool
}
// Authenticate implements the authenticator interface to authenticate requests via basic auth.
@@ -25,6 +26,15 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, error)
return nil, ErrAuthenticationFailed
}
if m.MultiInstanceEnabled {
// Basic auth credentials carry no OIDC claims, so there is no way to
// verify tenant membership (OCIS_MULTI_INSTANCE_MEMBER_CLAIM/GUEST_CLAIM)
// for them. Reject rather than let the request bypass the tenant
// check in services/proxy/pkg/middleware/account_resolver.go's
// resolveUserType.
return nil, ErrAuthenticationFailed
}
login, password, ok := r.BasicAuth()
if !ok {
return nil, ErrAuthenticationFailed
@@ -40,23 +50,21 @@ func (m BasicAuthenticator) Authenticate(r *http.Request) (*http.Request, error)
return nil, ErrAuthenticationFailed
}
// fake oidc claims
claims := map[string]interface{}{
oidc.Iss: user.Id.Idp,
oidc.PreferredUsername: user.Username,
oidc.Email: user.Mail,
oidc.OwncloudUUID: user.Id.OpaqueId,
user, err = m.UserRoleAssigner.ApplyUserRole(r.Context(), user)
if err != nil {
m.Logger.Error().
Err(err).
Str("authenticator", "basic").
Str("path", r.URL.Path).
Msg("could not apply user role")
return nil, ErrAuthenticationFailed
}
if m.UserCS3Claim == "userid" {
// set the custom user claim only if users will be looked up by the userid on the CS3api
// OpaqueId contains the userid configured in STORAGE_LDAP_USER_SCHEMA_UID
claims[m.UserOIDCClaim] = user.Id.OpaqueId
}
m.Logger.Debug().
Str("authenticator", "basic").
Str("path", r.URL.Path).
Msg("successfully authenticated request")
return r.WithContext(oidc.NewContext(r.Context(), claims)), nil
// the user is already authenticated, put it into the context directly
// instead of faking oidc claims for the account resolver to re-resolve.
return r.WithContext(revactx.ContextSetUser(r.Context(), user)), nil
}
@@ -1,6 +1,7 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
@@ -10,13 +11,17 @@ import (
. "github.com/onsi/gomega"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend"
"github.com/owncloud/ocis/v2/services/proxy/pkg/user/backend/mocks"
userRoleMocks "github.com/owncloud/ocis/v2/services/proxy/pkg/userroles/mocks"
"github.com/owncloud/reva/v2/pkg/auth/scope"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/token/manager/jwt"
)
var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func() {
var authenticator Authenticator
var roleAssigner *userRoleMocks.UserRoleAssigner
ub := mocks.UserBackend{}
ub.On("Authenticate", mock.Anything, "testuser", "testpassword").Return(
&userv1beta1.User{
@@ -33,9 +38,15 @@ var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func()
ub.On("Authenticate", mock.Anything, mock.Anything, mock.Anything).Return(nil, "", backend.ErrAccountNotFound)
BeforeEach(func() {
roleAssigner = &userRoleMocks.UserRoleAssigner{}
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
).Maybe()
authenticator = BasicAuthenticator{
Logger: log.NewLogger(),
UserProvider: &ub,
Logger: log.NewLogger(),
UserProvider: &ub,
UserRoleAssigner: roleAssigner,
}
})
@@ -49,19 +60,83 @@ var _ = Describe("Authenticating requests", Label("BasicAuthenticator"), func()
Expect(err).ToNot(HaveOccurred())
Expect(req2).ToNot(BeNil())
})
It("adds claims to the request context", func() {
It("puts the authenticated user into the request context", func() {
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
req.SetBasicAuth("testuser", "testpassword")
req2, err := authenticator.Authenticate(req)
Expect(err).ToNot(HaveOccurred())
claims := oidc.FromContext(req2.Context())
Expect(claims).ToNot(BeNil())
Expect(claims[oidc.Iss]).To(Equal("IdpId"))
Expect(claims[oidc.PreferredUsername]).To(Equal("testuser"))
Expect(claims[oidc.Email]).To(Equal("testuser@example.com"))
Expect(claims[oidc.OwncloudUUID]).To(Equal("OpaqueId"))
user, ok := revactx.ContextGetUser(req2.Context())
Expect(ok).To(Equal(true))
Expect(user.GetId().GetIdp()).To(Equal("IdpId"))
Expect(user.GetId().GetOpaqueId()).To(Equal("OpaqueId"))
Expect(user.GetUsername()).To(Equal("testuser"))
Expect(user.GetMail()).To(Equal("testuser@example.com"))
})
})
When("multi-instance mode is enabled", func() {
It("rejects the request, since basic auth credentials carry no tenant-membership claims", func() {
multiInstanceAuthenticator := BasicAuthenticator{
Logger: log.NewLogger(),
UserProvider: &ub,
UserRoleAssigner: roleAssigner,
MultiInstanceEnabled: true,
}
req := httptest.NewRequest(http.MethodGet, "http://example.com/example/path", http.NoBody)
req.SetBasicAuth("testuser", "testpassword")
req2, err := multiInstanceAuthenticator.Authenticate(req)
Expect(err).To(HaveOccurred())
Expect(req2).To(BeNil())
})
})
When("the account resolver is configured with a non-default PROXY_USER_OIDC_CLAIM", func() {
It("still resolves the already-authenticated user, bypassing claim-based lookup", func() {
req := httptest.NewRequest(http.MethodGet, "http://example.com/graph/v1.0/me", http.NoBody)
req.SetBasicAuth("testuser", "testpassword")
authenticatedReq, err := authenticator.Authenticate(req)
Expect(err).ToNot(HaveOccurred())
resolvedUser := &userv1beta1.User{
Id: &userv1beta1.UserId{Idp: "IdpId", OpaqueId: "OpaqueId"},
Username: "testuser",
}
tokenManager, err := jwt.New(map[string]interface{}{"secret": "change-me", "expires": int64(60)})
Expect(err).ToNot(HaveOccurred())
s, err := scope.AddOwnerScope(nil)
Expect(err).ToNot(HaveOccurred())
token, err := tokenManager.MintToken(context.Background(), resolvedUser, s)
Expect(err).ToNot(HaveOccurred())
resolverBackend := mocks.UserBackend{}
// services/proxy/pkg/middleware/account_resolver.go's verifyUser always looks
// up the user by "username", regardless of the configured PROXY_USER_OIDC_CLAIM,
// because the user arrives already authenticated via the request context.
resolverBackend.On("GetUserByClaims", mock.Anything, "username", "testuser", mock.Anything).Return(resolvedUser, token, nil)
roleAssigner := &userRoleMocks.UserRoleAssigner{}
roleAssigner.EXPECT().ApplyUserRole(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, user *userv1beta1.User) (*userv1beta1.User, error) { return user, nil },
).Maybe()
resolver := AccountResolver(
Logger(log.NewLogger()),
UserProvider(&resolverBackend),
UserRoleAssigner(roleAssigner),
UserOIDCClaim("sub"),
UserCS3Claim("userid"),
)(mockHandler{})
rw := httptest.NewRecorder()
resolver.ServeHTTP(rw, authenticatedReq)
Expect(rw.Code).To(Equal(http.StatusOK))
})
})
})
+5 -1
View File
@@ -58,7 +58,11 @@ func (m *createHome) ServeHTTP(w http.ResponseWriter, req *http.Request) {
createHomeReq := &provider.CreateHomeRequest{}
u, ok := revactx.ContextGetUser(ctx)
if !ok || u == nil {
m.logger.Error().Msg("no user in context")
// Requests on unprotected routes can carry a reva token without a resolved
// user, e.g. the internal download requests to the data gateway (/data), which
// reva's HTTP client sends with the caller's token. There is no home to create
// for them, so this is expected and not an error.
m.logger.Debug().Str("path", req.URL.Path).Msg("no user in context, not creating a home")
m.next.ServeHTTP(w, req)
return
}
@@ -0,0 +1,39 @@
package middleware
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)
// A request with a reva token but no user, like reva's internal download requests to
// the data gateway, is passed on unchanged and does not log an error.
func TestCreateHomeWithoutUserPassesThroughQuietly(t *testing.T) {
// Other tests in this package raise the global level; let error lines through.
defer zerolog.SetGlobalLevel(zerolog.GlobalLevel())
zerolog.SetGlobalLevel(zerolog.TraceLevel)
var buf bytes.Buffer
logger := log.Logger{Logger: zerolog.New(&buf).Level(zerolog.InfoLevel)}
nextCalled := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
})
sut := CreateHome(Logger(logger))(next)
req := httptest.NewRequest(http.MethodGet, "/data/some-transfer-token", nil)
req.Header.Set("x-access-token", "a-token")
rw := httptest.NewRecorder()
sut.ServeHTTP(rw, req)
assert.True(t, nextCalled)
assert.Equal(t, http.StatusOK, rw.Code)
assert.Empty(t, buf.String())
}
+8 -25
View File
@@ -4,11 +4,7 @@ import (
"context"
cs3 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
"github.com/owncloud/reva/v2/pkg/utils"
"go-micro.dev/v4/metadata"
)
type defaultRoleAssigner struct {
@@ -39,27 +35,9 @@ func (d defaultRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user
return nil, err
}
if len(roleIDs) == 0 {
// This user doesn't have a role assignment yet. Assign a
// default user role. At least until proper roles are provided. See
// https://github.com/owncloud/ocis/issues/1825 for more context.
if user.Id.Type == cs3.UserType_USER_TYPE_PRIMARY || user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
roleId := settingsService.BundleUUIDRoleUser
if user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
roleId = settingsService.BundleUUIDRoleUserLight
}
d.logger.Info().Str("userid", user.Id.OpaqueId).Msg("user has no role assigned, assigning default user role")
ctx = metadata.Set(ctx, middleware.AccountID, user.Id.OpaqueId)
_, err := d.roleService.AssignRoleToUser(ctx, &settingssvc.AssignRoleToUserRequest{
AccountUuid: user.Id.OpaqueId,
RoleId: roleId,
})
if err != nil {
d.logger.Error().Err(err).Msg("Could not add default role")
return nil, err
}
roleIDs = append(roleIDs, roleId)
}
roleIDs, err = bootstrapDefaultRoleIfNeeded(ctx, user, roleIDs, d.roleService, d.logger)
if err != nil {
return nil, err
}
}
@@ -76,6 +54,11 @@ func (d defaultRoleAssigner) ApplyUserRole(ctx context.Context, user *cs3.User)
return nil, err
}
roleIDs, err = bootstrapDefaultRoleIfNeeded(ctx, user, roleIDs, d.roleService, d.logger)
if err != nil {
return nil, err
}
user.Opaque = utils.AppendJSONToOpaque(user.Opaque, "roles", roleIDs)
return user, nil
}
@@ -0,0 +1,79 @@
package userroles
import (
"context"
"testing"
cs3user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
settingsmsg "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
graphmocks "github.com/owncloud/ocis/v2/services/graph/mocks"
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/stretchr/testify/mock"
)
// TestApplyUserRoleBootstrapsDefaultRoleForNewUser verifies that ApplyUserRole,
// just like UpdateUserRoleAssignment, assigns a default role to a user who
// doesn't have one yet. This matters for authentication paths (such as app
// passwords) that only call ApplyUserRole and never go through claims-based
// UpdateUserRoleAssignment, so a user who never logged in interactively must
// still end up with a role.
func TestApplyUserRoleBootstrapsDefaultRoleForNewUser(t *testing.T) {
const userOpaqueID = "user-1"
roleService := &graphmocks.RoleService{}
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListRoleAssignmentsResponse{}, nil)
roleService.On("AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == settingsService.BundleUUIDRoleUser
}), mock.Anything).Return(&settingssvc.AssignRoleToUserResponse{Assignment: &settingsmsg.UserRoleAssignment{
Id: "new-assignment-id",
AccountUuid: userOpaqueID,
RoleId: settingsService.BundleUUIDRoleUser,
}}, nil)
ra := NewDefaultRoleAssigner(WithRoleService(roleService), WithLogger(log.NopLogger()))
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID, Type: cs3user.UserType_USER_TYPE_PRIMARY}}
updated, err := ra.ApplyUserRole(context.Background(), user)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var roleIDs []string
if err := utils.ReadJSONFromOpaque(updated.GetOpaque(), "roles", &roleIDs); err != nil {
t.Fatalf("could not read roles from opaque: %v", err)
}
if len(roleIDs) != 1 || roleIDs[0] != settingsService.BundleUUIDRoleUser {
t.Fatalf("expected the default user role to be bootstrapped, got %v", roleIDs)
}
roleService.AssertCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == settingsService.BundleUUIDRoleUser
}), mock.Anything)
}
// TestApplyUserRoleDoesNotBootstrapForLightweightUser verifies that
// ApplyUserRole never assigns a default role to a lightweight (federated)
// user, mirroring UpdateUserRoleAssignment's existing behavior.
func TestApplyUserRoleDoesNotBootstrapForLightweightUser(t *testing.T) {
const userOpaqueID = "lightweight-user-1"
roleService := &graphmocks.RoleService{}
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
&settingssvc.ListRoleAssignmentsResponse{}, nil)
ra := NewDefaultRoleAssigner(WithRoleService(roleService), WithLogger(log.NopLogger()))
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID, Type: cs3user.UserType_USER_TYPE_LIGHTWEIGHT}}
_, err := ra.ApplyUserRole(context.Background(), user)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
}
+32
View File
@@ -6,9 +6,12 @@ import (
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
cs3 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
ocismiddleware "github.com/owncloud/ocis/v2/ocis-pkg/middleware"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
settingsService "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"go-micro.dev/v4/metadata"
)
// UserRoleAssigner allows providing different implementations for how users get their default roles
@@ -77,6 +80,35 @@ func WithServiceAccount(c config.ServiceAccount) Option {
}
}
// bootstrapDefaultRoleIfNeeded assigns the default "User" role (or "User Light"
// for guests) when the user has no role assignment yet, so that users who only
// ever authenticate without going through UpdateUserRoleAssignment (e.g. via an
// app password) still end up with a role. See
// https://github.com/owncloud/ocis/issues/1825 for context.
func bootstrapDefaultRoleIfNeeded(ctx context.Context, user *cs3.User, roleIDs []string, roleService settingssvc.RoleService, logger log.Logger) ([]string, error) {
if len(roleIDs) != 0 {
return roleIDs, nil
}
if user.Id.Type != cs3.UserType_USER_TYPE_PRIMARY && user.Id.Type != cs3.UserType_USER_TYPE_GUEST {
return roleIDs, nil
}
roleID := settingsService.BundleUUIDRoleUser
if user.Id.Type == cs3.UserType_USER_TYPE_GUEST {
roleID = settingsService.BundleUUIDRoleUserLight
}
logger.Info().Str("userid", user.Id.OpaqueId).Msg("user has no role assigned, assigning default user role")
ctx = metadata.Set(ctx, ocismiddleware.AccountID, user.Id.OpaqueId)
if _, err := roleService.AssignRoleToUser(ctx, &settingssvc.AssignRoleToUserRequest{
AccountUuid: user.Id.OpaqueId,
RoleId: roleID,
}); err != nil {
logger.Error().Err(err).Msg("Could not add default role")
return nil, err
}
return append(roleIDs, roleID), nil
}
// loadRolesIDs returns the role-ids assigned to an user
func loadRolesIDs(ctx context.Context, opaqueUserID string, rs settingssvc.RoleService) ([]string, error) {
req := &settingssvc.ListRoleAssignmentsRequest{AccountUuid: opaqueUserID}
+4
View File
@@ -170,6 +170,10 @@ ocis search index --all-spaces
Note that either `--space $SPACE_ID` or `--all-spaces` must be set.
The command does not open the index itself: it asks the running search service to do the indexing over gRPC. The search service must therefore be running, and the command works with the default `SEARCH_ENGINE_BLEVE_SCALE=false` (see [Scaling](#scaling)); the service's exclusive lock on the index does not block it.
The command waits for the service to walk the space and gives up after 10 minutes by default. The walk is cancelled when that happens, so a large space, or one where the content extractor is slow on a few files, may need a longer limit: `--timeout 2h` (a Go duration; `0` waits indefinitely).
## Notes
The indexing process tries to be self-healing in some situations.
+20 -2
View File
@@ -17,7 +17,12 @@ import (
"github.com/owncloud/ocis/v2/services/search/pkg/config/parser"
)
// Index is the entrypoint for the server command.
// _noTimeout stands in for "no limit" when --timeout is 0: go-micro treats a
// zero RequestTimeout as an immediately expired deadline, so a far-off one is
// used instead.
const _noTimeout = 100 * 365 * 24 * time.Hour
// Index is the entrypoint for the index command.
func Index(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "index",
@@ -34,6 +39,11 @@ func Index(cfg *config.Config) *cli.Command {
Name: "all-spaces",
Usage: "index all spaces instead. This or --space is required.",
},
&cli.DurationFlag{
Name: "timeout",
Usage: "how long to wait for the indexing to finish before giving up, e.g. 2h. The walk is cancelled when the timeout expires. 0 waits indefinitely.",
Value: 10 * time.Minute,
},
},
Before: func(_ *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
@@ -57,10 +67,18 @@ func Index(cfg *config.Config) *cli.Command {
return err
}
// The service walks the whole space inside this request, so the
// request timeout bounds the walk: when it expires the walk is
// cancelled and everything after that point stays unindexed.
timeout := ctx.Duration("timeout")
if timeout <= 0 {
timeout = _noTimeout
}
c := searchsvc.NewSearchProviderService("com.owncloud.api.search", grpcClient)
_, err = c.IndexSpace(context.Background(), &searchsvc.IndexSpaceRequest{
SpaceId: ctx.String("space"),
}, func(opts *client.CallOptions) { opts.RequestTimeout = 10 * time.Minute })
}, func(opts *client.CallOptions) { opts.RequestTimeout = timeout })
if err != nil {
fmt.Println("failed to index space: " + err.Error())
return err
+3 -3
View File
@@ -66,7 +66,7 @@ type Cache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;SETTINGS_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;SETTINGS_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;SETTINGS_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;SETTINGS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;SETTINGS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;SETTINGS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;SETTINGS_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;SETTINGS_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;SETTINGS_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+2 -2
View File
@@ -27,8 +27,8 @@ type Config struct {
PublicSharingDrivers PublicSharingDrivers `yaml:"public_sharing_drivers"`
WriteableShareMustHavePassword bool `yaml:"public_sharing_writeableshare_must_have_password" env:"OCIS_SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD;SHARING_PUBLIC_WRITEABLE_SHARE_MUST_HAVE_PASSWORD" desc:"Set this to true if you want to enforce passwords on Uploader, Editor or Contributor shares." introductionVersion:"5.0"`
PublicShareMustHavePassword bool `yaml:"public_sharing_share_must_have_password" env:"OCIS_SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD;SHARING_PUBLIC_SHARE_MUST_HAVE_PASSWORD" desc:"Set this to true if you want to enforce passwords on all public shares." introductionVersion:"5.0"`
EnableExpiredSharesCleanup bool `yaml:"enable_expired_shares_cleanup" env:"OCIS_SHARING_ENABLE_EXPIRED_SHARES_CLEANUP;SHARING_ENABLE_EXPIRED_SHARES_CLEANUP" desc:"Enable the periodic removal of expired public shares. When disabled, expired shares are still hidden from listings but never actually deleted." introductionVersion:"8.3.0"`
JanitorRunInterval int `yaml:"janitor_run_interval" env:"OCIS_SHARING_JANITOR_RUN_INTERVAL;SHARING_JANITOR_RUN_INTERVAL" desc:"Interval in seconds between two runs of the janitor that permanently deletes expired public shares. Defaults to '3600' (1 hour). Only relevant when OCIS_SHARING_ENABLE_EXPIRED_SHARES_CLEANUP is enabled." introductionVersion:"8.3.0"`
EnableExpiredSharesCleanup bool `yaml:"enable_expired_shares_cleanup" env:"OCIS_SHARING_ENABLE_EXPIRED_SHARES_CLEANUP;SHARING_ENABLE_EXPIRED_SHARES_CLEANUP" desc:"Enable the periodic removal of expired public shares. When disabled, expired shares are still hidden from listings but never actually deleted." introductionVersion:"9.0.0"`
JanitorRunInterval int `yaml:"janitor_run_interval" env:"OCIS_SHARING_JANITOR_RUN_INTERVAL;SHARING_JANITOR_RUN_INTERVAL" desc:"Interval in seconds between two runs of the janitor that permanently deletes expired public shares. Defaults to '3600' (1 hour). Only relevant when OCIS_SHARING_ENABLE_EXPIRED_SHARES_CLEANUP is enabled." introductionVersion:"9.0.0"`
EnableUserSharing bool `yaml:"enable_user_sharing" env:"OCIS_ENABLE_USER_SHARING" desc:"Enables direct sharing with users and groups. When disabled, creating new user or group shares is rejected. Public link sharing is not affected." introductionVersion:"8.2.0"`
EnablePublicSharing bool `yaml:"enable_public_sharing" env:"OCIS_ENABLE_PUBLIC_SHARING" desc:"Enables public link sharing. When disabled, creating new public links is rejected. Direct sharing with users and groups is not affected." introductionVersion:"8.2.0"`
PasswordPolicy PasswordPolicy `yaml:"password_policy"`
@@ -70,7 +70,7 @@ type Store struct {
Table string `yaml:"table" env:"STORAGE_PUBLICLINK_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"8.0.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;STORAGE_PUBLICLINK_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.0.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;STORAGE_PUBLICLINK_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.0.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;STORAGE_PUBLICLINK_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;STORAGE_PUBLICLINK_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;STORAGE_PUBLICLINK_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;STORAGE_PUBLICLINK_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;STORAGE_PUBLICLINK_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;STORAGE_PUBLICLINK_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+3 -3
View File
@@ -93,7 +93,7 @@ type Cache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_SYSTEM_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"auth_username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_SYSTEM_CACHE_AUTH_USERNAME" desc:"Username for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_SYSTEM_CACHE_AUTH_PASSWORD" desc:"Password for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_SYSTEM_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_SYSTEM_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_SYSTEM_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_SYSTEM_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_SYSTEM_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_SYSTEM_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
+13 -5
View File
@@ -22,12 +22,14 @@ import (
"github.com/owncloud/ocis/v2/services/storage-users/pkg/config"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/config/parser"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/event"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/logging"
"github.com/owncloud/ocis/v2/services/storage-users/pkg/revaconfig"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/lookup"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/node"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -125,15 +127,21 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
os.Exit(1)
}
drivers := revaconfig.StorageProviderDrivers(cfg)
fs, err := f(drivers[cfg.Driver].(map[string]interface{}), nil, nil)
driverConf, ok := drivers[cfg.Driver].(map[string]interface{})
if !ok {
fmt.Fprintf(os.Stderr, "No configuration found for filesystem driver '%s'\n", cfg.Driver)
os.Exit(1)
}
fs, err := f(driverConf, nil, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize filesystem driver '%s'\n", cfg.Driver)
return err
}
managingFS, ok := fs.(storage.UploadSessionLister)
if !ok {
fmt.Fprintf(os.Stderr, "'%s' storage does not support listing upload sessions\n", cfg.Driver)
logger := logging.Configure(cfg.Service.Name, cfg.Log)
coord, err := upload.NewCoordinatorFromConfig("", driverConf, fs, nil, &logger.Logger, false)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to initialize the upload coordinator: %v\n", err)
os.Exit(1)
}
@@ -147,7 +155,7 @@ func ListUploadSessions(cfg *config.Config) *cli.Command {
}
filter := buildFilter(c)
uploads, err := managingFS.ListUploadSessions(c.Context, filter)
uploads, err := coord.ListUploadSessions(c.Context, filter)
if err != nil {
return err
}
+6 -6
View File
@@ -231,9 +231,9 @@ type FilemetadataCache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// IDCache holds cache config
@@ -245,9 +245,9 @@ type IDCache struct {
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// S3Driver is the storage driver configuration when using 's3' storage driver
@@ -87,6 +87,7 @@ func StorageUsersConfigFromStruct(cfg *config.Config) map[string]interface{} {
"prefix": cfg.HTTP.Prefix,
"driver": cfg.Driver,
"drivers": DataProviderDrivers(cfg),
"mount_id": cfg.MountID,
"nats_address": cfg.Events.Addr,
"nats_clusterID": cfg.Events.ClusterID,
"nats_tls_insecure": cfg.Events.TLSInsecure,
+3 -3
View File
@@ -48,9 +48,9 @@ type Persistence struct {
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;USERLOG_STORE_TTL" desc:"Time to live for events in the store. Defaults to '336h' (2 weeks). See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;USERLOG_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;USERLOG_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;USERLOG_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;USERLOG_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"8.3.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;USERLOG_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;USERLOG_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;USERLOG_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;USERLOG_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
}
// Events combines the configuration options for the event bus.
+1 -1
View File
@@ -84,7 +84,7 @@ type LDAPDriver struct {
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;USERS_LDAP_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Valid options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed." introductionVersion:"pre5.0"`
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;USERS_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;USERS_LDAP_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance." introductionVersion:"7.0"`
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master instance ID for multi-instance setups. When set, LDAP user filters are enhanced to also match users belonging to the master instance. Also set 'user_filter'. Without an explicit 'user_filter', this instance resolves every user in the shared LDAP directory." introductionVersion:"7.0"`
UserMemberAttribute string `yaml:"user_member_attribute" env:"OCIS_LDAP_USER_MEMBER_ATTRIBUTE" desc:"LDAP attribute that marks a user as a member of an instance." introductionVersion:"7.0"`
UserGuestAttribute string `yaml:"user_guest_attribute" env:"OCIS_LDAP_USER_GUEST_ATTRIBUTE" desc:"LDAP attribute that marks a user as a guest of an instance." introductionVersion:"7.0"`
UserSchema LDAPUserSchema `yaml:"user_schema"`
@@ -42,5 +42,9 @@ func Validate(cfg *config.Config) error {
return shared.MissingLDAPBindPassword(cfg.Service.Name)
}
if cfg.Driver == "ldap" && cfg.Drivers.LDAP.MasterID != "" && cfg.Drivers.LDAP.UserFilter == "" {
return shared.MissingLDAPUserFilterForMasterID(cfg.Service.Name)
}
return nil
}
@@ -0,0 +1,63 @@
package parser
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/owncloud/ocis/v2/services/users/pkg/config"
)
func TestValidateMasterIDRequiresUserFilter(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "users"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.Error(t, err)
}
func TestValidateMasterIDWithUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "users"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "master-1",
UserFilter: "(ownCloudMemberOf=instance-1)",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
func TestValidateNoMasterIDWithEmptyUserFilterPasses(t *testing.T) {
cfg := &config.Config{
Service: config.Service{Name: "users"},
TokenManager: &config.TokenManager{JWTSecret: "secret"},
Driver: "ldap",
Drivers: config.Drivers{
LDAP: config.LDAPDriver{
BindPassword: "secret",
MasterID: "",
UserFilter: "",
},
},
}
err := Validate(cfg)
assert.NoError(t, err)
}
@@ -2521,6 +2521,36 @@ class SharingNgContext implements Context {
}
}
/**
* @Then /^the last share invitation should have an expiration date approximately "([^"]*)" days from now$/
*
* @param string $days
*
* @return void
*/
public function theLastShareInvitationShouldHaveAnExpirationDateApproximatelyDaysFromNow(
string $days,
): void {
$responseBody = $this->featureContext->getJsonDecodedResponseBodyContent();
Assert::assertTrue(
isset($responseBody->value[0]->expirationDateTime),
"Expected the created share to have an 'expirationDateTime' but none was returned:\n"
. print_r($responseBody, true),
);
$actual = new DateTime($responseBody->value[0]->expirationDateTime);
$expected = (new DateTime())->modify("+" . (int)$days . " days");
$diffSeconds = \abs($actual->getTimestamp() - $expected->getTimestamp());
// allow a 1-minute tolerance to absorb request/processing latency, matching the
// backend unit test's own tolerance (BeTemporally("~", expectedDefault, time.Minute))
Assert::assertLessThanOrEqual(
60,
$diffSeconds,
"Expected an expiration date approximately $days days from now ("
. $expected->format(DATE_ATOM) . "), but got " . $actual->format(DATE_ATOM)
. " (difference of {$diffSeconds}s)",
);
}
/**
* @When /^user "([^"]*)" lists permissions with following filters for (?:folder|file) "([^"]*)" of the space "([^"]*)" using the Graph API:$/
*
@@ -88,6 +88,51 @@ Feature: Send a drive invitations
| Manager |
Scenario Outline: space membership does not get a default expiration when created without one
Given using spaces DAV path
And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Alice" has created a space "NewSpace" with the default quota using the Graph API
When user "Alice" sends the following space share invitation using permissions endpoint of the Graph API:
| space | NewSpace |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
Then the HTTP status code should be "200"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "object",
"required": [
"grantedToV2",
"roles"
],
"not": {
"required": [
"expirationDateTime"
]
}
}
}
}
}
"""
Examples:
| permissions-role |
| Space Viewer |
| Space Editor |
| Manager |
Scenario Outline: send share invitation for disabled project space to user with different roles (permissions endpoint)
Given using spaces DAV path
And the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
@@ -1231,6 +1231,59 @@ Feature: vault
"""
Scenario Outline: server sets a default 30-day expiration when a user share is created without one
Given user "Brian" has been created with default attributes
And the administrator has assigned the role "Space Admin" to user "Brian" using the Graph API
And user "Alice" has been set up in oCIS
And user "Brian" has been set up in oCIS
And user "Alice" has uploaded a file inside space "Personal" with content "to share" to "textfile1.txt" in vault
And user "Alice" has created a folder "FolderToShare" in space "Personal" in vault
When user "Alice" sends the following resource share invitation using the Graph API:
| resource | <resource> |
| space | Personal |
| sharee | Brian |
| shareType | user |
| permissionsRole | <permissions-role> |
| storage | vault |
Then the HTTP status code should be "200"
And the JSON data of the response should match
"""
{
"type": "object",
"required": [
"value"
],
"properties": {
"value": {
"type": "array",
"minItems": 1,
"maxItems": 1,
"items": {
"type": "object",
"required": [
"id",
"roles",
"grantedToV2",
"expirationDateTime"
],
"properties": {
"expirationDateTime": {
"type": "string",
"format": "date-time"
}
}
}
}
}
}
"""
And the last share invitation should have an expiration date approximately "30" days from now
Examples:
| permissions-role | resource |
| Viewer | textfile1.txt |
| Viewer | FolderToShare |
Scenario Outline: try to send share invitation for a project space in vault to a user without the vault mode permission (permissions endpoint)
Given the administrator has assigned the role "Space Admin" to user "Alice" using the Graph API
And user "Brian" has been created with default attributes
+8
View File
@@ -92,5 +92,13 @@ if [[ "$ENABLE_VAULT" == "true" ]]; then
sed -i "/imgSrc:/i\\ - 'https://keycloak:8443/'" $CFG_DIR/values.yaml
fi
if [[ "$ENABLE_SHORT_ACCESS_TOKEN" == "true" ]]; then
sed -i '/shortAccessTokenTest:/{n;s|false|true|}' $CFG_DIR/values.yaml
fi
if [[ "$ENABLE_OIDC_OFFLINE_ACCESS" == "true" ]]; then
sed -i "s|webClientScope: 'openid profile email'|webClientScope: 'openid profile email offline_access'|" $CFG_DIR/values.yaml
fi
# copy custom values file
cp $CFG_DIR/values.yaml "$CHT_DIR/ci/deployment-values.yaml"
+6
View File
@@ -168,4 +168,10 @@
value: "1a01c2c4-4309-4483-a845-842fd56d8622"
{{- end -}}
{{- end -}}
{{- if and (eq .appName "idp") .Values.shortAccessTokenTest.enabled }}
{{/* Shortens the access token lifetime so the oidc/oidc-iframe e2e tests can actually
observe a token renewal within their wait window - see values.yaml. */}}
- name: IDP_ACCESS_TOKEN_EXPIRATION
value: "30"
{{- end -}}
{{- end -}}
+4
View File
@@ -13,6 +13,8 @@ insecure:
oidcIdpInsecure: true
ocisHttpApiInsecure: true
ocmInsecure: true
shortAccessTokenTest:
enabled: true
features:
authapp:
enabled: false
@@ -167,6 +169,8 @@ services:
enabled: true
accessModes:
- ReadWriteOnce
config:
webClientScope: 'openid profile email'
antivirus:
events:
consumer:
@@ -47,6 +47,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -71,6 +72,7 @@ type config struct {
MountID string `mapstructure:"mount_id"`
UploadExpiration int64 `mapstructure:"upload_expiration" docs:"0;Duration for how long uploads will be valid."`
Events eventconfig `mapstructure:"events" docs:"0;Event stream configuration"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
}
type eventconfig struct {
@@ -106,6 +108,7 @@ func (c *config) init() {
type Service struct {
conf *config
Storage storage.FS
Coordinator upload.Coordinator
dataServerURL *url.URL
availableXS []*provider.ResourceChecksumPriority
}
@@ -175,7 +178,14 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
c.init()
fs, err := getFS(c, log)
// One stream for both the driver and the coordinator: a second one would open a
// second nats connection for the same events.
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
fs, err := getFS(c, evstream, log)
if err != nil {
return nil, err
}
@@ -202,9 +212,16 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
return nil, err
}
// storageprovider only initiates uploads; the data path assembles chunks, so no chunking here.
coord, err := upload.NewCoordinatorFromConfig(c.UploadDirectory, c.Drivers[c.Driver], fs, evstream, log, false)
if err != nil {
return nil, fmt.Errorf("storageprovider: %w", err)
}
service := &Service{
conf: c,
Storage: fs,
Coordinator: coord,
dataServerURL: u,
availableXS: xsTypes,
}
@@ -423,7 +440,7 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
metadata["expires"] = strconv.Itoa(int(expirationTimestamp.Seconds))
}
uploadIDs, err := s.Storage.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
uploadIDs, err := s.Coordinator.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
if err != nil {
var st *rpc.Status
switch err.(type) {
@@ -1305,12 +1322,7 @@ func (s *Service) addMissingStorageProviderID(resourceID *provider.ResourceId, s
}
}
func getFS(c *config, log *zerolog.Logger) (storage.FS, error) {
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
func getFS(c *config, evstream events.Stream, log *zerolog.Logger) (storage.FS, error) {
if f, ok := registry.NewFuncs[c.Driver]; ok {
driverConf := c.Drivers[c.Driver]
driverConf["mount_id"] = c.MountID // pass the mount id to the driver
@@ -33,6 +33,7 @@ import (
"github.com/owncloud/reva/v2/pkg/rhttp/router"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -51,6 +52,7 @@ type config struct {
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
NatsUsername string `mapstructure:"nats_username"`
NatsPassword string `mapstructure:"nats_password"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
}
func (c *config) init() {
@@ -104,7 +106,21 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
return nil, err
}
dataTXs, err := getDataTXs(conf, fs, evstream, log)
// the data path assembles chunks, so enable chunking
coord, err := upload.NewCoordinatorFromConfig(conf.UploadDirectory, conf.Drivers[conf.Driver], fs, evstream, log, true)
if err != nil {
return nil, fmt.Errorf("dataprovider: %w", err)
}
// only the data path consumes postprocessing results: one consumer group gets
// one copy of each event, so a second subscriber would take half of them
if ac := upload.AsyncConfFromDriverConf(conf.Drivers[conf.Driver]); ac.Enabled {
if err := coord.StartPostprocessing(evstream, ac.ConsumerGroup, ac.MountID, ac.NumConsumers); err != nil {
return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err)
}
}
dataTXs, err := getDataTXs(conf, coord, fs, evstream, log)
if err != nil {
return nil, err
}
@@ -126,7 +142,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er
return nil, fmt.Errorf("driver not found: %s", c.Driver)
}
func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
if c.DataTXs == nil {
c.DataTXs = make(map[string]map[string]interface{})
}
@@ -146,7 +162,7 @@ func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerol
for t := range c.DataTXs {
if f, ok := datatxregistry.NewFuncs[t]; ok {
if tx, err := f(c.DataTXs[t], publisher, log); err == nil {
if handler, err := tx.Handler(fs); err == nil {
if handler, err := tx.Handler(coord, fs); err == nil {
txs[t] = handler
}
}
@@ -319,7 +319,8 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http.
sReq.Ref.Path = uReq.Ref.GetPath()
sReq.Ref.ResourceId = nil
} else {
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil {
// new files have no node id yet; keep the path-based ref instead
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil && resid.GetOpaqueId() != "" {
sReq.Ref = &provider.Reference{
ResourceId: &resid,
}
+3 -2
View File
@@ -403,6 +403,7 @@ type Version struct {
// CapabilitiesVault holds vault capabilities
type CapabilitiesVault struct {
Enabled ocsBool `json:"enabled" xml:"enabled" mapstructure:"enabled"`
VaultStorageProvider string `json:"vault_storage_provider" xml:"vault_storage_provider" mapstructure:"vault_storage_provider"`
Enabled ocsBool `json:"enabled" xml:"enabled" mapstructure:"enabled"`
VaultStorageProvider string `json:"vault_storage_provider" xml:"vault_storage_provider" mapstructure:"vault_storage_provider"`
DefaultShareExpirationDays int `json:"default_share_expiration_days" xml:"default_share_expiration_days" mapstructure:"default_share_expiration_days"`
}
+4 -1
View File
@@ -28,12 +28,15 @@ import (
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
// DataTX provides an abstraction around various data transfer protocols.
type DataTX interface {
Handler(fs storage.FS) (http.Handler, error)
// Handler serves the protocol's data path. Uploads go through coord, which
// owns the upload lifecycle for every driver; downloads read from driver.
Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error)
}
// EmitFileUploadedEvent is a helper function which publishes a FileUploaded event
@@ -24,8 +24,8 @@ import (
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/mitchellh/mapstructure"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -40,6 +40,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -78,7 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("path", r.URL.Path).Logger()
r = r.WithContext(appctx.WithLogger(r.Context(), &sublog))
@@ -92,7 +93,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, "")
download.GetOrHeadFile(w, r, driver, "")
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -114,7 +115,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
ctx = ctxpkg.ContextSetLockID(ctx, lockID)
}
info, err := fs.Upload(ctx, storage.UploadRequest{
info, err := coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
@@ -42,6 +42,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -80,7 +81,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var spaceID string
spaceID, r.URL.Path = router.ShiftPath(r.URL.Path)
@@ -97,7 +98,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, spaceID)
download.GetOrHeadFile(w, r, driver, spaceID)
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -117,7 +118,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
Path: fn,
}
var info *provider.ResourceInfo
info, err = fs.Upload(ctx, storage.UploadRequest{
info, err = coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
+34 -45
View File
@@ -33,13 +33,13 @@ import (
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/manager/registry"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -87,20 +87,14 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
composable, ok := fs.(storage.ComposableFS)
if !ok {
return nil, errtypes.NotSupported("file system does not support the tus protocol")
}
func (m *manager) Handler(coord upload.Coordinator, _ storage.FS) (http.Handler, error) {
// A storage backend for tusd may consist of multiple different parts which
// handle upload creation, locking, termination and so on. The composer is a
// place where all those separated pieces are joined together. In this example
// we only use the file store but you may plug in multiple.
// place where all those separated pieces are joined together.
composer := tusd.NewStoreComposer()
// let the composable storage tell tus which extensions it supports
composable.UseIn(composer)
// the coordinator serves the tus protocol on behalf of every driver
coord.UseIn(composer)
config := tusd.Config{
StoreComposer: composer,
@@ -130,33 +124,29 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return nil, err
}
if usl, ok := fs.(storage.UploadSessionLister); ok {
// We can currently only send updates if the fs is decomposedfs as we read very specific keys from the storage map of the tus info
go func() {
for {
ev := <-handler.CompleteUploads
// We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files
// so we create a Progress instance here that is used to read the correct properties
ups, err := usl.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
} else {
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
go func() {
for {
ev := <-handler.CompleteUploads
// tus erases its info files, so read the session back for the event's properties
ups, err := coord.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
continue
}
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
}()
}
}
}()
h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("uploadid", r.URL.Path).Logger()
@@ -174,7 +164,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PostFile(w, r)
case "HEAD":
handler.HeadFile(w, r)
@@ -184,7 +174,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PatchFile(w, r)
case "DELETE":
handler.DelFile(w, r)
@@ -205,15 +195,10 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return h, nil
}
func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
func setHeaders(coord upload.Coordinator, w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := path.Base(r.URL.Path)
datastore, ok := fs.(tusd.DataStore)
if !ok {
appctx.GetLogger(ctx).Error().Interface("fs", fs).Msg("storage is not a tus datastore")
return
}
upload, err := datastore.GetUpload(ctx, id)
upload, err := coord.GetUpload(ctx, id)
if err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("could not get upload from storage")
return
@@ -227,6 +212,10 @@ func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
if expires != "" {
w.Header().Set(net.HeaderTusUploadExpires, expires)
}
// the node id is only valid once the upload commits; skip the header for new files
if info.Storage["NodeExists"] != "true" {
return
}
resourceid := &provider.ResourceId{
StorageId: info.MetaData["providerID"],
SpaceId: info.Storage["SpaceRoot"],
@@ -74,6 +74,11 @@ var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/EmptyRecycle `: {200, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetQuota `: {200, `{"totalBytes":456,"usedBytes":123}`, serverStateEmpty},
// the parent of an upload target, stated for its permissions and its id
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":2,"id":{"opaque_id":"fileid-/"},"checksum":{},"etag":"deadbeef","mime_type":"httpd/unix-directory","mtime":{"seconds":1234567890},"path":"/","permission_set":{"initiate_file_upload":true,"stat":true,"list_container":true},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} EMPTY`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} HOME`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateHome},
@@ -111,7 +116,13 @@ var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetPathByID {"storage_id":"00000000-0000-0000-0000-000000000000","opaque_id":"fileid-/some/path"} EMPTY`: {200, "/subdir", serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
// the coordinator resolves the upload target itself: the file does not exist yet,
// so it stats the parent for the permissions and the parent id
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":[]}`: {404, ``, serverStateEmpty},
// a zero-length upload finishes at once, so the node is created and read back here
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/TouchFile {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"markprocessing":false,"mtime":"1234567890"}`: {200, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"mdKeys":[]}`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/file"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/file","permission_set":{},"size":0,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"path":"/file"},"uploadLength":0,"metadata":{"providerID":""}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":1,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":2,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
+7
View File
@@ -190,6 +190,13 @@ func (fs *posixFS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool
return fs.FS.(storage.OrphanChecker).IsOrphaned(ctx, ref)
}
// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a
// new file's node.
func (fs *posixFS) PrepareCreatesNode() bool {
nc, ok := fs.FS.(storage.NodeCreator)
return ok && nc.PrepareCreatesNode()
}
// UseIn tells the tus upload middleware which extensions it supports.
func (fs *posixFS) UseIn(composer *tusd.StoreComposer) {
fs.FS.(storage.ComposableFS).UseIn(composer)
+37 -6
View File
@@ -717,34 +717,65 @@ func (t *Tree) ResolveSpaceIDIndexEntry(spaceid, entry string) (string, string,
func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (metadata.UnlockFunc, error) {
_, span := tracer.Start(ctx, "InitNewNode")
defer span.End()
// The node is not cached yet, so its path comes from the parent and the name.
nodePath := filepath.Join(n.ParentPath(), n.Name)
// create folder structure (if needed)
if err := os.MkdirAll(filepath.Dir(n.InternalPath()), 0700); err != nil {
if err := os.MkdirAll(filepath.Dir(nodePath), 0700); err != nil {
return nil, err
}
// create and write lock new node metadata
unlock, err := t.lookup.MetadataBackend().Lock(n.InternalPath())
unlock, err := t.lookup.MetadataBackend().Lock(nodePath)
if err != nil {
return nil, err
}
// we also need to touch the actual node file here it stores the mtime of the resource
h, err := os.OpenFile(n.InternalPath(), os.O_CREATE|os.O_EXCL, 0600)
h, err := os.OpenFile(nodePath, os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
// The file is not ours: leave it, and its cache entry, alone.
releaseNewNodeLock(ctx, n, unlock)
if os.IsExist(err) {
return unlock, errtypes.AlreadyExists(n.InternalPath())
// The name only: the message reaches the client, the path is the server's.
return nil, errtypes.AlreadyExists(n.Name)
}
return unlock, err
return nil, err
}
h.Close()
// From here the file is ours. A failure removes it and our cache entry
// before unlocking, so nothing can open the node in between.
fail := func(err error) (metadata.UnlockFunc, error) {
if rErr := os.Remove(nodePath); rErr != nil {
appctx.GetLogger(ctx).Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file")
}
if dErr := t.lookup.(*lookup.Lookup).IDCache.Delete(ctx, n.SpaceID, n.ID); dErr != nil {
appctx.GetLogger(ctx).Error().Err(dErr).Str("nodeid", n.ID).Msg("could not remove new node from the id cache")
}
releaseNewNodeLock(ctx, n, unlock)
return nil, err
}
// Cached only now that the name is ours, so a losing upload cannot point it at its id.
if err := t.lookup.(*lookup.Lookup).CacheID(ctx, n.SpaceID, n.ID, nodePath); err != nil {
return fail(err)
}
if _, err := node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize); err != nil {
return unlock, err
return fail(err)
}
return unlock, nil
}
// releaseNewNodeLock releases the lock of a node InitNewNode failed to create.
func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) {
if err := unlock(); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock")
}
}
// TODO check if node exists?
func (t *Tree) createDirNode(ctx context.Context, n *node.Node) (err error) {
ctx, span := tracer.Start(ctx, "createDirNode")
+8 -2
View File
@@ -83,11 +83,16 @@ type UploadInfo struct {
IfMatch string
IfNoneMatch string
IfUnmodifiedSince time.Time
// Where a new file goes, for a driver whose PrepareUpload creates it. Empty
// leaves a missing node NotFound.
ParentID string
Name string
}
type PrepareUploadResult struct {
VersionCreated bool
SizeDiff int64
SpaceOwner *userpb.UserId // the space owner or a manager, for a new node; nil keeps the one already known
}
// RollbackInfo carries what a driver needs to undo PrepareUpload. NodeID and
@@ -135,7 +140,7 @@ type FS interface {
// CreateDir creates a resource of type container
CreateDir(ctx context.Context, ref *provider.Reference) (*CreateDirResult, error)
// TouchFile sets the mtime of a resource, creating an empty file if it does not exist
// FIXME(OCISDEV-900) remove markprocessing bool: coordinator calls MarkProcessing(true) explicitly after TouchFile
// FIXME(OCISDEV-900) remove markprocessing bool: PrepareUpload marks the node the coordinator touched
// FIXME the mtime should either be a time.Time or a CS3 Timestamp, not a string
TouchFile(ctx context.Context, ref *provider.Reference, markprocessing bool, mtime string) (*TouchFileResult, error)
// Delete deletes a resource.
@@ -155,7 +160,8 @@ type FS interface {
CommitUpload(ctx context.Context, ref *provider.Reference, sessionID string, source UploadSource) error
// PrepareUpload is called after all bytes are received and before postprocessing begins.
// Implementations may lock the target node, snapshot the previous version, write new metadata,
// and propagate size changes. Drivers that do not require any of these steps may return immediately.
// mark the node as processing for sessionID, and propagate size changes. Drivers that do not
// require any of these steps may return immediately.
PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info UploadInfo) (*PrepareUploadResult, error)
// RollbackUpload reverts node state after a failed or aborted postprocessing run.
// It is the inverse of PrepareUpload: restores previous metadata and reverts the optimistic
+8
View File
@@ -70,6 +70,14 @@ type OrphanChecker interface {
IsOrphaned(ctx context.Context, ref *provider.Reference) bool
}
// NodeCreator defines the interface for FS implementations whose PrepareUpload
// creates a new file's node from UploadInfo.ParentID and Name, so an upload need
// not TouchFile it first.
type NodeCreator interface {
// PrepareCreatesNode reports whether PrepareUpload creates a missing node.
PrepareCreatesNode() bool
}
// UploadSession is the interface that storage drivers need to return whan listing upload sessions.
type UploadSession interface {
// ID returns the upload id
@@ -28,9 +28,7 @@ import (
"path/filepath"
"strconv"
"strings"
"time"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/jellydator/ttlcache/v2"
@@ -41,7 +39,6 @@ import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/autoprop"
@@ -50,7 +47,6 @@ import (
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/logger"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/aspects"
@@ -79,16 +75,12 @@ const (
CtxKeySpaceGID CtxKey = iota
)
const maxCommitRetryBackoff = 2 * time.Minute
var (
tracer trace.Tracer
// the coordinator consumes the postprocessing events; reverting a revision is
// the driver's own business
_registeredEvents = []events.Unmarshaller{
events.PostprocessingFinished{},
events.PostprocessingStepFinished{},
events.RestartPostprocessing{},
events.CleanUpload{},
events.RevertRevision{},
}
)
@@ -133,9 +125,6 @@ type Decomposedfs struct {
groupSpaceIndex *spaceidindex.Index
spaceTypeIndex *spaceidindex.Index
// commitLimiter caps concurrent async blob commits at NumConsumers.
commitLimiter *semaphore.Weighted
log *zerolog.Logger
}
@@ -273,7 +262,9 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
return nil, errors.New("need nats for async file processing")
}
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup, _registeredEvents...)
// a group of its own: the coordinator holds o.Events.ConsumerGroup, and one
// group gets one copy of each event
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup+"-revisions", _registeredEvents...)
if err != nil {
return nil, err
}
@@ -282,18 +273,16 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
o.Events.NumConsumers = 1
}
fs.commitLimiter = semaphore.NewWeighted(int64(o.Events.NumConsumers))
for i := 0; i < o.Events.NumConsumers; i++ {
go fs.Postprocessing(ch)
go fs.ConsumeRevisionEvents(ch)
}
}
return fs, nil
}
// Postprocessing starts the postprocessing result collector
func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
// ConsumeRevisionEvents starts the revision event collector
func (fs *Decomposedfs) ConsumeRevisionEvents(ch <-chan events.Event) {
log := logger.New()
for event := range ch {
evCtx := context.Background()
@@ -301,219 +290,12 @@ func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
}
}
// finalizeWithRetry commits the staged bytes, retrying blobstore failures with
// capped exponential backoff.
func (fs *Decomposedfs) finalizeWithRetry(ctx context.Context, session *upload.OcisSession, log *zerolog.Logger) error {
maxAttempts := fs.o.Events.CommitMaxRetries + 1
backoff := fs.o.Events.CommitRetryBackoff
var err error
for attempt := 1; attempt <= maxAttempts; attempt++ {
if err = session.Finalize(ctx); err == nil {
return nil
}
ev := log.Warn().Err(err).
Int("attempt", attempt).Int("maxAttempts", maxAttempts).
Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID())
if attempt == maxAttempts {
ev.Msg("blob commit failed, giving up")
break
}
// clamp before use: this bounds backoff to maxCommitRetryBackoff every
// iteration, so the backoff *= 2 below can never grow past 2*max and
// cannot overflow the int64 duration.
backoff = min(backoff, maxCommitRetryBackoff)
ev.Dur("backoff", backoff).Msg("blob commit failed, retrying after backoff")
timer := time.NewTimer(backoff)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
// backoff elapsed, fall through to the next attempt
}
backoff *= 2
}
return err
}
// completePostprocessing reverts (failed) or finalizes the node, unmarks
// processing, and publishes UploadReady. keepUpload keeps the staged bytes. May
// run detached, so it touches no consumer-loop state.
func (fs *Decomposedfs) completePostprocessing(ctx context.Context, session *upload.OcisSession, n *node.Node, ev events.PostprocessingFinished, failed, keepUpload bool, sublog zerolog.Logger) {
now := time.Now()
if failed {
// if no other upload session is in progress (processing id != session id) or has finished (processing id == "")
latestSession, err := n.ProcessingID(ctx)
if err != nil {
sublog.Error().Err(err).Msg("reading node for session failed")
}
if latestSession == session.ID() {
// propagate reverted sizeDiff after failed postprocessing
if err := fs.tp.Propagate(ctx, n, -session.SizeDiff()); err != nil {
sublog.Error().Err(err).Msg("could not propagate tree size change")
}
}
} else if p, err := n.Parent(ctx); err != nil {
sublog.Error().Err(err).Msg("could not read parent")
} else if p != nil {
// update parent tmtime to propagate etag change after successful postprocessing
_ = p.SetTMTime(ctx, &now)
if err := fs.tp.Propagate(ctx, p, 0); err != nil {
sublog.Error().Err(err).Msg("could not propagate etag change")
}
}
// unmark processing; a leftover marker keeps downloads at 425
session.Cleanup(failed, !keepUpload, !keepUpload, true)
var isVersion bool
if session.NodeExists() {
info, err := session.GetInfo(ctx)
if err == nil && info.MetaData["versionsPath"] != "" {
isVersion = true
}
}
if err := events.Publish(
ctx,
fs.stream,
events.UploadReady{
UploadID: ev.UploadID,
Failed: failed,
ExecutingUser: ev.ExecutingUser,
Filename: ev.Filename,
FileRef: &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.SpaceID(),
},
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
},
ResourceID: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.NodeID(),
},
Timestamp: utils.TimeToTS(now),
SpaceOwner: n.SpaceOwnerOrManager(ctx),
IsVersion: isVersion,
ImpersonatingUser: ev.ImpersonatingUser,
},
); err != nil {
sublog.Error().Err(err).Msg("Failed to publish UploadReady event")
}
}
func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event, log *zerolog.Logger) {
ctx, span := events.TraceEventConsumerWithTracer(evCtx, tracer, event)
ctx = autoprop.SetMetaToContext(ctx, event.ExtraInfo)
defer span.End()
switch ev := event.Event.(type) {
case events.PostprocessingFinished:
sublog := log.With().Str("event", "PostprocessingFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
ctx = session.Context(ctx)
n, err := session.Node(ctx)
if err != nil {
// The node metadata is unreadable, so this upload can never finish:
// the destination cannot be resolved. Clean the session up instead of
// leaving it behind to be retried forever. Cleanup falls back to the
// session metadata to release the quota.
sublog.Error().Err(err).Msg("could not read node, cleaning up orphaned session")
session.Cleanup(true, true, true, false)
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
if !n.Exists {
sublog.Debug().Msg("node no longer exists")
session.Cleanup(false, true, true, false)
return
}
switch ev.Outcome {
default:
sublog.Error().Str("outcome", string(ev.Outcome)).Msg("unknown postprocessing outcome - aborting")
fallthrough
case events.PPOutcomeAbort:
metrics.UploadSessionsAborted.Inc()
fs.completePostprocessing(ctx, session, n, ev, true, true, sublog)
case events.PPOutcomeContinue:
// commit re-uploads the whole file and can block for the retry window;
// run it detached (bounded by commitLimiter) to not stall the consumer
go func() {
if err := fs.commitLimiter.Acquire(ctx, 1); err != nil {
sublog.Error().Err(err).Msg("could not acquire commit slot")
return
}
defer fs.commitLimiter.Release(1)
if err := fs.finalizeWithRetry(ctx, session, &sublog); err != nil {
sublog.Error().Err(err).Msg("could not finalize upload after retries, reverting to a recoverable failed state")
// revert like an abort: clears the 425 marker, frees quota, keeps bytes
metrics.UploadSessionsCommitFailed.Inc()
fs.completePostprocessing(ctx, session, n, ev, true, true, sublog)
return
}
metrics.UploadSessionsFinalized.Inc()
fs.completePostprocessing(ctx, session, n, ev, false, false, sublog)
}()
case events.PPOutcomeDelete:
metrics.UploadSessionsDeleted.Inc()
fs.completePostprocessing(ctx, session, n, ev, true, false, sublog)
}
case events.RestartPostprocessing:
sublog := log.With().Str("event", "RestartPostprocessing").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err := session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read node")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
s, err := session.URL(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not create url")
return
}
metrics.UploadSessionsRestarted.Inc()
// restart postprocessing
if err := events.Publish(ctx, fs.stream, events.BytesReceived{
UploadID: session.ID(),
URL: s,
SpaceOwner: n.SpaceOwnerOrManager(ctx),
ExecutingUser: &user.User{Id: &user.UserId{OpaqueId: "postprocessing-restart"}}, // send nil instead?
ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID},
Filename: session.Filename(),
Filesize: uint64(session.Size()),
}); err != nil {
sublog.Error().Err(err).Msg("Failed to publish BytesReceived event")
}
case events.CleanUpload:
sublog := log.With().Str("event", "CleanUpload").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
session.Cleanup(true, !ev.KeepUpload, !ev.KeepUpload, true)
case events.RevertRevision:
sublog := log.With().Str("event", "RevertRevision").Interface("nodeid", ev.ResourceID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
@@ -530,132 +312,6 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
sublog.Error().Err(err).Msg("Failed to revert revision")
return
}
case events.PostprocessingStepFinished:
sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
if ev.FinishedStep != events.PPStepAntivirus {
// atm we are only interested in antivirus results
return
}
res := ev.Result.(events.VirusscanResult)
if res.ErrorMsg != "" {
// scan failed somehow
// Should we handle this here?
return
}
sublog = log.With().Str("scan_description", res.Description).Bool("infected", res.Infected).Logger()
var n *node.Node
switch ev.UploadID {
case "":
// uploadid is empty -> this was an on-demand scan
/* ON DEMAND SCANNING NOT SUPPORTED ATM
ctx := ctxpkg.ContextSetUser(context.Background(), ev.ExecutingUser)
ref := &provider.Reference{ResourceId: ev.ResourceID}
no, err := fs.lu.NodeFromResource(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to get node after scan")
continue
}
n = no
if ev.Outcome == events.PPOutcomeDelete {
// antivir wants us to delete the file. We must obey and need to
// check if there a previous versions existing
revs, err := fs.ListRevisions(ctx, ref)
if len(revs) == 0 {
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to list revisions. Fallback to delete file")
}
// no versions -> trash file
err := fs.Delete(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to delete infected resource")
continue
}
// now purge it from the recycle bin
if err := fs.PurgeRecycleItem(ctx, &provider.Reference{ResourceId: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}}, n.ID, "/"); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to purge infected resource from trash")
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
// we have versions - find the newest
versions := make(map[uint64]string) // remember all versions - we need them later
var nv uint64
for _, v := range revs {
versions[v.Mtime] = v.Key
if v.Mtime > nv {
nv = v.Mtime
}
}
// restore newest version
if err := fs.RestoreRevision(ctx, ref, versions[nv]); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", versions[nv]).Msg("Failed to restore revision")
continue
}
// now find infected version
revs, err = fs.ListRevisions(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Error listing revisions after restore")
}
for _, v := range revs {
// we looking for a version that was previously not there
if _, ok := versions[v.Mtime]; ok {
continue
}
if err := fs.DeleteRevision(ctx, ref, v.Key); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", v.Key).Msg("Failed to delete revision")
}
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
*/
default:
// uploadid is not empty -> this is an async upload
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err = session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get node after scan")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
session.SetScanData(res.Description, res.Scandate)
if err := session.Persist(ctx); err != nil {
sublog.Error().Err(err).Msg("Failed to persist scan results")
}
}
if err := n.SetScanData(ctx, res.Description, res.Scandate); err != nil {
sublog.Error().Err(err).Msg("Failed to set scan results")
return
}
metrics.UploadSessionsScanned.Inc()
default:
log.Error().Interface("event", ev).Msg("Unknown event")
}
@@ -672,6 +328,11 @@ func (fs *Decomposedfs) Capabilities(_ context.Context) storage.Capabilities {
return storage.FullCapabilities()
}
// PrepareCreatesNode reports that PrepareUpload creates a new file's node.
func (fs *Decomposedfs) PrepareCreatesNode() bool {
return true
}
// GetQuota returns the quota available
// TODO Document in the cs3 should we return quota or free space?
func (fs *Decomposedfs) GetQuota(ctx context.Context, ref *provider.Reference) (total uint64, inUse uint64, remaining uint64, err error) {
@@ -168,20 +168,17 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
return err
}
// link child name to parent if it is new
// link child name to parent, create-only so a concurrent upload of the same
// new file cannot silently clobber it: the loser gets AlreadyExists and its
// CAS loop re-reads and retries instead of losing the update (OCISDEV-855)
childNameLink := filepath.Join(n.ParentPath(), n.Name)
var link string
link, err = os.Readlink(childNameLink)
if err == nil && link != "../"+n.ID {
if err = os.Remove(childNameLink); err != nil {
return errors.Wrap(err, "Decomposedfs: could not remove symlink child entry")
}
}
if errors.Is(err, fs.ErrNotExist) || link != "../"+n.ID {
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
_ = os.Remove(nodePath)
if errors.Is(err, fs.ErrExist) {
return errtypes.AlreadyExists(n.Name)
}
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
}
if storage.SkipTouchPropagation(ctx) {
@@ -708,18 +705,31 @@ 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 {
// The node file is not ours, so there is nothing of ours to remove.
releaseNewNodeLock(ctx, n, unlock)
if errors.Is(err, fs.ErrExist) {
return unlock, errtypes.AlreadyExists(n.Name)
return nil, errtypes.AlreadyExists(n.Name)
}
return unlock, err
return nil, err
}
h.Close()
// From here the node file is ours, but the name may not be: a failure removes
// the node file and leaves the name to whichever upload linked it. Removed
// before unlocking, so nothing can open the node in between.
fail := func(err error) (metadata.UnlockFunc, error) {
if rErr := os.Remove(n.InternalPath()); rErr != nil {
appctx.GetLogger(ctx).Error().Err(rErr).Str("nodeid", n.ID).Msg("could not remove new node file")
}
releaseNewNodeLock(ctx, n, unlock)
return nil, err
}
_, subspan = tracer.Start(ctx, "node.CheckQuota")
_, err = node.CheckQuota(ctx, n.SpaceRoot, false, 0, fsize)
subspan.End()
if err != nil {
return unlock, err
return fail(err)
}
// link child name to parent if it is new
@@ -735,15 +745,22 @@ func (t *Tree) InitNewNode(ctx context.Context, n *node.Node, fsize uint64) (met
log.Info().Err(err).Msg("initNewNode: symlink failed")
if errors.Is(err, fs.ErrExist) {
log.Info().Err(err).Msg("initNewNode: symlink already exists")
return unlock, errtypes.AlreadyExists(n.Name)
return fail(errtypes.AlreadyExists(n.Name))
}
return unlock, errors.Wrap(err, "Decomposedfs: could not symlink child entry")
return fail(errors.Wrap(err, "Decomposedfs: could not symlink child entry"))
}
log.Info().Msg("initNewNode: symlink created")
return unlock, nil
}
// releaseNewNodeLock releases the lock of a node InitNewNode failed to create.
func releaseNewNodeLock(ctx context.Context, n *node.Node, unlock metadata.UnlockFunc) {
if err := unlock(); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not release new node lock")
}
}
func (t *Tree) removeNode(ctx context.Context, path, timeSuffix string, n *node.Node) error {
logger := appctx.GetLogger(ctx)
+111 -15
View File
@@ -434,8 +434,9 @@ func (fs *Decomposedfs) CommitUpload(ctx context.Context, ref *provider.Referenc
return nil
}
// PrepareUpload finalizes node metadata after bytes are received, before postprocessing.
// CommitUpload is called after postprocessing completes.
// PrepareUpload finalizes node metadata after bytes are received, before postprocessing,
// and marks the node as processing for sessionID. CommitUpload is called after
// postprocessing completes.
func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.UploadInfo) (*storage.PrepareUploadResult, error) {
ctx, span := tracer.Start(ctx, "PrepareUpload")
defer span.End()
@@ -445,15 +446,50 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
appctx.GetLogger(ctx).Error().Err(err).Msg("PrepareUpload: unexpected NodeFromResource failure")
return nil, errtypes.InternalError("PrepareUpload: node lookup failed unexpectedly")
}
if !n.Exists {
// A new file nobody has created yet: PrepareUpload creates it, under the id the
// ref already carries.
create := !n.Exists && !info.NodeExisted && info.ParentID != "" && info.Name != ""
if !n.Exists && !create {
return nil, errtypes.NotFound(ref.String())
}
if create {
if err := fs.checkNewFileParent(ctx, n.SpaceID, info); err != nil {
return nil, err
}
n.ParentID = info.ParentID
n.Name = info.Name
}
committed := false
// Only a node this upload created is purged, and one it is creating only once the
// name is its own: Purge removes the name link by name.
purge := !info.NodeExisted && !create
// This upload created the node, so a failure must not leave it behind as an
// empty file. Purge, not trash: it never had content, and Purge needs no
// Delete permission. Registered before the lock is taken, so it runs once the
// lock is released. Purge leaves the lock file alone: InitNewNode's unlock
// removes it, a plain lockedfile's does not.
defer func() {
if committed || !purge {
return
}
if err := n.Purge(ctx); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not purge new node after failed prepare")
}
}()
n.SpaceRoot, err = node.ReadNode(ctx, fs.lu, n.SpaceID, n.SpaceID, false, nil, false)
if err != nil {
return nil, err
}
if err := n.CheckLock(ctx); err != nil {
if create {
// A node still to be created holds no lock, so any lock id is a mismatch, the
// answer CheckLock would give, here without creating the node first.
if lockID, _ := ctxpkg.ContextGetLockID(ctx); lockID != "" {
return nil, errtypes.Aborted("not locked")
}
} else if err := n.CheckLock(ctx); err != nil {
return nil, err
}
@@ -468,12 +504,27 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
}
}
targetPath := n.InternalPath()
f, err := lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(targetPath), os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, err
var (
f *lockedfile.File
unlock func() error
)
if create {
// InitNewNode refuses a name already taken, checks the quota, and on failure
// removes what it made and releases its lock. Its lock is the one PrepareUpload
// would take, so it is kept rather than taken again.
unlock, err = fs.tp.InitNewNode(ctx, n, uint64(info.Size))
if err != nil {
return nil, err
}
purge = true
} else {
f, err = lockedfile.OpenFile(fs.lu.MetadataBackend().LockfilePath(n.InternalPath()), os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, err
}
unlock = func() error { return f.Close() }
}
unlock := func() error { return f.Close() }
targetPath := n.InternalPath()
defer func() {
if err := unlock(); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not close lock")
@@ -486,7 +537,6 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
versionPath string
oldAttrs node.Attributes
oldMtime time.Time
committed bool
)
defer func() {
@@ -507,6 +557,13 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
if err := n.SetXattrsWithContext(ctx, oldAttrs, false); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not restore node xattrs during rollback")
}
// Restoring only rewrites the old keys, so the mark this upload added would
// stay, and with the session discarded nothing else would ever remove it.
if _, ok := oldAttrs[prefixes.StatusPrefix]; !ok {
if err := n.RemoveXattr(ctx, prefixes.StatusPrefix, false); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("nodeid", n.ID).Msg("could not remove processing mark during rollback")
}
}
}
}()
@@ -525,9 +582,12 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
}
// also for new files: the coordinator's check fails open without GetQuota
// permission, and CheckQuota guards disk space too
if _, err := node.CheckQuota(ctx, n.SpaceRoot, overwrite, uint64(oldBlobsize), uint64(info.Size)); err != nil {
return nil, err
// permission, and CheckQuota guards disk space too. InitNewNode has checked a
// node it created.
if !create {
if _, err := node.CheckQuota(ctx, n.SpaceRoot, overwrite, uint64(oldBlobsize), uint64(info.Size)); err != nil {
return nil, err
}
}
if info.NodeExisted {
@@ -607,7 +667,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
sizeDiff = info.Size - old.Blobsize
} else {
if c, ok := fs.lu.(node.IDCacher); ok {
// InitNewNode has cached a node it created
if c, ok := fs.lu.(node.IDCacher); ok && !create {
if err := c.CacheID(ctx, n.SpaceID, n.ID, filepath.Join(n.ParentPath(), n.Name)); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("failed to cache id")
}
@@ -625,6 +686,8 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
attrs[prefixes.ChecksumPrefix+"sha1"] = info.Checksums.SHA1
attrs[prefixes.ChecksumPrefix+"md5"] = info.Checksums.MD5
attrs[prefixes.ChecksumPrefix+"adler32"] = info.Checksums.Adler32
// in the same batch, so marking the node costs no write of its own
attrs.SetString(prefixes.StatusPrefix, node.ProcessingStatus+sessionID)
mtime := time.Now()
if !info.MTime.IsZero() {
@@ -643,7 +706,40 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
}
committed = true
return &storage.PrepareUploadResult{VersionCreated: versionCreated, SizeDiff: sizeDiff}, nil
result := &storage.PrepareUploadResult{VersionCreated: versionCreated, SizeDiff: sizeDiff}
if !info.NodeExisted {
// Read off the disk, not through ListGrants: an uploader who cannot see the
// space root still needs the manager of a project space reported.
result.SpaceOwner = n.SpaceOwnerOrManager(ctx)
}
return result, nil
}
// checkNewFileParent re-checks, for a file PrepareUpload is about to create, what
// TouchFile checked: the parent still exists, and the user may still upload into it.
// Either may have changed while the bytes were in flight.
func (fs *Decomposedfs) checkNewFileParent(ctx context.Context, spaceID string, info storage.UploadInfo) error {
parentID := &provider.ResourceId{SpaceId: spaceID, OpaqueId: info.ParentID}
parent, err := fs.lu.NodeFromID(ctx, parentID)
if err != nil {
return errtypes.InternalError(err.Error())
}
f, _ := storagespace.FormatReference(&provider.Reference{ResourceId: parentID, Path: info.Name})
if !parent.Exists {
return errtypes.NotFound(f)
}
rp, err := fs.p.AssemblePermissions(ctx, parent)
switch {
case err != nil:
return err
case !rp.InitiateFileUpload:
if rp.Stat {
return errtypes.PermissionDenied(f)
}
return errtypes.NotFound(f)
}
return nil
}
// RollbackUpload reverts the node state written by PrepareUpload after a failed or aborted
@@ -60,6 +60,13 @@ func (f *FS) IsOrphaned(ctx context.Context, ref *provider.Reference) bool {
return f.next.(storage.OrphanChecker).IsOrphaned(ctx, ref)
}
// PrepareCreatesNode reports whether the wrapped driver's PrepareUpload creates a
// new file's node.
func (f *FS) PrepareCreatesNode() bool {
nc, ok := f.next.(storage.NodeCreator)
return ok && nc.PrepareCreatesNode()
}
// UseIn tells the tus upload middleware which extensions it supports.
func (f *FS) UseIn(composer *tusd.StoreComposer) {
f.next.(storage.ComposableFS).UseIn(composer)
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more