Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5eab44d3d | ||
|
|
cbb018a501 | ||
|
|
15dacf5295 | ||
|
|
ef9b4f7fc9 | ||
|
|
633837b3e1 | ||
|
|
6b28863fa5 | ||
|
|
579249bd1e | ||
|
|
f6df02372c | ||
|
|
9469149f39 | ||
|
|
4680d9d905 | ||
|
|
64b18f5432 | ||
|
|
a065ed0962 | ||
|
|
887145f143 | ||
|
|
1986da8657 | ||
|
|
36a034fa83 | ||
|
|
dd6fa31ac9 | ||
|
|
cdaba15e35 | ||
|
|
efe85baed9 | ||
|
|
486fa4811c | ||
|
|
bacd899092 | ||
|
|
6c1dfdc38c | ||
|
|
390614e9d0 | ||
|
|
45e2b94b5e | ||
|
|
e609fefa8c | ||
|
|
2d8841f490 | ||
|
|
00567fa575 | ||
|
|
4f7de832a8 | ||
|
|
46684067e9 |
No files matched your search
+128
-33
@@ -459,8 +459,8 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
# - suite: part-1
|
||||
# args: "--type playwright --total-parts 4 --xsuites search,app-provider,ocm,keycloak,mfa,oidc,vault-storage --run-part 1"
|
||||
- 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
|
||||
@@ -488,9 +488,9 @@ jobs:
|
||||
- suite: ocm
|
||||
args: "--type playwright --suites ocm"
|
||||
federated: true
|
||||
# - suite: vault-storage
|
||||
# args: "--type playwright --suites vault-storage"
|
||||
# vault_storage: true
|
||||
- suite: vault-storage
|
||||
args: "--type playwright --suites vault-storage"
|
||||
vault_storage: true
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -541,6 +541,8 @@ jobs:
|
||||
|
||||
- name: Prepare Helm Charts
|
||||
env:
|
||||
ENABLE_TIKA: ${{ matrix.suite == 'vault-storage' }}
|
||||
ENABLE_VAULT: ${{ matrix.suite == 'vault-storage' }}
|
||||
ENABLE_WOPI: ${{ matrix.suite == 'app-provider' }}
|
||||
ENABLE_OCM: ${{ matrix.suite == 'ocm' }}
|
||||
run: |
|
||||
@@ -552,6 +554,83 @@ jobs:
|
||||
|
||||
- name: Deploy Suite-Specific External Backends
|
||||
run: |
|
||||
if [[ "${{ matrix.suite }}" == "vault-storage" ]]; then
|
||||
docker run -d \
|
||||
-p 9998:9998 \
|
||||
--name tika \
|
||||
apache/tika:3.2.2.0-full
|
||||
for i in {1..60}; do
|
||||
if curl -sf http://localhost:9998 > /dev/null; then
|
||||
break
|
||||
fi
|
||||
echo "Waiting for tika... ($i/60)"
|
||||
sleep 2
|
||||
done
|
||||
curl -sf http://localhost:9998 > /dev/null
|
||||
bash tests/config/k8s/expose-external-svc.sh tika:9998
|
||||
|
||||
# GitHub runners ship PostgreSQL pre-installed on 5432, but not always
|
||||
# already running - reuse it for keycloak's DB instead of running our
|
||||
# own container for it, once it's up.
|
||||
sudo systemctl start postgresql
|
||||
for i in {1..30}; do
|
||||
sudo -u postgres pg_isready && break
|
||||
echo "Waiting for postgres... ($i/30)"
|
||||
sleep 2
|
||||
done
|
||||
sudo -u postgres pg_isready
|
||||
sudo -u postgres psql -c "CREATE USER keycloak WITH PASSWORD 'keycloak';"
|
||||
sudo -u postgres psql -c "CREATE DATABASE keycloak OWNER keycloak;"
|
||||
|
||||
mkdir -p keycloak-certs
|
||||
openssl req -x509 -newkey rsa:2048 \
|
||||
-keyout keycloak-certs/keycloakkey.pem \
|
||||
-out keycloak-certs/keycloakcrt.pem \
|
||||
-nodes -days 365 -subj "/CN=keycloak"
|
||||
chmod 777 keycloak-certs/*
|
||||
|
||||
# patch the realm so the "web" client's redirect/origin URLs match
|
||||
# the k8s ingress domain instead of the non-k8s "localhost:9200" one
|
||||
sed "s|https://localhost:9200|${TEST_SERVER_URL}|g" \
|
||||
tests/config/ci/ocis-mfa-ci-realm.dist.json > /tmp/ocis-realm.json
|
||||
|
||||
docker run -d --name keycloak --network host \
|
||||
-e OCIS_DOMAIN="$TEST_SERVER_URL" \
|
||||
-e KC_HOSTNAME=keycloak \
|
||||
-e KC_PORT=8443 \
|
||||
-e KC_DB=postgres \
|
||||
-e KC_DB_URL=jdbc:postgresql://localhost:5432/keycloak \
|
||||
-e KC_DB_USERNAME=keycloak \
|
||||
-e KC_DB_PASSWORD=keycloak \
|
||||
-e KC_FEATURES=impersonation \
|
||||
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
|
||||
-e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
|
||||
-e KC_HTTPS_CERTIFICATE_FILE=/keycloak-certs/keycloakcrt.pem \
|
||||
-e KC_HTTPS_CERTIFICATE_KEY_FILE=/keycloak-certs/keycloakkey.pem \
|
||||
-v "$(pwd)/keycloak-certs:/keycloak-certs:ro" \
|
||||
-v /tmp/ocis-realm.json:/opt/keycloak/data/import/ocis-mfa-ci-realm.dist.json:ro \
|
||||
quay.io/keycloak/keycloak:26.5.6 \
|
||||
start-dev --proxy-headers xforwarded \
|
||||
--spi-connections-http-client-default-disable-trust-manager=true \
|
||||
--import-realm --health-enabled=true
|
||||
|
||||
keycloak_ready=false
|
||||
for i in {1..60}; do
|
||||
if curl -skf https://localhost:9000/health/ready > /dev/null; then
|
||||
keycloak_ready=true
|
||||
break
|
||||
fi
|
||||
echo "Waiting for keycloak... ($i/60)"
|
||||
sleep 5
|
||||
done
|
||||
if [[ "$keycloak_ready" != "true" ]]; then
|
||||
docker logs keycloak --tail 80
|
||||
exit 1
|
||||
fi
|
||||
|
||||
bash tests/config/k8s/expose-external-svc.sh keycloak:8443
|
||||
fi
|
||||
|
||||
if [[ "${{ matrix.suite }}" == "app-provider" ]]; then
|
||||
# Start Collabora
|
||||
docker run -d \
|
||||
@@ -627,6 +706,15 @@ jobs:
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-onlyoffice 9300 30302
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9304 30304
|
||||
|
||||
- name: Expose proxy readyz
|
||||
if: ${{ matrix.suite == 'vault-storage' }}
|
||||
run: |
|
||||
(
|
||||
while true; do
|
||||
kubectl -n "$TEST_SERVER_DOMAIN" port-forward deployment/proxy 19205:9205 >> /tmp/proxy-readyz-portforward.log 2>&1
|
||||
sleep 1
|
||||
done
|
||||
) &
|
||||
- name: Wait for oCIS to be ready
|
||||
env:
|
||||
FILE_URL: ${{ env.TEST_SERVER_URL }}/remote.php/dav/files/admin/hello1.txt
|
||||
@@ -662,41 +750,48 @@ jobs:
|
||||
return 1
|
||||
}
|
||||
|
||||
echo "Creating test file in oCIS..."
|
||||
if [[ "${{ matrix.suite }}" == "vault-storage" ]]; then
|
||||
retry "proxy readyz" curl -sf http://localhost:19205/readyz || exit 1
|
||||
else
|
||||
echo "Creating test file in oCIS..."
|
||||
|
||||
request() {
|
||||
local method=$1
|
||||
shift
|
||||
curl -ks -o /dev/null -w "%{http_code}" \
|
||||
-X "$method" \
|
||||
-u admin:admin \
|
||||
"$@" \
|
||||
"$FILE_URL"
|
||||
}
|
||||
put_file() {
|
||||
request PUT \
|
||||
-H "Content-Type: text/plain" \
|
||||
--data "Hello from GitHub Actions!"
|
||||
}
|
||||
delete_file() {
|
||||
request DELETE
|
||||
}
|
||||
check_status() {
|
||||
local expected=$1
|
||||
shift
|
||||
status=$("$@")
|
||||
[ "$status" = "$expected" ]
|
||||
}
|
||||
echo "Creating test file..."
|
||||
retry "create file (HTTP 201)" check_status 201 put_file || exit 1
|
||||
echo "Deleting test file..."
|
||||
retry "delete file (HTTP 204)" check_status 204 delete_file || exit 1
|
||||
request() {
|
||||
local method=$1
|
||||
shift
|
||||
curl -ks -o /dev/null -w "%{http_code}" \
|
||||
-X "$method" \
|
||||
-u admin:admin \
|
||||
"$@" \
|
||||
"$FILE_URL"
|
||||
}
|
||||
put_file() {
|
||||
request PUT \
|
||||
-H "Content-Type: text/plain" \
|
||||
--data "Hello from GitHub Actions!"
|
||||
}
|
||||
delete_file() {
|
||||
request DELETE
|
||||
}
|
||||
check_status() {
|
||||
local expected=$1
|
||||
shift
|
||||
status=$("$@")
|
||||
[ "$status" = "$expected" ]
|
||||
}
|
||||
echo "Creating test file..."
|
||||
retry "create file (HTTP 201)" check_status 201 put_file || exit 1
|
||||
echo "Deleting test file..."
|
||||
retry "delete file (HTTP 204)" check_status 204 delete_file || exit 1
|
||||
fi
|
||||
|
||||
- name: Run e2e ${{ matrix.suite }} tests
|
||||
env:
|
||||
E2E_ARGS: "${{ matrix.args }}"
|
||||
K8S: ${{ env.K8S }}
|
||||
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
|
||||
KEYCLOAK: ${{ matrix.suite == 'vault-storage' }}
|
||||
KEYCLOAK_HOST: keycloak:8443
|
||||
VAULT_MODE: ${{ matrix.suite == 'vault-storage' }}
|
||||
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
|
||||
FED_SERVER_URL: ${{ env.FED_SERVER_URL }}
|
||||
FEDERATED_NEEDED: ${{ matrix.federated == true && 'true' || 'false' }}
|
||||
|
||||
@@ -4,3 +4,4 @@
|
||||
|
||||
CVE-2026-32284 # github.com/shamaton/msgpack/v2 v2.4.0 — no fix available upstream
|
||||
vendor/github.com/crewjam/saml/xmlenc/fuzz.go # test RSA key used in fuzz corpus, not a real secret
|
||||
CVE-2026-116587 # github.com/go-jose/go-jose/v3 v3.0.5 — no v3 fix exists, only a transitive dependency of libregraph/lico, which parses JWKs only from local files and from configured OIDC authorities; go-jose/v4 is fixed
|
||||
@@ -0,0 +1,10 @@
|
||||
Bugfix: Fix closing a shared document from the office editor
|
||||
|
||||
Closing a document or using "Open file location" in the office editor failed
|
||||
with a private link error for users who had a single file shared with them.
|
||||
The editor linked to the folder containing the file, which belongs to the
|
||||
sharer and is not accessible to the sharee. The folder link is now only
|
||||
provided if the user can access the folder, otherwise closing the editor
|
||||
leads back to oCIS.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13198
|
||||
@@ -0,0 +1,11 @@
|
||||
Bugfix: fixed copy link failing in the EPUB library book details
|
||||
|
||||
Clicking "Copy link" in the details of a book in the EPUB library showed
|
||||
a "The link could not be copied" error whenever the book had been found
|
||||
through the server-side search, because those search results carry no
|
||||
link to the file.
|
||||
|
||||
The link is now built from the id of the file when the search result does
|
||||
not provide one, so copying the link works for all books.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13239
|
||||
@@ -0,0 +1,7 @@
|
||||
Bugfix: Disable confirm in the link password dialog until a password is entered
|
||||
|
||||
The "Add password" / "Edit password" dialog for links could be confirmed with
|
||||
an empty field, which removed the password from the link. The confirm button
|
||||
is now disabled until a valid password is entered.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13218
|
||||
@@ -0,0 +1,16 @@
|
||||
Bugfix: Stop logging OAuth tokens to the browser console
|
||||
|
||||
On every login and every silent token renewal, the web client wrote the
|
||||
signed-in user's raw OAuth `access_token` and `refresh_token` to the browser
|
||||
console via a `console.debug` call in the `userLoaded` handler of the auth
|
||||
service. Anyone with access to that browser's console or log buffer - a
|
||||
malicious or over-permissioned browser extension, a shared or kiosk terminal,
|
||||
a screen share or recording, or a session-replay tool that captures console
|
||||
output - could read and reuse those live credentials. The production build
|
||||
does not strip `console.debug`, so this shipped in the deployed bundle, not
|
||||
just local dev.
|
||||
|
||||
The debug line now confirms that a new user was loaded without logging the
|
||||
token, profile, or any other user field.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13233
|
||||
@@ -0,0 +1,9 @@
|
||||
Bugfix: Pass SMTP password and authentication to ocis in the ocis_full example
|
||||
|
||||
The `ocis_full` deployment example defined `SMTP_PASSWORD` and
|
||||
`SMTP_AUTHENTICATION` in its `.env` file but did not forward them to the `ocis`
|
||||
container, so an SMTP server requiring authentication could not be configured.
|
||||
`NOTIFICATIONS_SMTP_PASSWORD` and `NOTIFICATIONS_SMTP_AUTHENTICATION` are now
|
||||
passed through.
|
||||
|
||||
https://github.com/owncloud/ocis/issues/11757
|
||||
@@ -0,0 +1,14 @@
|
||||
Bugfix: Restore multiple trash items with the same name
|
||||
|
||||
Restoring several deleted files with the same name at once showed a conflict
|
||||
dialog claiming the file already exists, even when it didn't. Choosing to
|
||||
replace it then showed both a success and a failure notification, because
|
||||
all files were restored to the same location at the same time and only one
|
||||
of them could succeed.
|
||||
|
||||
Trash items that only collide with each other are now restored side by side
|
||||
with unique names, without asking. When they collide with an existing file
|
||||
and the user chooses to replace it, only one of them replaces the file and
|
||||
the others are restored with unique names.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13238
|
||||
@@ -0,0 +1,9 @@
|
||||
Bugfix: Clarify the message for a trash the user may not access
|
||||
|
||||
When a member of a space was not allowed to list the space's deleted files, the
|
||||
trash view said the user "may not" have the permission, even though the server
|
||||
had clearly denied access. The view now states that the user does not have
|
||||
permission to view the deleted files. Other failures to load the trash show a
|
||||
generic error message instead of a guess about permissions.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13217
|
||||
@@ -0,0 +1,9 @@
|
||||
Change: Remove the owncloudsql driver
|
||||
|
||||
We removed the deprecated `owncloudsql` driver from oCIS.
|
||||
|
||||
The services `storage-users`, `auth-basic`, `users`, `groups`, and `sharing` no
|
||||
longer accept the value `owncloudsql` for their driver. The related
|
||||
configuration sections and environment variables are removed.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13191
|
||||
@@ -0,0 +1,8 @@
|
||||
Enhancement: Make the user search attributes configurable
|
||||
|
||||
Which attributes user search matches against is now configurable via
|
||||
`GRAPH_LDAP_USER_SEARCH_ATTRIBUTES`, defaulting to name, display name and
|
||||
e-mail. Deployments that need stricter matching (e.g. for data protection)
|
||||
can restrict it to name, surname and username, excluding e-mail.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13219
|
||||
@@ -0,0 +1,17 @@
|
||||
Enhancement: Pick the role of multi-instance guests from their claims
|
||||
|
||||
In a multi-instance setup every guest got the same role,
|
||||
`OCIS_MULTI_INSTANCE_GUEST_ROLE`, no matter what their roles claim said. A
|
||||
teacher invited to another instance could therefore not be given access to
|
||||
vault (Safe) resources there without giving it to every other guest as well.
|
||||
|
||||
The new `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` setting takes a list of
|
||||
`claimvalue:rolename` pairs, for example `spaceadmin:user-light-vault`. A guest whose
|
||||
`PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM` claim matches a pair gets that role instead
|
||||
of the guest role, guests without a match keep `OCIS_MULTI_INSTANCE_GUEST_ROLE`.
|
||||
A pair that points to a role which does not exist fails the login of the
|
||||
matching guests. The proxy does not start if the setting is malformed or used
|
||||
without the `oidc` role assignment driver. The setting is empty by default,
|
||||
which keeps the previous behaviour.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13231
|
||||
@@ -0,0 +1,14 @@
|
||||
Enhancement: Sort "Shared with me" by "Shared by"
|
||||
|
||||
The "Shared by" column in "Shared with me" can now be sorted. Items are ordered
|
||||
by the alphabetised display names of all the people who shared them, joined
|
||||
into one key, so an item shared by several people is placed consistently
|
||||
regardless of which avatar happens to display first. Clicking the column
|
||||
header again reverses the order. The order of the avatars shown in the
|
||||
column and the sidebar is unaffected.
|
||||
|
||||
Sorting by "Shared with" no longer reorders the avatars in that column. They
|
||||
used to stay sorted alphabetically after switching to another sort, until the
|
||||
page was reloaded.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13213
|
||||
@@ -0,0 +1,19 @@
|
||||
Bugfix: Fix the role assignment of multi-instance guests
|
||||
|
||||
The proxy now rejects an unknown multi-instance guest role. Before this
|
||||
fix, the proxy assigned an empty role id when
|
||||
`OCIS_MULTI_INSTANCE_GUEST_ROLE` named a role that does not exist.
|
||||
|
||||
The proxy now trims the spaces in the pairs of
|
||||
`OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING`. The proxy does not start when the
|
||||
mapping is set and `OCIS_MULTI_INSTANCE_GUEST_ROLE` is empty.
|
||||
|
||||
When a guest role is not in the role cache, the proxy reads the roles again.
|
||||
Thus a new role works before the cache time ends. The proxy reads the roles
|
||||
a maximum of one time in 30 seconds.
|
||||
|
||||
The proxy writes a debug log line when the roles claim of a guest is missing.
|
||||
The description of `OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING` now tells that
|
||||
a claim value is a regular expression.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13250
|
||||
@@ -0,0 +1,7 @@
|
||||
Security: Bump go-jose and golang.org/x/net dependencies
|
||||
|
||||
We've bumped go-jose/v4 to v4.1.6 to fix CVE-2026-116587, a denial of service
|
||||
when parsing JWKs that contain RSA keys, and golang.org/x/net to v0.62.0 to
|
||||
fix GO-2026-6860 and GO-2026-6866 in its html package.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13256
|
||||
@@ -0,0 +1,8 @@
|
||||
Security: Ignore CVE-2026-116587 for go-jose/v3 in the Trivy scan
|
||||
|
||||
The indirect dependency go-jose/v3 has no fix for CVE-2026-116587. It comes
|
||||
from libregraph/lico. Lico reads JWKs only from local files and from
|
||||
configured OIDC authorities. We've fixed go-jose/v4 and we ignore the go-jose/v3
|
||||
finding in the Trivy scan.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13267
|
||||
@@ -123,6 +123,7 @@ SMTP_USERNAME=
|
||||
# Password for the SMTP host to connect to.
|
||||
SMTP_PASSWORD=
|
||||
# Authentication method for the SMTP communication.
|
||||
# Possible values are 'login', 'plain', 'crammd5', 'none' or 'auto'. Defaults to 'auto' if unset.
|
||||
SMTP_AUTHENTICATION=
|
||||
# Allow insecure connections to the SMTP server. Defaults to false.
|
||||
SMTP_INSECURE=
|
||||
|
||||
@@ -43,6 +43,8 @@ services:
|
||||
NOTIFICATIONS_SMTP_PORT: "${SMTP_PORT}"
|
||||
NOTIFICATIONS_SMTP_SENDER: "${SMTP_SENDER:-oCIS notifications <notifications@${OCIS_DOMAIN:-ocis.owncloud.test}>}"
|
||||
NOTIFICATIONS_SMTP_USERNAME: "${SMTP_USERNAME}"
|
||||
NOTIFICATIONS_SMTP_PASSWORD: "${SMTP_PASSWORD}"
|
||||
NOTIFICATIONS_SMTP_AUTHENTICATION: "${SMTP_AUTHENTICATION}"
|
||||
NOTIFICATIONS_SMTP_INSECURE: "${SMTP_INSECURE}"
|
||||
# make the registry available to the app provider containers
|
||||
MICRO_REGISTRY_ADDRESS: 127.0.0.1:9233
|
||||
|
||||
@@ -38,3 +38,19 @@ In this example, the admin user (configured in `config/ldap/ldif/20_users.ldif`
|
||||
**Security Note:** Master-ID grants member status only (not admin privileges). Regular users require specific instance IDs for access control.
|
||||
|
||||
|
||||
|
||||
## Vault Mode
|
||||
|
||||
You can enable the vault storage on both instances. The file `vault-storage.yml` adds one extra `storage-users` service to each instance: `storage-users-vault` for `ocis` and `storage-users-vault-ocm` for `ocis-ocm`. It also enables MFA and vault mode on both `ocis` and `ocis-ocm`.
|
||||
|
||||
To start the deployment with the vault, add the file `vault-storage.yml` to the compose command:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.yml -f vault-storage.yml up -d
|
||||
```
|
||||
|
||||
Alternatively, set the `COMPOSE_FILE` environment variable:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.yml:vault-storage.yml docker compose up -d
|
||||
```
|
||||
@@ -18,7 +18,7 @@ gidNumber: 30000
|
||||
homeDirectory: /home/einstein
|
||||
ownCloudUUID: 4c510ada-c86b-4815-8820-42cdf82c3d51
|
||||
owncloudMemberOf: ec730a6c-1b63-4b45-b83b-9e2311afdf85
|
||||
ownCloudRole: ocisUser
|
||||
ownCloudRole: ocisSpaceAdmin
|
||||
userPassword:: e1NTSEF9TXJEcXpFNGdKbXZxbVRVTGhvWEZ1VzJBbkV3NWFLK3J3WTIvbHc9PQ==
|
||||
|
||||
dn: uid=marie,ou=users,dc=owncloud,dc=com
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
services:
|
||||
ocis:
|
||||
environment:
|
||||
OCIS_MFA_ENABLED: true
|
||||
NATS_NATS_HOST: 0.0.0.0
|
||||
SETTINGS_GRPC_ADDR: ocis:9191
|
||||
OCIS_ENABLE_VAULT_MODE: true
|
||||
|
||||
ocis-ocm:
|
||||
environment:
|
||||
OCIS_MFA_ENABLED: true
|
||||
SETTINGS_GRPC_ADDR: ocis-ocm:9191
|
||||
OCIS_ENABLE_VAULT_MODE: true
|
||||
|
||||
storage-users-vault:
|
||||
image: ${OCIS_DOCKER_IMAGE:-owncloud/ocis}:${OCIS_DOCKER_TAG:-latest}
|
||||
networks:
|
||||
ocis-net:
|
||||
depends_on:
|
||||
ocis:
|
||||
condition: service_started
|
||||
command: ["storage-users", "server"]
|
||||
environment:
|
||||
OCIS_LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
OCIS_LOG_COLOR: "${LOG_PRETTY:-false}"
|
||||
OCIS_LOG_PRETTY: "${LOG_PRETTY:-false}"
|
||||
OCIS_GATEWAY_GRPC_ADDR: ocis:9142
|
||||
OCIS_EVENTS_ENDPOINT: ocis:9233
|
||||
OCIS_CACHE_STORE_NODES: ocis:9233
|
||||
MICRO_REGISTRY_ADDRESS: ocis:9233
|
||||
# configure vault mode for the storage users service
|
||||
STORAGE_USERS_ENABLE_VAULT_MODE: true
|
||||
STORAGE_USERS_SERVICE_NAME: storage-users-vault
|
||||
STORAGE_USERS_GRPC_ADDR: storage-users-vault:9285
|
||||
STORAGE_USERS_HTTP_ADDR: storage-users-vault:9286
|
||||
STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault:9286/data
|
||||
STORAGE_USERS_DEBUG_ADDR: storage-users-vault:9287
|
||||
STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault
|
||||
STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs
|
||||
volumes:
|
||||
# use the same volumes as the ocis service
|
||||
- ${OCIS_CONFIG_DIR:-ocis-config}:/etc/ocis
|
||||
- ${OCIS_DATA_DIR:-ocis-data}:/var/lib/ocis
|
||||
logging:
|
||||
driver: ${LOG_DRIVER:-local}
|
||||
restart: always
|
||||
|
||||
storage-users-vault-ocm:
|
||||
image: ${OCIS_DOCKER_IMAGE:-owncloud/ocis}:${OCIS_DOCKER_TAG:-latest}
|
||||
networks:
|
||||
ocis-net:
|
||||
depends_on:
|
||||
ocis-ocm:
|
||||
condition: service_started
|
||||
command: ["storage-users", "server"]
|
||||
environment:
|
||||
OCIS_LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
OCIS_LOG_COLOR: "${LOG_PRETTY:-false}"
|
||||
OCIS_LOG_PRETTY: "${LOG_PRETTY:-false}"
|
||||
OCIS_GATEWAY_GRPC_ADDR: ocis-ocm:9142
|
||||
OCIS_EVENTS_ENDPOINT: ocis-ocm:9233
|
||||
OCIS_CACHE_STORE_NODES: ocis-ocm:9233
|
||||
MICRO_REGISTRY_ADDRESS: ocis-ocm:9233
|
||||
# configure vault mode for the storage users service
|
||||
STORAGE_USERS_ENABLE_VAULT_MODE: true
|
||||
STORAGE_USERS_SERVICE_NAME: storage-users-vault
|
||||
STORAGE_USERS_GRPC_ADDR: storage-users-vault-ocm:9285
|
||||
STORAGE_USERS_HTTP_ADDR: storage-users-vault-ocm:9286
|
||||
STORAGE_USERS_DATA_SERVER_URL: http://storage-users-vault-ocm:9286/data
|
||||
STORAGE_USERS_DEBUG_ADDR: storage-users-vault-ocm:9287
|
||||
STORAGE_USERS_OCIS_ROOT: /var/lib/ocis/storage/users-vault
|
||||
STORAGE_USERS_EVENTS_CONSUMER_GROUP: vault-dcfs
|
||||
volumes:
|
||||
# use the same volumes as the ocis-ocm service
|
||||
- ${OCIS_OCM_CONFIG_DIR:-ocis-ocm-config}:/etc/ocis
|
||||
- ${OCIS_OCM_DATA_DIR:-ocis-ocm-data}:/var/lib/ocis
|
||||
logging:
|
||||
driver: ${LOG_DRIVER:-local}
|
||||
restart: always
|
||||
@@ -67,7 +67,7 @@ require (
|
||||
github.com/open-policy-agent/opa v1.21.1
|
||||
github.com/orcaman/concurrent-map v1.0.0
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
@@ -97,14 +97,14 @@ require (
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0
|
||||
go.opentelemetry.io/otel/sdk v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/net v0.62.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
golang.org/x/term v0.47.0
|
||||
golang.org/x/text v0.43.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
|
||||
google.golang.org/grpc v1.86.0-dev
|
||||
google.golang.org/protobuf v1.36.12
|
||||
@@ -191,7 +191,7 @@ require (
|
||||
github.com/go-git/go-billy/v5 v5.9.0 // indirect
|
||||
github.com/go-git/go-git/v5 v5.19.2 // indirect
|
||||
github.com/go-jose/go-jose/v3 v3.0.5 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
|
||||
github.com/go-kit/log v0.2.1 // indirect
|
||||
github.com/go-logfmt/logfmt v0.5.1 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
@@ -341,9 +341,9 @@ require (
|
||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/mod v0.41.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/time v0.16.0 // indirect
|
||||
golang.org/x/tools v0.50.0 // indirect
|
||||
golang.org/x/tools v0.51.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20260622175928-b703f567277d // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
|
||||
|
||||
@@ -306,8 +306,8 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2
|
||||
github.com/go-jose/go-jose/v3 v3.0.3/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
|
||||
github.com/go-jose/go-jose/v3 v3.0.5 h1:BLLJWbC4nMZOfuPVxoZIxeYsn6Nl2r1fITaJ78UQlVQ=
|
||||
github.com/go-jose/go-jose/v3 v3.0.5/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4=
|
||||
github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
|
||||
@@ -736,8 +736,10 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899 h1:IMu076AtnFEdabpBbowcGDYOeFLtm9ycNY1Z43YPYZU=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575 h1:GOsblJHW/dvNdxxXmCb/PZOGRIg1ci4SVs+pA7hw6t4=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261019155447-90c24c1b3575/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629 h1:h0jekinxPFEwKl0IkGT8iYOca9ZdIXJDixIIFI/yhfY=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261022133635-764ed1d17629/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
|
||||
@@ -1018,8 +1020,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -1102,8 +1104,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -1191,8 +1193,8 @@ golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@@ -1200,8 +1202,8 @@ golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
|
||||
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -1213,8 +1215,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
@@ -1267,8 +1269,8 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f
|
||||
golang.org/x/tools v0.0.0-20210112230658-8b4aab62c064/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
|
||||
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
|
||||
@@ -501,15 +501,6 @@ func revaShareConfig(cfg *sharing.Config) map[string]interface{} {
|
||||
"enable_expired_shares_cleanup": cfg.UserSharingDrivers.SQL.EnableExpiredSharesCleanup,
|
||||
"janitor_run_interval": cfg.UserSharingDrivers.SQL.JanitorRunInterval,
|
||||
},
|
||||
"owncloudsql": map[string]interface{}{
|
||||
"gateway_addr": cfg.Reva.Address,
|
||||
"storage_mount_id": cfg.UserSharingDrivers.OwnCloudSQL.UserStorageMountID,
|
||||
"db_username": cfg.UserSharingDrivers.OwnCloudSQL.DBUsername,
|
||||
"db_password": cfg.UserSharingDrivers.OwnCloudSQL.DBPassword,
|
||||
"db_host": cfg.UserSharingDrivers.OwnCloudSQL.DBHost,
|
||||
"db_port": cfg.UserSharingDrivers.OwnCloudSQL.DBPort,
|
||||
"db_name": cfg.UserSharingDrivers.OwnCloudSQL.DBName,
|
||||
},
|
||||
"cs3": map[string]interface{}{
|
||||
"gateway_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
|
||||
"provider_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
|
||||
|
||||
@@ -52,9 +52,8 @@ type GRPCConfig struct {
|
||||
}
|
||||
|
||||
type AuthProviders struct {
|
||||
LDAP LDAPProvider `yaml:"ldap"`
|
||||
OwnCloudSQL OwnCloudSQLProvider `yaml:"owncloudsql"`
|
||||
JSON JSONProvider `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
LDAP LDAPProvider `yaml:"ldap"`
|
||||
JSON JSONProvider `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
}
|
||||
|
||||
type JSONProvider struct {
|
||||
@@ -110,15 +109,3 @@ type LDAPGroupSchema struct {
|
||||
Groupname string `yaml:"group_name" env:"OCIS_LDAP_GROUP_SCHEMA_GROUPNAME;AUTH_BASIC_LDAP_GROUP_SCHEMA_GROUPNAME" desc:"LDAP Attribute to use for the name of groups." introductionVersion:"pre5.0"`
|
||||
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;AUTH_BASIC_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
type OwnCloudSQLProvider struct {
|
||||
DBUsername string `yaml:"db_username" env:"AUTH_BASIC_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
|
||||
DBPassword string `yaml:"db_password" env:"AUTH_BASIC_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
|
||||
DBHost string `yaml:"db_host" env:"AUTH_BASIC_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
|
||||
DBPort int `yaml:"db_port" env:"AUTH_BASIC_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
|
||||
DBName string `yaml:"db_name" env:"AUTH_BASIC_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
|
||||
IDP string `yaml:"idp" env:"AUTH_BASIC_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
|
||||
Nobody int64 `yaml:"nobody" env:"AUTH_BASIC_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
|
||||
JoinUsername bool `yaml:"join_username" env:"AUTH_BASIC_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames" introductionVersion:"pre5.0"`
|
||||
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"AUTH_BASIC_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user ID's." introductionVersion:"pre5.0"`
|
||||
}
|
||||
@@ -76,16 +76,6 @@ func DefaultConfig() *config.Config {
|
||||
},
|
||||
},
|
||||
JSON: config.JSONProvider{},
|
||||
OwnCloudSQL: config.OwnCloudSQLProvider{
|
||||
DBUsername: "owncloud",
|
||||
DBHost: "mysql",
|
||||
DBPort: 3306,
|
||||
DBName: "owncloud",
|
||||
IDP: "https://localhost:9200",
|
||||
Nobody: 90,
|
||||
JoinUsername: false,
|
||||
JoinOwnCloudUUID: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,17 +30,6 @@ func AuthBasicConfigFromStruct(cfg *config.Config) map[string]interface{} {
|
||||
"users": cfg.AuthProviders.JSON.File,
|
||||
},
|
||||
"ldap": ldapConfigFromString(cfg.AuthProviders.LDAP),
|
||||
"owncloudsql": map[string]interface{}{
|
||||
"dbusername": cfg.AuthProviders.OwnCloudSQL.DBUsername,
|
||||
"dbpassword": cfg.AuthProviders.OwnCloudSQL.DBPassword,
|
||||
"dbhost": cfg.AuthProviders.OwnCloudSQL.DBHost,
|
||||
"dbport": cfg.AuthProviders.OwnCloudSQL.DBPort,
|
||||
"dbname": cfg.AuthProviders.OwnCloudSQL.DBName,
|
||||
"idp": cfg.AuthProviders.OwnCloudSQL.IDP,
|
||||
"nobody": cfg.AuthProviders.OwnCloudSQL.Nobody,
|
||||
"join_username": cfg.AuthProviders.OwnCloudSQL.JoinUsername,
|
||||
"join_ownclouduuid": cfg.AuthProviders.OwnCloudSQL.JoinOwnCloudUUID,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1241,8 +1241,17 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
|
||||
privateLinkURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetId()))
|
||||
parentFolderURL := &url.URL{}
|
||||
*parentFolderURL = *ocisURL
|
||||
breadcrumbFolderURL := ""
|
||||
if !isPublicShare {
|
||||
parentFolderURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetParentId()))
|
||||
// the parent folder isn't always accessible, e.g. for a file shared directly with
|
||||
// the user. Only link to it if it is, closing falls back to the oCIS URL otherwise.
|
||||
parentStatRes, err := gwc.Stat(ctx, &providerv1beta1.StatRequest{
|
||||
Ref: &providerv1beta1.Reference{ResourceId: statRes.GetInfo().GetParentId()},
|
||||
})
|
||||
if err == nil && parentStatRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_OK {
|
||||
parentFolderURL.Path = path.Join(ocisURL.Path, "f", storagespace.FormatResourceID(statRes.GetInfo().GetParentId()))
|
||||
breadcrumbFolderURL = parentFolderURL.String()
|
||||
}
|
||||
} else {
|
||||
if scopes, ok := ctxpkg.ContextGetScopes(ctx); ok {
|
||||
publicShare := &link.PublicShare{}
|
||||
@@ -1254,6 +1263,7 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
|
||||
} else {
|
||||
logger.Error().Err(err).Msg("CheckFileInfo: error getting scopes from the context")
|
||||
}
|
||||
breadcrumbFolderURL = parentFolderURL.String()
|
||||
}
|
||||
// BreadcrumbBrandURL points at the space's root resource, exposing an internal
|
||||
// space/resource id; for public shares an anonymous user has no other way to reach
|
||||
@@ -1297,11 +1307,11 @@ func (f *FileConnector) CheckFileInfo(ctx context.Context) (*ConnectorResponse,
|
||||
fileinfo.KeyBreadcrumbDocName: path.Base(statRes.GetInfo().GetPath()),
|
||||
// to get the folder we actually need to do a GetPath() request
|
||||
fileinfo.KeyBreadcrumbFolderName: breadcrumbFolderName,
|
||||
fileinfo.KeyBreadcrumbFolderURL: parentFolderURL.String(),
|
||||
fileinfo.KeyBreadcrumbFolderURL: breadcrumbFolderURL,
|
||||
fileinfo.KeyBreadcrumbBrandName: statRes.GetInfo().GetSpace().GetName(),
|
||||
fileinfo.KeyBreadcrumbBrandURL: breadcrumbBrandURL,
|
||||
// the WOPI client should navigate here when the editor is closed; the folder
|
||||
// containing the file is the same target used for the breadcrumb folder link
|
||||
// containing the file if the user can access it, the oCIS URL otherwise
|
||||
fileinfo.KeyCloseURL: parentFolderURL.String(),
|
||||
|
||||
fileinfo.KeyHostViewURL: createHostUrl("view", ocisURL, f.cfg.App.Name, statRes.GetInfo()),
|
||||
|
||||
@@ -1713,6 +1713,17 @@ var _ = Describe("FileConnector", func() {
|
||||
})
|
||||
|
||||
Describe("CheckFileInfo", func() {
|
||||
var parentStatRes *providerv1beta1.StatResponse
|
||||
BeforeEach(func() {
|
||||
// CheckFileInfo stats the parent folder to check whether the user can access it
|
||||
parentStatRes = &providerv1beta1.StatResponse{Status: status.NewOK(context.Background())}
|
||||
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(req *providerv1beta1.StatRequest) bool {
|
||||
return req.GetRef().GetResourceId().GetOpaqueId() != wopiCtx.FileReference.GetResourceId().GetOpaqueId()
|
||||
})).Maybe().Return(func(context.Context, *providerv1beta1.StatRequest, ...grpc.CallOption) (*providerv1beta1.StatResponse, error) {
|
||||
return parentStatRes, nil
|
||||
})
|
||||
})
|
||||
|
||||
It("No valid context", func() {
|
||||
gatewaySelector.EXPECT().Next().Unset()
|
||||
ctx := context.Background()
|
||||
@@ -3396,6 +3407,64 @@ var _ = Describe("FileConnector", func() {
|
||||
Expect(collaboraResponse.BreadcrumbFolderURL).To(Equal("https://ocis.example.prv/f/storageid$spaceid%21documentsid"))
|
||||
})
|
||||
|
||||
It("Collabora CheckFileInfo omits the folder link if the parent folder isn't accessible", func() {
|
||||
// e.g. a file shared directly with the user, its parent folder belongs to the sharer
|
||||
parentStatRes = &providerv1beta1.StatResponse{Status: status.NewNotFound(context.Background(), "not found")}
|
||||
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
u := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{
|
||||
Idp: "customIdp",
|
||||
OpaqueId: "admin",
|
||||
},
|
||||
DisplayName: "Pet Shaft",
|
||||
}
|
||||
ctx = ctxpkg.ContextSetUser(ctx, u)
|
||||
|
||||
gatewayClient.On("Stat", mock.Anything, mock.Anything).Times(1).Return(&providerv1beta1.StatResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
Info: &providerv1beta1.ResourceInfo{
|
||||
Owner: &userv1beta1.UserId{
|
||||
Idp: "customIdp",
|
||||
OpaqueId: "aabbcc",
|
||||
Type: userv1beta1.UserType_USER_TYPE_PRIMARY,
|
||||
},
|
||||
Size: uint64(998877),
|
||||
Mtime: &typesv1beta1.Timestamp{Seconds: uint64(16273849)},
|
||||
Path: "/personal/user/Documents/report.docx",
|
||||
Id: &providerv1beta1.ResourceId{
|
||||
StorageId: "storageid",
|
||||
OpaqueId: "fileid",
|
||||
SpaceId: "spaceid",
|
||||
},
|
||||
ParentId: &providerv1beta1.ResourceId{
|
||||
StorageId: "storageid",
|
||||
OpaqueId: "documentsid",
|
||||
SpaceId: "spaceid",
|
||||
},
|
||||
Space: &providerv1beta1.StorageSpace{
|
||||
Name: "Personal",
|
||||
Root: &providerv1beta1.ResourceId{
|
||||
StorageId: "storageid",
|
||||
OpaqueId: "rootid",
|
||||
SpaceId: "spaceid",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
cfg.App.Name = "Collabora"
|
||||
cfg.App.Product = "Collabora"
|
||||
|
||||
response, err := fc.CheckFileInfo(ctx)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(response.Status).To(Equal(200))
|
||||
|
||||
collaboraResponse := response.Body.(*fileinfo.Collabora)
|
||||
Expect(collaboraResponse.BreadcrumbFolderURL).To(BeEmpty())
|
||||
Expect(collaboraResponse.CloseURL).To(Equal("https://ocis.example.prv"))
|
||||
})
|
||||
|
||||
It("Collabora CheckFileInfo breadcrumb folder name falls back to the space name for a file at the space root", func() {
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
u := &userv1beta1.User{
|
||||
|
||||
@@ -84,20 +84,23 @@ type LDAP struct {
|
||||
PoolSize int `yaml:"pool_size" env:"OCIS_LDAP_POOL_SIZE;GRAPH_LDAP_POOL_SIZE" desc:"Maximum number of concurrently open LDAP connections when 'OCIS_LDAP_POOL_ENABLED' is 'true'. Defaults to 5 when unset or <= 0." introductionVersion:"8.2.0"`
|
||||
PoolCheckoutTimeout time.Duration `yaml:"pool_checkout_timeout" env:"OCIS_LDAP_POOL_CHECKOUT_TIMEOUT;GRAPH_LDAP_POOL_CHECKOUT_TIMEOUT" desc:"Maximum time to wait for a pooled LDAP connection to become available once the pool is exhausted. Defaults to 30s when unset or <= 0. See the Environment Variable Types description for more details." introductionVersion:"8.2.0"`
|
||||
|
||||
UserBaseDN string `yaml:"user_base_dn" env:"OCIS_LDAP_USER_BASE_DN;GRAPH_LDAP_USER_BASE_DN" desc:"Search base DN for looking up LDAP users." introductionVersion:"pre5.0"`
|
||||
UserSearchScope string `yaml:"user_search_scope" env:"OCIS_LDAP_USER_SCOPE;GRAPH_LDAP_USER_SCOPE" desc:"LDAP search scope to use when looking up users. Supported scopes are 'base', 'one' and 'sub'." introductionVersion:"pre5.0"`
|
||||
UserFilter string `yaml:"user_filter" env:"OCIS_LDAP_USER_FILTER;GRAPH_LDAP_USER_FILTER" desc:"LDAP filter to add to the default filters for user search like '(objectclass=ownCloud)'." introductionVersion:"pre5.0"`
|
||||
UserObjectClass string `yaml:"user_objectclass" env:"OCIS_LDAP_USER_OBJECTCLASS;GRAPH_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
|
||||
UserEmailAttribute string `yaml:"user_mail_attribute" env:"OCIS_LDAP_USER_SCHEMA_MAIL;GRAPH_LDAP_USER_EMAIL_ATTRIBUTE" desc:"LDAP Attribute to use for the email address of users." introductionVersion:"pre5.0"`
|
||||
UserDisplayNameAttribute string `yaml:"user_displayname_attribute" env:"OCIS_LDAP_USER_SCHEMA_DISPLAYNAME;GRAPH_LDAP_USER_DISPLAYNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the display name of users." introductionVersion:"pre5.0"`
|
||||
UserNameAttribute string `yaml:"user_name_attribute" env:"OCIS_LDAP_USER_SCHEMA_USERNAME;GRAPH_LDAP_USER_NAME_ATTRIBUTE" desc:"LDAP Attribute to use for username of users." introductionVersion:"pre5.0"`
|
||||
UserIDAttribute string `yaml:"user_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_ID;GRAPH_LDAP_USER_UID_ATTRIBUTE" desc:"LDAP Attribute to use as the unique ID for users. This should be a stable globally unique ID like a UUID." introductionVersion:"pre5.0"`
|
||||
UserIDIsOctetString bool `yaml:"user_id_is_octet_string" env:"OCIS_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING;GRAPH_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING" desc:"Set this to true if the defined 'ID' attribute for users is of the 'OCTETSTRING' syntax. This is required when using the 'objectGUID' attribute of Active Directory for the user ID's." introductionVersion:"pre5.0"`
|
||||
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;GRAPH_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
|
||||
UserEnabledAttribute string `yaml:"user_enabled_attribute" env:"OCIS_LDAP_USER_ENABLED_ATTRIBUTE;GRAPH_USER_ENABLED_ATTRIBUTE" desc:"LDAP Attribute to use as a flag telling if the user is enabled or disabled." introductionVersion:"pre5.0"`
|
||||
ExternalIDAttribute string `yaml:"external_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID;GRAPH_LDAP_EXTERNAL_ID_ATTRIBUTE" desc:"LDAP attribute that references the external ID of users during the provisioning process. The final ID is provided by an external identity provider. If it is not set, a default attribute will be used instead." introductionVersion:"8.0.0"`
|
||||
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;GRAPH_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Supported options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed. Default is 'attribute'." introductionVersion:"pre5.0"`
|
||||
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;GRAPH_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
|
||||
UserBaseDN string `yaml:"user_base_dn" env:"OCIS_LDAP_USER_BASE_DN;GRAPH_LDAP_USER_BASE_DN" desc:"Search base DN for looking up LDAP users." introductionVersion:"pre5.0"`
|
||||
UserSearchScope string `yaml:"user_search_scope" env:"OCIS_LDAP_USER_SCOPE;GRAPH_LDAP_USER_SCOPE" desc:"LDAP search scope to use when looking up users. Supported scopes are 'base', 'one' and 'sub'." introductionVersion:"pre5.0"`
|
||||
UserFilter string `yaml:"user_filter" env:"OCIS_LDAP_USER_FILTER;GRAPH_LDAP_USER_FILTER" desc:"LDAP filter to add to the default filters for user search like '(objectclass=ownCloud)'." introductionVersion:"pre5.0"`
|
||||
UserObjectClass string `yaml:"user_objectclass" env:"OCIS_LDAP_USER_OBJECTCLASS;GRAPH_LDAP_USER_OBJECTCLASS" desc:"The object class to use for users in the default user search filter ('inetOrgPerson')." introductionVersion:"pre5.0"`
|
||||
UserAdditionalObjectClasses []string `yaml:"user_additional_objectclasses" env:"OCIS_LDAP_USER_ADDITIONAL_OBJECTCLASSES;GRAPH_LDAP_USER_ADDITIONAL_OBJECTCLASSES" desc:"Additional object classes to set when creating new users (e.g. to allow a custom surname attribute). The default classes 'inetOrgPerson', 'organizationalPerson', 'person', 'top' and 'ownCloudUser' are always included." introductionVersion:"9.0.0"`
|
||||
UserEmailAttribute string `yaml:"user_mail_attribute" env:"OCIS_LDAP_USER_SCHEMA_MAIL;GRAPH_LDAP_USER_EMAIL_ATTRIBUTE" desc:"LDAP Attribute to use for the email address of users." introductionVersion:"pre5.0"`
|
||||
UserDisplayNameAttribute string `yaml:"user_displayname_attribute" env:"OCIS_LDAP_USER_SCHEMA_DISPLAYNAME;GRAPH_LDAP_USER_DISPLAYNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the display name of users." introductionVersion:"pre5.0"`
|
||||
UserNameAttribute string `yaml:"user_name_attribute" env:"OCIS_LDAP_USER_SCHEMA_USERNAME;GRAPH_LDAP_USER_NAME_ATTRIBUTE" desc:"LDAP Attribute to use for username of users." introductionVersion:"pre5.0"`
|
||||
UserSurnameAttribute string `yaml:"user_surname_attribute" env:"OCIS_LDAP_USER_SCHEMA_SURNAME;GRAPH_LDAP_USER_SURNAME_ATTRIBUTE" desc:"LDAP Attribute to use for the surname of users." introductionVersion:"9.0.0"`
|
||||
UserSearchAttributes []string `yaml:"user_search_attributes" env:"GRAPH_LDAP_USER_SEARCH_ATTRIBUTES" desc:"The user attributes to match against when searching for users via the Graph API. Does not affect the legacy OCS sharees search, which always matches on username, display name, and mail. Accepts the logical names 'onPremisesSamAccountName', 'displayName', 'surname', 'mail' (case-insensitive), or any other LDAP attribute name directly." introductionVersion:"9.0.0"`
|
||||
UserIDAttribute string `yaml:"user_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_ID;GRAPH_LDAP_USER_UID_ATTRIBUTE" desc:"LDAP Attribute to use as the unique ID for users. This should be a stable globally unique ID like a UUID." introductionVersion:"pre5.0"`
|
||||
UserIDIsOctetString bool `yaml:"user_id_is_octet_string" env:"OCIS_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING;GRAPH_LDAP_USER_SCHEMA_ID_IS_OCTETSTRING" desc:"Set this to true if the defined 'ID' attribute for users is of the 'OCTETSTRING' syntax. This is required when using the 'objectGUID' attribute of Active Directory for the user ID's." introductionVersion:"pre5.0"`
|
||||
UserTypeAttribute string `yaml:"user_type_attribute" env:"OCIS_LDAP_USER_SCHEMA_USER_TYPE;GRAPH_LDAP_USER_TYPE_ATTRIBUTE" desc:"LDAP Attribute to distinguish between 'Member' and 'Guest' users. Default is 'ownCloudUserType'." introductionVersion:"pre5.0"`
|
||||
UserEnabledAttribute string `yaml:"user_enabled_attribute" env:"OCIS_LDAP_USER_ENABLED_ATTRIBUTE;GRAPH_USER_ENABLED_ATTRIBUTE" desc:"LDAP Attribute to use as a flag telling if the user is enabled or disabled." introductionVersion:"pre5.0"`
|
||||
ExternalIDAttribute string `yaml:"external_id_attribute" env:"OCIS_LDAP_USER_SCHEMA_EXTERNAL_ID;GRAPH_LDAP_EXTERNAL_ID_ATTRIBUTE" desc:"LDAP attribute that references the external ID of users during the provisioning process. The final ID is provided by an external identity provider. If it is not set, a default attribute will be used instead." introductionVersion:"8.0.0"`
|
||||
DisableUserMechanism string `yaml:"disable_user_mechanism" env:"OCIS_LDAP_DISABLE_USER_MECHANISM;GRAPH_DISABLE_USER_MECHANISM" desc:"An option to control the behavior for disabling users. Supported options are 'none', 'attribute' and 'group'. If set to 'group', disabling a user via API will add the user to the configured group for disabled users, if set to 'attribute' this will be done in the ldap user entry, if set to 'none' the disable request is not processed. Default is 'attribute'." introductionVersion:"pre5.0"`
|
||||
LdapDisabledUsersGroupDN string `yaml:"ldap_disabled_users_group_dn" env:"OCIS_LDAP_DISABLED_USERS_GROUP_DN;GRAPH_DISABLED_USERS_GROUP_DN" desc:"The distinguished name of the group to which added users will be classified as disabled when 'disable_user_mechanism' is set to 'group'." introductionVersion:"pre5.0"`
|
||||
|
||||
GroupBaseDN string `yaml:"group_base_dn" env:"OCIS_LDAP_GROUP_BASE_DN;GRAPH_LDAP_GROUP_BASE_DN" desc:"Search base DN for looking up LDAP groups." introductionVersion:"pre5.0"`
|
||||
GroupCreateBaseDN string `yaml:"group_create_base_dn" env:"GRAPH_LDAP_GROUP_CREATE_BASE_DN" desc:"Parent DN under which new groups are created. This DN needs to be subordinate to the 'GRAPH_LDAP_GROUP_BASE_DN'. This setting is only relevant when 'GRAPH_LDAP_SERVER_WRITE_ENABLED' is 'true'. It defaults to the value of 'GRAPH_LDAP_GROUP_BASE_DN'. All groups outside of this subtree are treated as readonly groups and cannot be updated." introductionVersion:"pre5.0"`
|
||||
|
||||
@@ -104,6 +104,8 @@ func DefaultConfig() *config.Config {
|
||||
UserEmailAttribute: "mail",
|
||||
UserDisplayNameAttribute: "displayName",
|
||||
UserNameAttribute: "uid",
|
||||
UserSurnameAttribute: "sn",
|
||||
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
|
||||
// FIXME: switch this to some more widely available attribute by default
|
||||
// ideally this needs to be constant for the lifetime of a users
|
||||
UserIDAttribute: "ownCloudUUID",
|
||||
|
||||
@@ -27,7 +27,6 @@ import (
|
||||
|
||||
const (
|
||||
givenNameAttribute = "givenname"
|
||||
surNameAttribute = "sn"
|
||||
identitiesAttribute = "oCExternalIdentity"
|
||||
lastSignAttribute = "oCLastSignInTimestamp"
|
||||
ldapDateFormat = "20060102150405Z0700"
|
||||
@@ -61,12 +60,14 @@ type LDAP struct {
|
||||
retryBaseDelay time.Duration
|
||||
retryMaxDelay time.Duration
|
||||
|
||||
userBaseDN string
|
||||
userFilter string
|
||||
userObjectClass string
|
||||
userIDisOctetString bool
|
||||
userScope int
|
||||
userAttributeMap userAttributeMap
|
||||
userBaseDN string
|
||||
userFilter string
|
||||
userObjectClass string
|
||||
userAdditionalObjectClasses []string
|
||||
userIDisOctetString bool
|
||||
userScope int
|
||||
userAttributeMap userAttributeMap
|
||||
userSearchFilterTemplate string
|
||||
|
||||
disableUserMechanism DisableUserMechanismType
|
||||
localUserDisableGroupDN string
|
||||
@@ -144,9 +145,24 @@ func ParseDisableMechanismType(disableMechanism string) (DisableUserMechanismTyp
|
||||
}
|
||||
|
||||
func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, instanceID string, masterID string) (*LDAP, error) {
|
||||
if config.UserDisplayNameAttribute == "" || config.UserIDAttribute == "" ||
|
||||
config.UserEmailAttribute == "" || config.UserNameAttribute == "" {
|
||||
return nil, errors.New("invalid user attribute mappings")
|
||||
requiredUserAttrs := map[string]string{
|
||||
"UserDisplayNameAttribute": config.UserDisplayNameAttribute,
|
||||
"UserIDAttribute": config.UserIDAttribute,
|
||||
"UserEmailAttribute": config.UserEmailAttribute,
|
||||
"UserNameAttribute": config.UserNameAttribute,
|
||||
"UserSurnameAttribute": config.UserSurnameAttribute,
|
||||
}
|
||||
for name, value := range requiredUserAttrs {
|
||||
if value == "" {
|
||||
return nil, fmt.Errorf("invalid user attribute mappings: %s must not be empty", name)
|
||||
}
|
||||
}
|
||||
// Normalize to the canonical "sn" spelling (LDAP attribute names are case-insensitive,
|
||||
// and "surname" is its RFC 4519 schema alias) so downstream code can do a plain string
|
||||
// compare instead of re-checking case/alias on every use.
|
||||
surnameAttribute := config.UserSurnameAttribute
|
||||
if strings.EqualFold(surnameAttribute, "sn") || strings.EqualFold(surnameAttribute, "surname") {
|
||||
surnameAttribute = "sn"
|
||||
}
|
||||
uam := userAttributeMap{
|
||||
displayName: config.UserDisplayNameAttribute,
|
||||
@@ -155,7 +171,7 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
|
||||
userName: config.UserNameAttribute,
|
||||
accountEnabled: config.UserEnabledAttribute,
|
||||
givenName: givenNameAttribute,
|
||||
surname: surNameAttribute,
|
||||
surname: surnameAttribute,
|
||||
userType: config.UserTypeAttribute,
|
||||
identities: identitiesAttribute,
|
||||
lastSignIn: lastSignAttribute,
|
||||
@@ -163,6 +179,10 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
|
||||
userMemberAttribute: config.UserMemberAttribute,
|
||||
userGuestAttribute: config.UserGuestAttribute,
|
||||
}
|
||||
userSearchFilterTemplate, searchAttrErr := userSearchFilterTemplateFor(uam, config.UserSearchAttributes)
|
||||
if searchAttrErr != nil {
|
||||
return nil, fmt.Errorf("error configuring user search attributes: %w", searchAttrErr)
|
||||
}
|
||||
|
||||
if config.GroupNameAttribute == "" || config.GroupIDAttribute == "" {
|
||||
return nil, errors.New("invalid group attribute mappings")
|
||||
@@ -234,9 +254,11 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst
|
||||
userBaseDN: config.UserBaseDN,
|
||||
userFilter: config.UserFilter,
|
||||
userObjectClass: config.UserObjectClass,
|
||||
userAdditionalObjectClasses: config.UserAdditionalObjectClasses,
|
||||
userIDisOctetString: config.UserIDIsOctetString,
|
||||
userScope: userScope,
|
||||
userAttributeMap: uam,
|
||||
userSearchFilterTemplate: userSearchFilterTemplate,
|
||||
groupBaseDN: config.GroupBaseDN,
|
||||
groupCreateBaseDN: config.GroupCreateBaseDN,
|
||||
groupFilter: config.GroupFilter,
|
||||
@@ -423,6 +445,15 @@ func (i *LDAP) UpdateUser(ctx context.Context, nameOrID string, user libregraph.
|
||||
}
|
||||
}
|
||||
|
||||
// person's mandatory "sn" is a separate attribute from the configured one above;
|
||||
// keep it in sync like CreateUser does.
|
||||
if sn := user.GetSurname(); sn != "" && i.mirrorSurnameIntoSN() {
|
||||
if e.GetEqualFoldAttributeValue("sn") != sn {
|
||||
mr.Replace("sn", []string{sn})
|
||||
updateNeeded = true
|
||||
}
|
||||
}
|
||||
|
||||
if user.PasswordProfile != nil && user.PasswordProfile.GetPassword() != "" {
|
||||
if i.usePwModifyExOp {
|
||||
if err := i.updateUserPassword(ctx, e.DN, user.PasswordProfile.GetPassword()); err != nil {
|
||||
@@ -525,6 +556,47 @@ func (i *LDAP) AddUser(ctx context.Context, id string, instanceID string) (libre
|
||||
return *u, nil
|
||||
}
|
||||
|
||||
// %[1]s is reused by every clause so userSearchFilter fills them all with one Sprintf arg.
|
||||
// Excluding mail from the configured names keeps search from revealing which address is whose.
|
||||
func userSearchFilterTemplateFor(uam userAttributeMap, logicalNames []string) (string, error) {
|
||||
if len(logicalNames) == 0 {
|
||||
return "", errors.New("at least one user search attribute must be configured")
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("(|")
|
||||
for _, name := range logicalNames {
|
||||
var attr string
|
||||
switch {
|
||||
case strings.EqualFold(name, "onPremisesSamAccountName"):
|
||||
attr = uam.userName
|
||||
case strings.EqualFold(name, "displayName"):
|
||||
attr = uam.displayName
|
||||
case strings.EqualFold(name, "surname"):
|
||||
attr = uam.surname
|
||||
case strings.EqualFold(name, "mail"):
|
||||
attr = uam.mail
|
||||
default:
|
||||
// Not one of the known logical names; treat it as a literal LDAP attribute
|
||||
// name so admins can search on attributes graph has no logical name for (e.g. "uid").
|
||||
attr = name
|
||||
}
|
||||
b.WriteString("(")
|
||||
// attr is admin-configured, not user input, but a literal '%' would still corrupt the
|
||||
// Sprintf template below
|
||||
b.WriteString(strings.ReplaceAll(attr, "%", "%%"))
|
||||
b.WriteString("=*%[1]s*)")
|
||||
}
|
||||
b.WriteString(")")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (i *LDAP) userSearchFilter(term string) string {
|
||||
if term == "" || i.userSearchFilterTemplate == "" {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(i.userSearchFilterTemplate, ldap.EscapeFilter(term))
|
||||
}
|
||||
|
||||
func (i *LDAP) getUserByDN(dn, searchTerm string) (*ldap.Entry, error) {
|
||||
baseFilter := fmt.Sprintf("(objectClass=%s)", i.userObjectClass)
|
||||
|
||||
@@ -532,16 +604,7 @@ func (i *LDAP) getUserByDN(dn, searchTerm string) (*ldap.Entry, error) {
|
||||
if i.userFilter != "" {
|
||||
userFilter = fmt.Sprintf("(%s)", i.userFilter)
|
||||
}
|
||||
searchFilter := ""
|
||||
if searchTerm != "" {
|
||||
searchTerm = ldap.EscapeFilter(searchTerm)
|
||||
searchFilter = fmt.Sprintf(
|
||||
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
|
||||
i.userAttributeMap.userName, searchTerm,
|
||||
i.userAttributeMap.mail, searchTerm,
|
||||
i.userAttributeMap.displayName, searchTerm,
|
||||
)
|
||||
}
|
||||
searchFilter := i.userSearchFilter(searchTerm)
|
||||
|
||||
filter := baseFilter
|
||||
if userFilter != "" || searchFilter != "" {
|
||||
@@ -805,16 +868,7 @@ func (i *LDAP) FilterUsers(ctx context.Context, oreq *godata.GoDataRequest, filt
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var userFilter string
|
||||
if search != "" {
|
||||
search = ldap.EscapeFilter(search)
|
||||
userFilter = fmt.Sprintf(
|
||||
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
|
||||
i.userAttributeMap.userName, search,
|
||||
i.userAttributeMap.mail, search,
|
||||
i.userAttributeMap.displayName, search,
|
||||
)
|
||||
}
|
||||
userFilter := i.userSearchFilter(search)
|
||||
userFilter = fmt.Sprintf("(&%s(objectClass=%s)%s%s)", i.userFilter, i.userObjectClass, queryFilter, userFilter)
|
||||
searchRequest := ldap.NewSearchRequest(
|
||||
i.userBaseDN, i.userScope, ldap.NeverDerefAliases, 0, 0, false,
|
||||
@@ -1152,7 +1206,7 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
|
||||
i.userAttributeMap.displayName: {user.GetDisplayName()},
|
||||
i.userAttributeMap.userName: {user.GetOnPremisesSamAccountName()},
|
||||
i.userAttributeMap.mail: {user.GetMail()},
|
||||
"objectClass": {"inetOrgPerson", "organizationalPerson", "person", "top", "ownCloudUser"},
|
||||
"objectClass": append([]string{"inetOrgPerson", "organizationalPerson", "person", "top", "ownCloudUser"}, i.userAdditionalObjectClasses...),
|
||||
"cn": {user.GetOnPremisesSamAccountName()},
|
||||
i.userAttributeMap.userType: {user.GetUserType()},
|
||||
}
|
||||
@@ -1180,7 +1234,7 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
|
||||
}
|
||||
}
|
||||
|
||||
// inetOrgPerson requires "sn" to be set. Set it to the Username if
|
||||
// inetOrgPerson/person require "sn" to be set. Set it to the Username if
|
||||
// Surname is not set in the Request
|
||||
var sn string
|
||||
if user.Surname != nil && *user.Surname != "" {
|
||||
@@ -1189,6 +1243,10 @@ func (i *LDAP) userToLDAPAttrValues(user libregraph.User) (map[string][]string,
|
||||
sn = user.OnPremisesSamAccountName
|
||||
}
|
||||
attrs[i.userAttributeMap.surname] = []string{sn}
|
||||
if i.mirrorSurnameIntoSN() {
|
||||
// person's mandatory "sn" is a separate attribute from the configured one above
|
||||
attrs["sn"] = []string{sn}
|
||||
}
|
||||
|
||||
// When we get a givenName, we set the attribute.
|
||||
if givenName := user.GetGivenName(); givenName != "" {
|
||||
@@ -1218,6 +1276,12 @@ func (i *LDAP) identityToLDAPAttrValue(identity libregraph.ObjectIdentity) (stri
|
||||
return identityStr, nil
|
||||
}
|
||||
|
||||
// mirrorSurnameIntoSN reports whether the configured surname attribute is not itself
|
||||
// "sn", meaning person's mandatory "sn" must be kept in sync as a separate attribute.
|
||||
func (i *LDAP) mirrorSurnameIntoSN() bool {
|
||||
return i.userAttributeMap.surname != "sn"
|
||||
}
|
||||
|
||||
func (i *LDAP) getUserAttrTypesForSearch() []string {
|
||||
return []string{
|
||||
i.userAttributeMap.displayName,
|
||||
@@ -1237,7 +1301,12 @@ func (i *LDAP) getUserAttrTypesForSearch() []string {
|
||||
}
|
||||
|
||||
func (i *LDAP) getUserAttrTypes() []string {
|
||||
return append(i.getUserAttrTypesForSearch(), "cn", "userPassword", "objectClass")
|
||||
types := append(i.getUserAttrTypesForSearch(), "cn", "objectClass")
|
||||
if i.mirrorSurnameIntoSN() {
|
||||
// userToLDAPAttrValues also mirrors surname into the literal "sn" person requires
|
||||
types = append(types, "sn")
|
||||
}
|
||||
return types
|
||||
}
|
||||
|
||||
func (i *LDAP) getUserLDAPDN(user libregraph.User) string {
|
||||
@@ -1262,6 +1331,9 @@ func (i *LDAP) userToAddRequest(user libregraph.User) (*ldap.AddRequest, error)
|
||||
ar.Attribute(attrType, values)
|
||||
}
|
||||
}
|
||||
if values, ok := attrMap["userPassword"]; ok {
|
||||
ar.Attribute("userPassword", values)
|
||||
}
|
||||
return ar, nil
|
||||
}
|
||||
|
||||
@@ -1408,16 +1480,7 @@ func (i *LDAP) expandLDAPAttributeEntriesByUsername(ctx context.Context, e *ldap
|
||||
logger.Debug().Str("backend", "ldap").Msg("ExpandLDAPAttributeEntries")
|
||||
result := []*ldap.Entry{}
|
||||
|
||||
searchFilter := ""
|
||||
if searchTerm != "" {
|
||||
searchTerm = ldap.EscapeFilter(searchTerm)
|
||||
searchFilter = fmt.Sprintf(
|
||||
"(|(%s=*%s*)(%s=*%s*)(%s=*%s*))",
|
||||
i.userAttributeMap.userName, searchTerm,
|
||||
i.userAttributeMap.mail, searchTerm,
|
||||
i.userAttributeMap.displayName, searchTerm,
|
||||
)
|
||||
}
|
||||
searchFilter := i.userSearchFilter(searchTerm)
|
||||
|
||||
for _, entryUid := range e.GetEqualFoldAttributeValues(attribute) {
|
||||
if entryUid == "" {
|
||||
|
||||
@@ -24,6 +24,8 @@ var eduConfig = config.LDAP{
|
||||
UserIDAttribute: "entryUUID",
|
||||
UserEmailAttribute: "mail",
|
||||
UserNameAttribute: "uid",
|
||||
UserSurnameAttribute: "sn",
|
||||
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
|
||||
UserEnabledAttribute: "userEnabledAttribute",
|
||||
ExternalIDAttribute: "externalID",
|
||||
DisableUserMechanism: "attribute",
|
||||
|
||||
@@ -317,6 +317,48 @@ func TestGetGroupsSearch(t *testing.T) {
|
||||
t.Errorf("Expected zero length user slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetGroupMembersSearch_MemberUid(t *testing.T) {
|
||||
memberUidConfig := lconfig
|
||||
memberUidConfig.GroupMemberAttribute = "memberuid"
|
||||
|
||||
req, err := godata.ParseRequest(context.Background(), "",
|
||||
url.Values{
|
||||
"$search": []string{`"term"`},
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Errorf("Expected success got '%s'", err.Error())
|
||||
}
|
||||
|
||||
group := ldap.NewEntry("cn=group", map[string][]string{
|
||||
"cn": {"group"},
|
||||
"entryuuid": {"abcd-defg"},
|
||||
"memberuid": {"user"},
|
||||
})
|
||||
|
||||
lm := &mocks.Client{}
|
||||
lm.On("Search", mock.MatchedBy(
|
||||
func(r *ldap.SearchRequest) bool {
|
||||
return r.Filter == "(&(objectClass=groupOfNames)(|(cn=group)(entryUUID=group)))"
|
||||
})).
|
||||
Return(&ldap.SearchResult{Entries: []*ldap.Entry{group}}, nil)
|
||||
lm.On("Search", mock.MatchedBy(
|
||||
func(r *ldap.SearchRequest) bool {
|
||||
return r.Filter == "(&(objectClass=inetOrgPerson)(&(|(uid=*term*)(displayname=*term*)(mail=*term*))(uid=user)))"
|
||||
})).
|
||||
Return(&ldap.SearchResult{}, nil)
|
||||
|
||||
b, _ := getMockedBackend(lm, memberUidConfig, &logger)
|
||||
members, err := b.GetGroupMembers(context.Background(), "group", req)
|
||||
if err != nil {
|
||||
t.Errorf("Expected success, got '%s'", err.Error())
|
||||
} else if len(members) != 0 {
|
||||
t.Errorf("Expected zero length member slice")
|
||||
}
|
||||
lm.AssertExpectations(t)
|
||||
}
|
||||
|
||||
func TestUpdateGroupName(t *testing.T) {
|
||||
groupDn := "cn=TheGroup,ou=groups,dc=owncloud,dc=com"
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ var instanceMapperConfig = config.LDAP{
|
||||
UserIDAttribute: "entryUUID",
|
||||
UserEmailAttribute: "mail",
|
||||
UserNameAttribute: "uid",
|
||||
UserSurnameAttribute: "sn",
|
||||
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
|
||||
|
||||
GroupBaseDN: "ou=groups,dc=test",
|
||||
GroupObjectClass: "groupOfNames",
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/libregraph/idm/server/handler/boltdb"
|
||||
libregraph "github.com/owncloud/libre-graph-api-go"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
|
||||
connldap "github.com/owncloud/reva/v2/pkg/utils/ldap"
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -44,15 +45,28 @@ func init() {
|
||||
idmConfig.UseServerUUID = false // boltdb does not auto-generate entryUUID; client must supply it
|
||||
}
|
||||
|
||||
// restrictedSearchConfig narrows idmConfig's search attributes to name/surname/username.
|
||||
func restrictedSearchConfig() config.LDAP {
|
||||
cfg := idmConfig
|
||||
cfg.UserSearchAttributes = []string{"onPremisesSamAccountName", "displayName", "surname"}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// idmEntry builds a gldap.Entry matching idmConfig attribute names.
|
||||
func idmEntry(uid, uuid string) *gldap.Entry {
|
||||
func idmEntry(uid, uuid, mail string) *gldap.Entry {
|
||||
return idmEntryWithSurname(uid, uuid, mail, uid)
|
||||
}
|
||||
|
||||
// idmEntryWithSurname is idmEntry with an explicit surname, for tests that need it to
|
||||
// differ from the uid (e.g. to isolate surname-only search matches).
|
||||
func idmEntryWithSurname(uid, uuid, mail, surname string) *gldap.Entry {
|
||||
dn := fmt.Sprintf("uid=%s,%s", uid, idmConfig.UserBaseDN)
|
||||
return gldap.NewEntry(dn, map[string][]string{
|
||||
idmConfig.UserNameAttribute: {uid},
|
||||
idmConfig.UserDisplayNameAttribute: {"Display " + uid},
|
||||
idmConfig.UserEmailAttribute: {uid + "@example.com"},
|
||||
idmConfig.UserEmailAttribute: {mail},
|
||||
idmConfig.UserIDAttribute: {uuid},
|
||||
"sn": {uid},
|
||||
"sn": {surname},
|
||||
"givenname": {uid},
|
||||
idmConfig.UserEnabledAttribute: {"TRUE"},
|
||||
idmConfig.UserTypeAttribute: {"Member"},
|
||||
@@ -102,6 +116,11 @@ func seedIDMDB(t *testing.T, dbfile string, entries ...*gldap.Entry) {
|
||||
// newIDMBackend starts the libregraph/idm boltdb LDAP server and returns a wired LDAP identity backend.
|
||||
func newIDMBackend(t *testing.T, entries ...*gldap.Entry) *LDAP {
|
||||
t.Helper()
|
||||
return newIDMBackendWithConfig(t, idmConfig, entries...)
|
||||
}
|
||||
|
||||
func newIDMBackendWithConfig(t *testing.T, cfg config.LDAP, entries ...*gldap.Entry) *LDAP {
|
||||
t.Helper()
|
||||
|
||||
dbfile := filepath.Join(t.TempDir(), "idm.db")
|
||||
seedIDMDB(t, dbfile, entries...)
|
||||
@@ -142,7 +161,7 @@ func newIDMBackend(t *testing.T, entries ...*gldap.Entry) *LDAP {
|
||||
})
|
||||
conn.SetLogger(&lgr.Logger)
|
||||
|
||||
backend, err := NewLDAPBackend(conn, idmConfig, &lgr, "", "")
|
||||
backend, err := NewLDAPBackend(conn, cfg, &lgr, "", "")
|
||||
require.NoError(t, err)
|
||||
return backend
|
||||
}
|
||||
@@ -156,7 +175,7 @@ func odataReq(t *testing.T) *godata.GoDataRequest {
|
||||
|
||||
func TestIntegrationGetUser_HappyPath(t *testing.T) {
|
||||
b := newIDMBackend(t,
|
||||
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001"),
|
||||
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com"),
|
||||
)
|
||||
|
||||
user, err := b.GetUser(context.Background(), "alice", odataReq(t))
|
||||
@@ -168,8 +187,8 @@ func TestIntegrationGetUser_HappyPath(t *testing.T) {
|
||||
|
||||
func TestIntegrationGetUsers_HappyPath(t *testing.T) {
|
||||
b := newIDMBackend(t,
|
||||
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001"),
|
||||
idmEntry("bob", "bbbbbbbb-0000-0000-0000-000000000002"),
|
||||
idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com"),
|
||||
idmEntry("bob", "bbbbbbbb-0000-0000-0000-000000000002", "bob@example.com"),
|
||||
)
|
||||
|
||||
users, err := b.GetUsers(context.Background(), odataReq(t))
|
||||
@@ -183,6 +202,74 @@ func TestIntegrationGetUsers_HappyPath(t *testing.T) {
|
||||
assert.True(t, names["bob"])
|
||||
}
|
||||
|
||||
func TestIntegrationGetUsers_SearchDoesNotMatchEmail(t *testing.T) {
|
||||
// Gunda's mail contains "klaus" but her name, surname, and user-id don't.
|
||||
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
|
||||
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), gunda)
|
||||
|
||||
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
|
||||
require.NoError(t, err)
|
||||
|
||||
users, err := b.GetUsers(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, users, "a search config excluding mail must not match the mail attribute")
|
||||
}
|
||||
|
||||
func TestIntegrationGetUsers_SearchMatchesEmailByDefault(t *testing.T) {
|
||||
// same fixture as TestIntegrationGetUsers_SearchDoesNotMatchEmail, default config instead:
|
||||
// existing deployments must keep matching by mail unless they opt into the narrower attribute list.
|
||||
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
|
||||
b := newIDMBackend(t, gunda)
|
||||
|
||||
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
|
||||
require.NoError(t, err)
|
||||
|
||||
users, err := b.GetUsers(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, users, 1, "the default config must still match the mail attribute")
|
||||
assert.Equal(t, "ruetten", users[0].GetOnPremisesSamAccountName())
|
||||
}
|
||||
|
||||
func TestIntegrationGetUsers_SearchMatchesAllowedAttributes(t *testing.T) {
|
||||
// alice matches via userName/displayName (idmEntry default); carol only via surname.
|
||||
alice := idmEntry("alice", "aaaaaaaa-0000-0000-0000-000000000001", "alice@example.com")
|
||||
carol := idmEntryWithSurname("carol", "eeeeeeee-0000-0000-0000-000000000005", "carol@example.com", "Winterbourne")
|
||||
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), alice, carol)
|
||||
|
||||
aliceReq, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"alice"`}})
|
||||
require.NoError(t, err)
|
||||
aliceUsers, err := b.GetUsers(context.Background(), aliceReq)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, aliceUsers, 1, "search must still match userName/displayName")
|
||||
assert.Equal(t, "alice", aliceUsers[0].GetOnPremisesSamAccountName())
|
||||
|
||||
carolReq, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"Winterbourne"`}})
|
||||
require.NoError(t, err)
|
||||
carolUsers, err := b.GetUsers(context.Background(), carolReq)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, carolUsers, 1, "a search config including surname must match surname")
|
||||
assert.Equal(t, "carol", carolUsers[0].GetOnPremisesSamAccountName())
|
||||
}
|
||||
|
||||
func TestIntegrationGetGroupMembers_SearchDoesNotMatchEmail(t *testing.T) {
|
||||
// Same as TestIntegrationGetUsers_SearchDoesNotMatchEmail, via group-member search instead.
|
||||
gunda := idmEntry("ruetten", "cccccccc-0000-0000-0000-000000000003", "klauspeter.eckel@ruth.info")
|
||||
group := gldap.NewEntry(fmt.Sprintf("cn=%s,%s", "teachers", idmConfig.GroupBaseDN), map[string][]string{
|
||||
"cn": {"teachers"},
|
||||
"entryUUID": {"dddddddd-0000-0000-0000-000000000004"},
|
||||
"member": {gunda.DN},
|
||||
"objectClass": {"groupOfNames"},
|
||||
})
|
||||
b := newIDMBackendWithConfig(t, restrictedSearchConfig(), gunda, group)
|
||||
|
||||
req, err := godata.ParseRequest(context.Background(), "", url.Values{"$search": {`"klaus"`}})
|
||||
require.NoError(t, err)
|
||||
|
||||
members, err := b.GetGroupMembers(context.Background(), "teachers", req)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, members, "a search config excluding mail must not match the mail attribute")
|
||||
}
|
||||
|
||||
func TestIntegrationCreateUser_HappyPath(t *testing.T) {
|
||||
b := newIDMBackend(t) // empty — no pre-seeded users
|
||||
|
||||
@@ -200,8 +287,28 @@ func TestIntegrationCreateUser_HappyPath(t *testing.T) {
|
||||
assert.Equal(t, "charlie@example.com", created.GetMail())
|
||||
}
|
||||
|
||||
func TestIntegrationCreateUser_MirrorsSurnameIntoLiteralSN(t *testing.T) {
|
||||
cfg := idmConfig
|
||||
cfg.UserSurnameAttribute = "customSurname"
|
||||
b := newIDMBackendWithConfig(t, cfg)
|
||||
|
||||
newUser := libregraph.NewUser("Eve", "eve")
|
||||
newUser.SetSurname("Example")
|
||||
_, err := b.CreateUser(context.Background(), *newUser)
|
||||
require.NoError(t, err)
|
||||
|
||||
sr := gldap.NewSearchRequest(cfg.UserBaseDN, gldap.ScopeWholeSubtree, gldap.NeverDerefAliases, 0, 0, false,
|
||||
"(uid=eve)", []string{"sn", "customSurname"}, nil)
|
||||
res, err := b.conn.Search(sr)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, res.Entries, 1)
|
||||
assert.Equal(t, "Example", res.Entries[0].GetEqualFoldAttributeValue("customSurname"))
|
||||
// person's objectClass requires the literal "sn" to be set regardless of configuration
|
||||
assert.Equal(t, "Example", res.Entries[0].GetEqualFoldAttributeValue("sn"))
|
||||
}
|
||||
|
||||
func TestIntegrationDeleteUser_HappyPath(t *testing.T) {
|
||||
entry := idmEntry("dave", "dddddddd-0000-0000-0000-000000000004")
|
||||
entry := idmEntry("dave", "dddddddd-0000-0000-0000-000000000004", "dave@example.com")
|
||||
b := newIDMBackend(t, entry)
|
||||
|
||||
// Confirm user exists first.
|
||||
|
||||
@@ -35,6 +35,8 @@ var lconfig = config.LDAP{
|
||||
UserIDAttribute: "entryUUID",
|
||||
UserEmailAttribute: "mail",
|
||||
UserNameAttribute: "uid",
|
||||
UserSurnameAttribute: "sn",
|
||||
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
|
||||
UserEnabledAttribute: "userEnabledAttribute",
|
||||
UserTypeAttribute: "userTypeAttribute",
|
||||
ExternalIDAttribute: "externalID",
|
||||
@@ -119,6 +121,18 @@ func TestNewLDAPBackend(t *testing.T) {
|
||||
if _, err := NewLDAPBackend(l, lconfig, &logger, "", ""); err != nil {
|
||||
t.Errorf("Should fail with invalid group search scope")
|
||||
}
|
||||
|
||||
tc = lconfig
|
||||
tc.UserSearchAttributes = nil
|
||||
if _, err := NewLDAPBackend(l, tc, &logger, "", ""); err == nil {
|
||||
t.Error("Should fail with no user search attributes configured")
|
||||
}
|
||||
|
||||
tc = lconfig
|
||||
tc.UserSearchAttributes = []string{"notARealAttribute"}
|
||||
if _, err := NewLDAPBackend(l, tc, &logger, "", ""); err != nil {
|
||||
t.Errorf("Should accept an unrecognized name as a literal LDAP attribute: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateUser(t *testing.T) {
|
||||
@@ -327,7 +341,6 @@ func TestGetUsers(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetUsersSearch(t *testing.T) {
|
||||
lm := &mocks.Client{}
|
||||
odataReqDefault, err := godata.ParseRequest(context.Background(), "",
|
||||
url.Values{
|
||||
"$search": []string{"\"term\""},
|
||||
@@ -337,19 +350,38 @@ func TestGetUsersSearch(t *testing.T) {
|
||||
t.Errorf("Expected success got '%s'", err.Error())
|
||||
}
|
||||
|
||||
// only match if the filter contains the search term unquoted
|
||||
lm.On("Search", mock.MatchedBy(
|
||||
func(req *ldap.SearchRequest) bool {
|
||||
return req.Filter == "(&(objectClass=inetOrgPerson)(|(uid=*term*)(mail=*term*)(displayname=*term*)))"
|
||||
})).
|
||||
Return(&ldap.SearchResult{}, nil)
|
||||
b, _ := getMockedBackend(lm, lconfig, &logger)
|
||||
g, err := b.GetUsers(context.Background(), odataReqDefault)
|
||||
if err != nil {
|
||||
t.Errorf("Expected success, got '%s'", err.Error())
|
||||
} else if g == nil || len(g) != 0 {
|
||||
t.Errorf("Expected zero length user slice")
|
||||
assertSearchFilter := func(t *testing.T, cfg config.LDAP, wantFilter string) {
|
||||
lm := &mocks.Client{}
|
||||
// only match if the filter contains the search term unquoted
|
||||
lm.On("Search", mock.MatchedBy(
|
||||
func(req *ldap.SearchRequest) bool {
|
||||
return req.Filter == wantFilter
|
||||
})).
|
||||
Return(&ldap.SearchResult{}, nil)
|
||||
b, _ := getMockedBackend(lm, cfg, &logger)
|
||||
g, err := b.GetUsers(context.Background(), odataReqDefault)
|
||||
if err != nil {
|
||||
t.Errorf("Expected success, got '%s'", err.Error())
|
||||
} else if g == nil || len(g) != 0 {
|
||||
t.Errorf("Expected zero length user slice")
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("default config matches userName, displayName and mail", func(t *testing.T) {
|
||||
assertSearchFilter(t, lconfig, "(&(objectClass=inetOrgPerson)(|(uid=*term*)(displayname=*term*)(mail=*term*)))")
|
||||
})
|
||||
|
||||
t.Run("a config excluding mail matches surname instead", func(t *testing.T) {
|
||||
restrictedConfig := lconfig
|
||||
restrictedConfig.UserSearchAttributes = []string{"onPremisesSamAccountName", "displayName", "surname"}
|
||||
assertSearchFilter(t, restrictedConfig, "(&(objectClass=inetOrgPerson)(|(uid=*term*)(displayname=*term*)(sn=*term*)))")
|
||||
})
|
||||
|
||||
t.Run("a literal '%' in a configured attribute name does not corrupt the filter", func(t *testing.T) {
|
||||
percentConfig := lconfig
|
||||
percentConfig.UserNameAttribute = "uid%"
|
||||
assertSearchFilter(t, percentConfig, "(&(objectClass=inetOrgPerson)(|(uid%=*term*)(displayname=*term*)(mail=*term*)))")
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateUser(t *testing.T) {
|
||||
|
||||
@@ -67,6 +67,8 @@ var _ = Describe("Users changing their own password", func() {
|
||||
WriteEnabled: true,
|
||||
UserDisplayNameAttribute: "displayName",
|
||||
UserNameAttribute: "uid",
|
||||
UserSurnameAttribute: "sn",
|
||||
UserSearchAttributes: []string{"onPremisesSamAccountName", "displayName", "mail"},
|
||||
UserEmailAttribute: "mail",
|
||||
UserIDAttribute: "ownCloudUUID",
|
||||
UserSearchScope: "sub",
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@@ -442,6 +443,11 @@ func setIdentityBackends(options Options, svc *Graph) error {
|
||||
if options.IdentityBackend == nil {
|
||||
switch options.Config.Identity.Backend {
|
||||
case "cs3":
|
||||
// the cs3 backend has no attribute-scoped search filter of its own; this config
|
||||
// only takes effect on the ldap backend
|
||||
if !slices.Contains(options.Config.Identity.LDAP.UserSearchAttributes, "mail") {
|
||||
options.Logger.Warn().Msg("GRAPH_LDAP_USER_SEARCH_ATTRIBUTES excludes mail but has no effect with GRAPH_IDENTITY_BACKEND=cs3; user search may still match by mail")
|
||||
}
|
||||
gatewaySelector, err := pool.GatewaySelector(
|
||||
options.Config.Reva.Address,
|
||||
append(
|
||||
|
||||
@@ -282,6 +282,26 @@ func (g Graph) applyFilterVaultEligible(ctx context.Context, req *godata.GoDataR
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// unlike other filters, vaultEligible applies its own role check below, so it's safe to
|
||||
// look up a cross-instance match here - the GetUsers switch only blocks a cross-instance
|
||||
// lookup when it would bypass that check entirely.
|
||||
if username, instancename := g.parseExternalSearch(req); username != "" && instancename != "" &&
|
||||
g.contextUserHasExternalSharePermission(ctx) {
|
||||
if preciseUser, err := g.identityBackend.GetPreciseUser(ctx, username, instancename, req); err == nil {
|
||||
found := false
|
||||
for _, u := range users {
|
||||
if u.GetId() == preciseUser.GetId() {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
users = append(users, preciseUser)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(users) == 0 {
|
||||
return users, nil
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/graph/mocks"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
|
||||
identitymocks "github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks"
|
||||
service "github.com/owncloud/ocis/v2/services/graph/pkg/service/v0"
|
||||
)
|
||||
@@ -710,8 +711,7 @@ var _ = Describe("Users", func() {
|
||||
}, nil)
|
||||
})
|
||||
|
||||
// None of these reach GetPreciseUser: a filter, a non-matching search, no search at
|
||||
// all, or missing permission each independently keep it from firing.
|
||||
// vaultEligible is excluded here; it does reach GetPreciseUser — see "the vaultEligible filter, with a cross-instance match" below
|
||||
DescribeTable("does not resolve via GetPreciseUser",
|
||||
func(search string, filter string, permissionGranted bool, needsMFA bool) {
|
||||
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
|
||||
@@ -744,8 +744,8 @@ var _ = Describe("Users", func() {
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
},
|
||||
Entry("filter present, even though the search string also matches the cross-instance pattern",
|
||||
`"student@other-instance.example.test"`, "vaultEligible eq true", true, false),
|
||||
Entry("a non-vaultEligible filter is present, even though the search string also matches the cross-instance pattern",
|
||||
`"student@other-instance.example.test"`, "userType eq 'Member'", true, false),
|
||||
Entry("search string doesn't match the cross-instance pattern",
|
||||
`"not-a-cross-instance-string"`, "", true, false),
|
||||
Entry("no $search present at all",
|
||||
@@ -782,6 +782,9 @@ var _ = Describe("Users", func() {
|
||||
ineligible.SetId(otherUser)
|
||||
identityBackend.On("GetUsers", mock.Anything, mock.Anything).
|
||||
Return([]*libregraph.User{eligible, ineligible}, nil)
|
||||
// no cross-instance account behind this reference; GetPreciseUser finds nothing
|
||||
identityBackend.On("GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(nil, identity.ErrNotFound)
|
||||
|
||||
expectRoles()
|
||||
expectAssignments(eligibleUser, []*settingsmsg.UserRoleAssignment{
|
||||
@@ -807,7 +810,61 @@ var _ = Describe("Users", func() {
|
||||
ids = append(ids, u.GetId())
|
||||
}
|
||||
Expect(ids).To(ConsistOf(eligibleUser))
|
||||
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
})
|
||||
|
||||
Describe("the vaultEligible filter, with a cross-instance match", func() {
|
||||
const crossInstanceUser = "cross-instance-user"
|
||||
|
||||
It("includes a cross-instance match that holds the vault-granting role", func() {
|
||||
crossInstance := &libregraph.User{}
|
||||
crossInstance.SetId(crossInstanceUser)
|
||||
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
|
||||
identityBackend.On("GetPreciseUser", mock.Anything, "teacher", "school5", mock.Anything).
|
||||
Return(crossInstance, nil)
|
||||
|
||||
expectRoles()
|
||||
expectAssignments(crossInstanceUser, []*settingsmsg.UserRoleAssignment{
|
||||
{Id: "assignment-ID", AccountUuid: crossInstanceUser, RoleId: vaultRole},
|
||||
}, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet,
|
||||
"/graph/v1.0/users?$search="+url.QueryEscape(`"teacher@school5.example.test"`)+
|
||||
"&$filter="+url.QueryEscape("vaultEligible eq true"), nil)
|
||||
svc.GetUsers(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
data, err := io.ReadAll(rr.Body)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
res := userList{}
|
||||
Expect(json.Unmarshal(data, &res)).To(Succeed())
|
||||
|
||||
Expect(res.Value).To(HaveLen(1))
|
||||
Expect(res.Value[0].GetId()).To(Equal(crossInstanceUser))
|
||||
})
|
||||
|
||||
It("excludes a cross-instance match that lacks the vault-granting role", func() {
|
||||
crossInstance := &libregraph.User{}
|
||||
crossInstance.SetId(crossInstanceUser)
|
||||
identityBackend.On("GetUsers", mock.Anything, mock.Anything).Return([]*libregraph.User{}, nil)
|
||||
identityBackend.On("GetPreciseUser", mock.Anything, "student", "school5", mock.Anything).
|
||||
Return(crossInstance, nil)
|
||||
|
||||
expectRoles()
|
||||
expectAssignments(crossInstanceUser, nil, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet,
|
||||
"/graph/v1.0/users?$search="+url.QueryEscape(`"student@school5.example.test"`)+
|
||||
"&$filter="+url.QueryEscape("vaultEligible eq true"), nil)
|
||||
svc.GetUsers(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
data, err := io.ReadAll(rr.Body)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
res := userList{}
|
||||
Expect(json.Unmarshal(data, &res)).To(Succeed())
|
||||
|
||||
Expect(res.Value).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ type Config struct {
|
||||
|
||||
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"GROUPS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
|
||||
|
||||
Driver string `yaml:"driver" env:"GROUPS_DRIVER" desc:"The driver which should be used by the groups service. Supported values are 'ldap' and 'owncloudsql'." introductionVersion:"pre5.0"`
|
||||
Driver string `yaml:"driver" env:"GROUPS_DRIVER" desc:"The driver which should be used by the groups service. Supported value is 'ldap'." introductionVersion:"pre5.0"`
|
||||
Drivers Drivers `yaml:"drivers"`
|
||||
|
||||
Context context.Context `yaml:"-"`
|
||||
@@ -53,8 +53,7 @@ type GRPCConfig struct {
|
||||
}
|
||||
|
||||
type Drivers struct {
|
||||
LDAP LDAPDriver `yaml:"ldap"`
|
||||
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
|
||||
LDAP LDAPDriver `yaml:"ldap"`
|
||||
|
||||
JSON JSONDriver `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
REST RESTProvider `yaml:"rest,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
@@ -107,19 +106,6 @@ type LDAPGroupSchema struct {
|
||||
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;GROUPS_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
type OwnCloudSQLDriver struct {
|
||||
DBUsername string `yaml:"db_username" env:"GROUPS_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
|
||||
DBPassword string `yaml:"db_password" env:"GROUPS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
|
||||
DBHost string `yaml:"db_host" env:"GROUPS_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
|
||||
DBPort int `yaml:"db_port" env:"GROUPS_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
|
||||
DBName string `yaml:"db_name" env:"GROUPS_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
|
||||
IDP string `yaml:"idp" env:"GROUPS_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
|
||||
Nobody int64 `yaml:"nobody" env:"GROUPS_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
|
||||
JoinUsername bool `yaml:"join_username" env:"GROUPS_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames." introductionVersion:"pre5.0"`
|
||||
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"GROUPS_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user IDs." introductionVersion:"pre5.0"`
|
||||
EnableMedialSearch bool `yaml:"enable_medial_search" env:"GROUPS_OWNCLOUDSQL_ENABLE_MEDIAL_SEARCH" desc:"Allow 'medial search' when searching for users instead of just doing a prefix search. This allows finding 'Alice' when searching for 'lic'." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
type JSONDriver struct {
|
||||
File string
|
||||
}
|
||||
|
||||
@@ -72,18 +72,6 @@ func DefaultConfig() *config.Config {
|
||||
Member: "member",
|
||||
},
|
||||
},
|
||||
OwnCloudSQL: config.OwnCloudSQLDriver{
|
||||
DBUsername: "owncloud",
|
||||
DBPassword: "",
|
||||
DBHost: "mysql",
|
||||
DBPort: 3306,
|
||||
DBName: "owncloud",
|
||||
IDP: "https://localhost:9200",
|
||||
Nobody: 90,
|
||||
JoinUsername: false,
|
||||
JoinOwnCloudUUID: false,
|
||||
EnableMedialSearch: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,6 +251,11 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
rolesClient := settingssvc.NewRoleService("com.owncloud.api.settings", cfg.GrpcClient)
|
||||
policiesProviderClient := policiessvc.NewPoliciesProviderService("com.owncloud.api.policies", cfg.GrpcClient)
|
||||
|
||||
guestRoleMapping, err := userroles.GuestRoleMapping(cfg)
|
||||
if err != nil {
|
||||
logger.Fatal().Err(err).Msg("Invalid guest role mapping")
|
||||
}
|
||||
|
||||
var roleAssigner userroles.UserRoleAssigner
|
||||
switch cfg.RoleAssignment.Driver {
|
||||
case "default":
|
||||
@@ -264,6 +269,7 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
userroles.WithLogger(logger),
|
||||
userroles.WithRolesClaim(cfg.RoleAssignment.OIDCRoleMapper.RoleClaim),
|
||||
userroles.WithRoleMapping(cfg.RoleAssignment.OIDCRoleMapper.RolesMap),
|
||||
userroles.WithGuestRoleMapping(guestRoleMapping),
|
||||
userroles.WithRevaGatewaySelector(gatewaySelector),
|
||||
userroles.WithServiceAccount(cfg.ServiceAccount),
|
||||
)
|
||||
|
||||
@@ -259,10 +259,11 @@ type ClaimSpaceManagement struct {
|
||||
|
||||
// MultiInstanceConfig holds configuration for multi-instance-ocis
|
||||
type MultiInstanceConfig struct {
|
||||
Enabled bool `yaml:"enabled" env:"OCIS_MULTI_INSTANCE_ENABLED" desc:"Enable multiple instances of Infinite Scale." introductionVersion:"8.0.0"`
|
||||
InstanceID string `yaml:"instanceid" env:"OCIS_MULTI_INSTANCE_INSTANCEID" desc:"The unique id of this instance" introductionVersion:"8.0.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable." introductionVersion:"8.1.0"`
|
||||
MemberClaim string `yaml:"member_claim" env:"OCIS_MULTI_INSTANCE_MEMBER_CLAIM" desc:"The claim name for the 'memberOf' property" introductionVersion:"8.0.0"`
|
||||
GuestClaim string `yaml:"guest_claim" env:"OCIS_MULTI_INSTANCE_GUEST_CLAIM" desc:"The claim name for the 'guestOf' property" introductionVersion:"8.0.0"`
|
||||
GuestRole string `yaml:"guest_role" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE" desc:"The role that should be assigned to a guest user" introductionVersion:"8.0.0"`
|
||||
Enabled bool `yaml:"enabled" env:"OCIS_MULTI_INSTANCE_ENABLED" desc:"Enable multiple instances of Infinite Scale." introductionVersion:"8.0.0"`
|
||||
InstanceID string `yaml:"instanceid" env:"OCIS_MULTI_INSTANCE_INSTANCEID" desc:"The unique id of this instance" introductionVersion:"8.0.0"`
|
||||
MasterID string `yaml:"master_id" env:"OCIS_MULTI_INSTANCE_MASTER_ID" desc:"The master ID that grants access to all instances. Users with this ID in their memberOf or guestOf claims can access any instance. Leave empty to disable." introductionVersion:"8.1.0"`
|
||||
MemberClaim string `yaml:"member_claim" env:"OCIS_MULTI_INSTANCE_MEMBER_CLAIM" desc:"The claim name for the 'memberOf' property" introductionVersion:"8.0.0"`
|
||||
GuestClaim string `yaml:"guest_claim" env:"OCIS_MULTI_INSTANCE_GUEST_CLAIM" desc:"The claim name for the 'guestOf' property" introductionVersion:"8.0.0"`
|
||||
GuestRole string `yaml:"guest_role" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE" desc:"The role that should be assigned to a guest user" introductionVersion:"8.0.0"`
|
||||
GuestRoleMapping []string `yaml:"guest_role_mapping" env:"OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING" desc:"(Optional) Mapping of PROXY_ROLE_ASSIGNMENT_OIDC_CLAIM values to the role a guest gets instead of OCIS_MULTI_INSTANCE_GUEST_ROLE. Example: 'spaceadmin:user-light-vault'. A claim value is an exact string or a regular expression that must match the full claim value, the same as the claim_value of the role mapping. Escape regex metacharacters such as '.' in an exact string. The first match wins. Role names must not contain a colon. Only applies to the 'oidc' role assignment driver." introductionVersion:"9.0.0"`
|
||||
}
|
||||
@@ -3,7 +3,9 @@ package userroles
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -13,6 +15,7 @@ import (
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
|
||||
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
|
||||
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"go-micro.dev/v4/metadata"
|
||||
@@ -100,12 +103,21 @@ func matchesClaimMapping(mappingValue string, claimRoles map[string]struct{}) bo
|
||||
func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *cs3user.User, claims map[string]interface{}, overwriteRole string) (*cs3user.User, error) {
|
||||
userID := user.GetId().GetOpaqueId()
|
||||
logger := ra.logger.SubloggerWithRequestID(ctx).With().Str("userid", userID).Logger()
|
||||
roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx)
|
||||
roleNamesToRoleIDs, err := ra.roleNamesToRoleIDs(ctx, roleCacheTTL)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("Error mapping role names to role ids")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the account resolver passes the guest role as overwriteRole for multi-instance guests
|
||||
if overwriteRole != "" {
|
||||
overwriteRole, roleNamesToRoleIDs, err = ra.guestRoleName(ctx, claims, overwriteRole, roleNamesToRoleIDs)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("Error mapping guest role")
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
roleIDFromClaim := roleNamesToRoleIDs[overwriteRole]
|
||||
if overwriteRole == "" {
|
||||
claimRoles, err := extractRoles(ra.rolesClaim, claims)
|
||||
@@ -174,7 +186,7 @@ func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *c
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO: check if it's ctx or newctx
|
||||
// TODO: check if it's ctx or newctx
|
||||
canCreateDrives, err := utils.CheckPermission(revactx.ContextSetUser(ctx, user), "Drives.Create", client)
|
||||
if err != nil {
|
||||
// The permission could not be determined. Fail closed: leave the personal
|
||||
@@ -205,6 +217,95 @@ func (ra oidcRoleAssigner) UpdateUserRoleAssignment(ctx context.Context, user *c
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// GuestRoleMapping reads the 'claimvalue:rolename' pairs of OCIS_MULTI_INSTANCE_GUEST_ROLE_MAPPING.
|
||||
// A pair is split at its last colon, so the claim value may contain colons but the role name must not.
|
||||
// Roles created through the settings service can't contain a colon, their names are restricted to
|
||||
// letters, digits, '-' and '_'.
|
||||
func GuestRoleMapping(cfg *config.Config) ([]config.RoleMapping, error) {
|
||||
pairs := cfg.MultiInstance.GuestRoleMapping
|
||||
if len(pairs) > 0 && cfg.RoleAssignment.Driver != "oidc" {
|
||||
return nil, fmt.Errorf("the guest role mapping requires the 'oidc' role assignment driver, not '%s'", cfg.RoleAssignment.Driver)
|
||||
}
|
||||
// the role assigner only applies the mapping to users that get the guest role
|
||||
if len(pairs) > 0 && cfg.MultiInstance.GuestRole == "" {
|
||||
return nil, errors.New("the guest role mapping requires OCIS_MULTI_INSTANCE_GUEST_ROLE")
|
||||
}
|
||||
|
||||
mappings := make([]config.RoleMapping, 0, len(pairs))
|
||||
for _, pair := range pairs {
|
||||
i := strings.LastIndex(pair, ":")
|
||||
// the env var parser trims list elements, the yaml parser does not
|
||||
claimValue, roleName := "", ""
|
||||
if i >= 0 {
|
||||
claimValue, roleName = strings.TrimSpace(pair[:i]), strings.TrimSpace(pair[i+1:])
|
||||
}
|
||||
if claimValue == "" || roleName == "" {
|
||||
return nil, fmt.Errorf("invalid guest role mapping '%s', expected 'claimvalue:rolename'", pair)
|
||||
}
|
||||
mappings = append(mappings, config.RoleMapping{ClaimValue: claimValue, RoleName: roleName})
|
||||
}
|
||||
return mappings, nil
|
||||
}
|
||||
|
||||
// guestRoleName returns the role name of a multi-instance guest and the role name to role id map
|
||||
// that knows this role. A role that the cached map does not know can be a new role, so
|
||||
// guestRoleName reads the roles again one time. An unknown role is an error: do not assign an
|
||||
// empty role id.
|
||||
func (ra oidcRoleAssigner) guestRoleName(ctx context.Context, claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, map[string]string, error) {
|
||||
resolve := func(roleNamesToRoleIDs map[string]string) (string, error) {
|
||||
roleName := guestRole
|
||||
if len(ra.guestMapping) > 0 {
|
||||
var err error
|
||||
if roleName, err = ra.mapGuestRole(claims, guestRole, roleNamesToRoleIDs); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if _, ok := roleNamesToRoleIDs[roleName]; !ok {
|
||||
return "", fmt.Errorf("unknown role '%s'", roleName)
|
||||
}
|
||||
return roleName, nil
|
||||
}
|
||||
|
||||
roleName, err := resolve(roleNamesToRoleIDs)
|
||||
if err == nil {
|
||||
return roleName, roleNamesToRoleIDs, nil
|
||||
}
|
||||
// the minimum age limits the reads for a role that does not exist
|
||||
roleNamesToRoleIDs, rerr := ra.roleNamesToRoleIDs(ctx, roleCacheMinAge)
|
||||
if rerr != nil {
|
||||
return "", nil, rerr
|
||||
}
|
||||
roleName, err = resolve(roleNamesToRoleIDs)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return roleName, roleNamesToRoleIDs, nil
|
||||
}
|
||||
|
||||
// mapGuestRole returns the role of the first guest role mapping that matches a value of the
|
||||
// user's roles claim, or guestRole when nothing matches. A mapping to a role that does not exist
|
||||
// is an error: it can only be a misconfiguration, and falling back to guestRole could give the
|
||||
// guest more permissions than the mapped role was meant to.
|
||||
func (ra oidcRoleAssigner) mapGuestRole(claims map[string]interface{}, guestRole string, roleNamesToRoleIDs map[string]string) (string, error) {
|
||||
claimRoles, err := extractRoles(ra.rolesClaim, claims)
|
||||
if err != nil || len(claimRoles) == 0 {
|
||||
// a guest without roles claim is valid, log at debug level to help find a wrong claim name
|
||||
ra.logger.Debug().Err(err).Str("claim", ra.rolesClaim).Msg("no roles in claim, the guest keeps the guest role")
|
||||
return guestRole, nil
|
||||
}
|
||||
|
||||
for _, mapping := range ra.guestMapping {
|
||||
if !matchesClaimMapping(mapping.ClaimValue, claimRoles) {
|
||||
continue
|
||||
}
|
||||
if _, ok := roleNamesToRoleIDs[mapping.RoleName]; !ok {
|
||||
return "", fmt.Errorf("guest role mapping '%s' points to the unknown role '%s'", mapping.ClaimValue, mapping.RoleName)
|
||||
}
|
||||
return mapping.RoleName, nil
|
||||
}
|
||||
return guestRole, nil
|
||||
}
|
||||
|
||||
// ApplyUserRole it looks up the user's role in the settings service and adds it
|
||||
// user's opaque data
|
||||
func (ra oidcRoleAssigner) ApplyUserRole(ctx context.Context, user *cs3user.User) (*cs3user.User, error) {
|
||||
@@ -242,11 +343,19 @@ type roleNameToIDCache struct {
|
||||
|
||||
var roleNameToID roleNameToIDCache
|
||||
|
||||
func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]string, error) {
|
||||
cacheTTL := 5 * time.Minute
|
||||
const (
|
||||
// roleCacheTTL is the maximum age of the cached role name to role id map
|
||||
roleCacheTTL = 5 * time.Minute
|
||||
// roleCacheMinAge is the age that the cached map must have before a read for an unknown role
|
||||
roleCacheMinAge = 30 * time.Second
|
||||
)
|
||||
|
||||
// roleNamesToRoleIDs returns the cached role name to role id map. When the map is older than
|
||||
// maxAge, roleNamesToRoleIDs reads the roles from the settings service.
|
||||
func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context, maxAge time.Duration) (map[string]string, error) {
|
||||
roleNameToID.lock.RLock()
|
||||
|
||||
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL {
|
||||
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge {
|
||||
defer roleNameToID.lock.RUnlock()
|
||||
return roleNameToID.roleNameToID, nil
|
||||
}
|
||||
@@ -258,7 +367,7 @@ func (ra oidcRoleAssigner) roleNamesToRoleIDs(ctx context.Context) (map[string]s
|
||||
defer roleNameToID.lock.Unlock()
|
||||
|
||||
// check again, another goroutine might have updated while we "upgraded" the lock
|
||||
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < cacheTTL {
|
||||
if !roleNameToID.lastRead.IsZero() && time.Since(roleNameToID.lastRead) < maxAge {
|
||||
return roleNameToID.roleNameToID, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package userroles
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -270,3 +272,377 @@ func TestUpdateUserRoleAssignmentFailsClosedOnInconclusivePermission(t *testing.
|
||||
return req.GetRoleId() == oldRoleID
|
||||
}), mock.Anything)
|
||||
}
|
||||
|
||||
func TestMapGuestRole(t *testing.T) {
|
||||
roleIDs := map[string]string{"user-light": "user-light-id", "user-light-vault": "user-light-vault-id"}
|
||||
spaceAdminMapping := []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mapping []config.RoleMapping
|
||||
roleIDs map[string]string
|
||||
claims map[string]interface{}
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "spaceadmin gets the mapped role",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: roleIDs,
|
||||
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
|
||||
want: "user-light-vault",
|
||||
},
|
||||
{
|
||||
name: "spaceadmin with more claim values gets the mapped role",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: roleIDs,
|
||||
claims: map[string]interface{}{"roles": []interface{}{"user", "spaceadmin"}},
|
||||
want: "user-light-vault",
|
||||
},
|
||||
{
|
||||
name: "user keeps the guest role",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: roleIDs,
|
||||
claims: map[string]interface{}{"roles": []interface{}{"user"}},
|
||||
want: "user-light",
|
||||
},
|
||||
{
|
||||
name: "guest without roles claim keeps the guest role",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: roleIDs,
|
||||
claims: map[string]interface{}{"sub": "someone"},
|
||||
want: "user-light",
|
||||
},
|
||||
{
|
||||
name: "mapping to an unknown role is an error",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: map[string]string{"user-light": "user-light-id"},
|
||||
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "unknown role of a non-matching mapping is no error",
|
||||
mapping: spaceAdminMapping,
|
||||
roleIDs: map[string]string{"user-light": "user-light-id"},
|
||||
claims: map[string]interface{}{"roles": []interface{}{"user"}},
|
||||
want: "user-light",
|
||||
},
|
||||
{
|
||||
name: "first matching mapping wins",
|
||||
mapping: []config.RoleMapping{
|
||||
{ClaimValue: "spaceadmin", RoleName: "user-light-vault"},
|
||||
{ClaimValue: ".*", RoleName: "user-light"},
|
||||
},
|
||||
roleIDs: roleIDs,
|
||||
claims: map[string]interface{}{"roles": []interface{}{"spaceadmin"}},
|
||||
want: "user-light-vault",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ra := oidcRoleAssigner{Options: Options{rolesClaim: "roles", guestMapping: tt.mapping}}
|
||||
got, err := ra.mapGuestRole(tt.claims, "user-light", tt.roleIDs)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected an error, got role %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("got role %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateUserRoleAssignmentMapsGuestRole verifies that a guest who already holds the
|
||||
// guest role is moved to the role the guest role mapping picks for their claims, which is
|
||||
// how guests invited before the mapping was configured get the new role on their next login.
|
||||
func TestUpdateUserRoleAssignmentMapsGuestRole(t *testing.T) {
|
||||
const (
|
||||
guestRoleID = "user-light-id"
|
||||
vaultRoleID = "user-light-vault-id"
|
||||
userOpaqueID = "user-1"
|
||||
)
|
||||
|
||||
// reset the package-global role-name cache so this test is deterministic
|
||||
roleNameToID.lock.Lock()
|
||||
roleNameToID.roleNameToID = nil
|
||||
roleNameToID.lastRead = time.Time{}
|
||||
roleNameToID.lock.Unlock()
|
||||
|
||||
gatewayClient := &cs3mocks.GatewayAPIClient{}
|
||||
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
|
||||
"GatewaySelector",
|
||||
"com.owncloud.api.gateway",
|
||||
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
|
||||
return gatewayClient
|
||||
},
|
||||
)
|
||||
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
|
||||
|
||||
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
|
||||
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
|
||||
Token: "service-token",
|
||||
}, nil)
|
||||
// like the guest role, the mapped role can't create drives, so the assigner disables
|
||||
// the (here non-existent) personal space
|
||||
gatewayClient.On("CheckPermission", mock.Anything, mock.Anything).Return(&permissions.CheckPermissionResponse{
|
||||
Status: &rpc.Status{Code: rpc.Code_CODE_PERMISSION_DENIED},
|
||||
}, nil)
|
||||
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&storageprovider.ListStorageSpacesResponse{
|
||||
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
|
||||
}, nil)
|
||||
|
||||
roleService := &graphmocks.RoleService{}
|
||||
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{
|
||||
{Id: guestRoleID, Name: "user-light"},
|
||||
{Id: vaultRoleID, Name: "user-light-vault"},
|
||||
}}, nil)
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListRoleAssignmentsResponse{Assignments: []*settingsmsg.UserRoleAssignment{
|
||||
{Id: "guest-assignment-id", AccountUuid: userOpaqueID, RoleId: guestRoleID},
|
||||
}}, nil)
|
||||
roleService.On("AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.AssignRoleToUserResponse{Assignment: &settingsmsg.UserRoleAssignment{
|
||||
Id: "vault-assignment-id",
|
||||
AccountUuid: userOpaqueID,
|
||||
RoleId: vaultRoleID,
|
||||
}}, nil)
|
||||
|
||||
ra := oidcRoleAssigner{Options: Options{
|
||||
logger: log.NopLogger(),
|
||||
gatewaySelector: gatewaySelector,
|
||||
roleService: roleService,
|
||||
rolesClaim: "roles",
|
||||
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
|
||||
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
|
||||
}}
|
||||
|
||||
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: userOpaqueID}}
|
||||
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
|
||||
|
||||
if _, err := ra.UpdateUserRoleAssignment(context.Background(), user, claims, "user-light"); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
roleService.AssertCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
|
||||
return req.GetAccountUuid() == userOpaqueID && req.GetRoleId() == vaultRoleID
|
||||
}), mock.Anything)
|
||||
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.MatchedBy(func(req *settingssvc.AssignRoleToUserRequest) bool {
|
||||
return req.GetRoleId() == guestRoleID
|
||||
}), mock.Anything)
|
||||
}
|
||||
|
||||
// TestUpdateUserRoleAssignmentFailsOnUnknownGuestRole verifies that a guest role mapping that
|
||||
// points to a role which does not exist fails the role assignment instead of silently assigning
|
||||
// the guest role.
|
||||
func TestUpdateUserRoleAssignmentFailsOnUnknownGuestRole(t *testing.T) {
|
||||
// reset the package-global role-name cache so this test is deterministic
|
||||
roleNameToID.lock.Lock()
|
||||
roleNameToID.roleNameToID = nil
|
||||
roleNameToID.lastRead = time.Time{}
|
||||
roleNameToID.lock.Unlock()
|
||||
|
||||
gatewayClient := &cs3mocks.GatewayAPIClient{}
|
||||
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
|
||||
"GatewaySelector",
|
||||
"com.owncloud.api.gateway",
|
||||
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
|
||||
return gatewayClient
|
||||
},
|
||||
)
|
||||
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
|
||||
|
||||
// listing the roles needs a service account context
|
||||
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
|
||||
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
|
||||
Token: "service-token",
|
||||
}, nil)
|
||||
|
||||
roleService := &graphmocks.RoleService{}
|
||||
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{{Id: "user-light-id", Name: "user-light"}}}, nil)
|
||||
|
||||
ra := oidcRoleAssigner{Options: Options{
|
||||
logger: log.NopLogger(),
|
||||
gatewaySelector: gatewaySelector,
|
||||
roleService: roleService,
|
||||
rolesClaim: "roles",
|
||||
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
|
||||
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
|
||||
}}
|
||||
|
||||
user := &cs3user.User{Id: &cs3user.UserId{OpaqueId: "user-1"}}
|
||||
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
|
||||
|
||||
_, err := ra.UpdateUserRoleAssignment(context.Background(), user, claims, "user-light")
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown role 'user-light-vault'") {
|
||||
t.Fatalf("expected an error for the guest role mapping to an unknown role, got %v", err)
|
||||
}
|
||||
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
|
||||
|
||||
// a guest that no mapping matches gets the guest role, which must exist too
|
||||
claims = map[string]interface{}{"roles": []interface{}{"user"}}
|
||||
_, err = ra.UpdateUserRoleAssignment(context.Background(), user, claims, "no-such-guest-role")
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown role 'no-such-guest-role'") {
|
||||
t.Fatalf("expected an error for an unknown guest role, got %v", err)
|
||||
}
|
||||
roleService.AssertNotCalled(t, "AssignRoleToUser", mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
|
||||
func TestGuestRoleMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
driver string
|
||||
// noGuestRole leaves OCIS_MULTI_INSTANCE_GUEST_ROLE empty
|
||||
noGuestRole bool
|
||||
pairs []string
|
||||
want []config.RoleMapping
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "empty",
|
||||
driver: "default",
|
||||
pairs: nil,
|
||||
want: []config.RoleMapping{},
|
||||
},
|
||||
{
|
||||
name: "pairs keep their order",
|
||||
driver: "oidc",
|
||||
pairs: []string{"spaceadmin:user-light-vault", "admin:guest-admin"},
|
||||
want: []config.RoleMapping{
|
||||
{ClaimValue: "spaceadmin", RoleName: "user-light-vault"},
|
||||
{ClaimValue: "admin", RoleName: "guest-admin"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "claim value may contain colons",
|
||||
driver: "oidc",
|
||||
pairs: []string{"urn:ocis:spaceadmin:user-light-vault"},
|
||||
want: []config.RoleMapping{{ClaimValue: "urn:ocis:spaceadmin", RoleName: "user-light-vault"}},
|
||||
},
|
||||
{
|
||||
name: "spaces around the claim value and the role name are trimmed",
|
||||
driver: "oidc",
|
||||
pairs: []string{" spaceadmin : user-light-vault "},
|
||||
want: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
|
||||
},
|
||||
{name: "requires the oidc driver", driver: "default", pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true},
|
||||
{name: "requires a guest role", driver: "oidc", noGuestRole: true, pairs: []string{"spaceadmin:user-light-vault"}, wantErr: true},
|
||||
{name: "missing colon", driver: "oidc", pairs: []string{"spaceadmin"}, wantErr: true},
|
||||
{name: "missing claim value", driver: "oidc", pairs: []string{":user-light-vault"}, wantErr: true},
|
||||
{name: "missing role name", driver: "oidc", pairs: []string{"spaceadmin:"}, wantErr: true},
|
||||
{name: "blank claim value", driver: "oidc", pairs: []string{" :user-light-vault"}, wantErr: true},
|
||||
{name: "blank role name", driver: "oidc", pairs: []string{"spaceadmin: "}, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
guestRole := "user-light"
|
||||
if tt.noGuestRole {
|
||||
guestRole = ""
|
||||
}
|
||||
cfg := &config.Config{
|
||||
RoleAssignment: config.RoleAssignment{Driver: tt.driver},
|
||||
MultiInstance: config.MultiInstanceConfig{GuestRole: guestRole, GuestRoleMapping: tt.pairs},
|
||||
}
|
||||
got, err := GuestRoleMapping(cfg)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("expected an error for %v", tt.pairs)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("got %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGuestRoleNameRefreshesRoles verifies that a role which the cached role map does not know
|
||||
// makes the assigner read the roles again, so a new role works before the cache TTL ends. The
|
||||
// assigner reads the roles again only when the cached map is older than roleCacheMinAge.
|
||||
func TestGuestRoleNameRefreshesRoles(t *testing.T) {
|
||||
gatewayClient := &cs3mocks.GatewayAPIClient{}
|
||||
gatewaySelector := pool.GetSelector[gateway.GatewayAPIClient](
|
||||
"GatewaySelector",
|
||||
"com.owncloud.api.gateway",
|
||||
func(cc grpc.ClientConnInterface) gateway.GatewayAPIClient {
|
||||
return gatewayClient
|
||||
},
|
||||
)
|
||||
defer pool.RemoveSelector("GatewaySelector" + "com.owncloud.api.gateway")
|
||||
|
||||
// listing the roles needs a service account context
|
||||
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
|
||||
Status: &rpc.Status{Code: rpc.Code_CODE_OK},
|
||||
Token: "service-token",
|
||||
}, nil)
|
||||
|
||||
claims := map[string]interface{}{"roles": []interface{}{"spaceadmin"}}
|
||||
cached := map[string]string{"user-light": "user-light-id"}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cacheAge time.Duration
|
||||
wantRole string
|
||||
wantErr bool
|
||||
wantReads int
|
||||
}{
|
||||
{name: "an old cache is read again", cacheAge: time.Minute, wantRole: "user-light-vault", wantReads: 1},
|
||||
{name: "a fresh cache is not read again", cacheAge: 0, wantErr: true, wantReads: 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
roleNameToID.lock.Lock()
|
||||
roleNameToID.roleNameToID = cached
|
||||
roleNameToID.lastRead = time.Now().Add(-tt.cacheAge)
|
||||
roleNameToID.lock.Unlock()
|
||||
|
||||
roleService := &graphmocks.RoleService{}
|
||||
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(
|
||||
&settingssvc.ListBundlesResponse{Bundles: []*settingsmsg.Bundle{
|
||||
{Id: "user-light-id", Name: "user-light"},
|
||||
{Id: "user-light-vault-id", Name: "user-light-vault"},
|
||||
}}, nil)
|
||||
|
||||
ra := oidcRoleAssigner{Options: Options{
|
||||
logger: log.NopLogger(),
|
||||
gatewaySelector: gatewaySelector,
|
||||
roleService: roleService,
|
||||
rolesClaim: "roles",
|
||||
guestMapping: []config.RoleMapping{{ClaimValue: "spaceadmin", RoleName: "user-light-vault"}},
|
||||
serviceAccount: config.ServiceAccount{ServiceAccountID: "service-account", ServiceAccountSecret: "secret"},
|
||||
}}
|
||||
|
||||
got, roleIDs, err := ra.guestRoleName(context.Background(), claims, "user-light", cached)
|
||||
roleService.AssertNumberOfCalls(t, "ListRoles", tt.wantReads)
|
||||
if tt.wantErr {
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown role 'user-light-vault'") {
|
||||
t.Fatalf("expected an unknown role error, got role %q and error %v", got, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.wantRole || roleIDs[got] != "user-light-vault-id" {
|
||||
t.Fatalf("got role %q with id %q, want %q", got, roleIDs[got], tt.wantRole)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// reset the package-global role-name cache for the other tests
|
||||
roleNameToID.lock.Lock()
|
||||
roleNameToID.roleNameToID = nil
|
||||
roleNameToID.lastRead = time.Time{}
|
||||
roleNameToID.lock.Unlock()
|
||||
}
|
||||
@@ -31,6 +31,7 @@ type Options struct {
|
||||
roleService settingssvc.RoleService
|
||||
rolesClaim string
|
||||
roleMapping []config.RoleMapping
|
||||
guestMapping []config.RoleMapping
|
||||
serviceAccount config.ServiceAccount
|
||||
logger log.Logger
|
||||
}
|
||||
@@ -66,6 +67,13 @@ func WithRoleMapping(roleMap []config.RoleMapping) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithGuestRoleMapping configures the map of ocis role names to claim values for multi-instance guests
|
||||
func WithGuestRoleMapping(roleMap []config.RoleMapping) Option {
|
||||
return func(o *Options) {
|
||||
o.guestMapping = roleMap
|
||||
}
|
||||
}
|
||||
|
||||
// WithRevaGatewaySelector set the gatewaySelector option
|
||||
func WithRevaGatewaySelector(selectable pool.Selectable[gateway.GatewayAPIClient]) Option {
|
||||
return func(o *Options) {
|
||||
|
||||
@@ -21,7 +21,7 @@ type Config struct {
|
||||
|
||||
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"SHARING_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
|
||||
|
||||
UserSharingDriver string `yaml:"user_sharing_driver" env:"SHARING_USER_DRIVER" desc:"Driver to be used to persist shares. Supported values are 'jsoncs3', 'json', 'cs3' (deprecated) and 'owncloudsql'." introductionVersion:"pre5.0"`
|
||||
UserSharingDriver string `yaml:"user_sharing_driver" env:"SHARING_USER_DRIVER" desc:"Driver to be used to persist shares. Supported values are 'jsoncs3', 'json' and 'cs3' (deprecated)." introductionVersion:"pre5.0"`
|
||||
UserSharingDrivers UserSharingDrivers `yaml:"user_sharing_drivers"`
|
||||
PublicSharingDriver string `yaml:"public_sharing_driver" env:"SHARING_PUBLIC_DRIVER" desc:"Driver to be used to persist public shares. Supported values are 'jsoncs3', 'json' and 'cs3' (deprecated)." introductionVersion:"pre5.0"`
|
||||
PublicSharingDrivers PublicSharingDrivers `yaml:"public_sharing_drivers"`
|
||||
@@ -62,10 +62,9 @@ type GRPCConfig struct {
|
||||
}
|
||||
|
||||
type UserSharingDrivers struct {
|
||||
JSONCS3 UserSharingJSONCS3Driver `yaml:"jsoncs3"`
|
||||
JSON UserSharingJSONDriver `yaml:"json"`
|
||||
CS3 UserSharingCS3Driver `yaml:"cs3"`
|
||||
OwnCloudSQL UserSharingOwnCloudSQLDriver `yaml:"owncloudsql"`
|
||||
JSONCS3 UserSharingJSONCS3Driver `yaml:"jsoncs3"`
|
||||
JSON UserSharingJSONDriver `yaml:"json"`
|
||||
CS3 UserSharingCS3Driver `yaml:"cs3"`
|
||||
|
||||
SQL UserSharingSQLDriver `yaml:"sql,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
}
|
||||
@@ -86,15 +85,6 @@ type UserSharingSQLDriver struct {
|
||||
UserStorageMountID string `yaml:"user_storage_mount_id"`
|
||||
}
|
||||
|
||||
type UserSharingOwnCloudSQLDriver struct {
|
||||
DBUsername string `yaml:"db_username" env:"SHARING_USER_OWNCLOUDSQL_DB_USERNAME" desc:"Username for the database." introductionVersion:"pre5.0"`
|
||||
DBPassword string `yaml:"db_password" env:"SHARING_USER_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database." introductionVersion:"pre5.0"`
|
||||
DBHost string `yaml:"db_host" env:"SHARING_USER_OWNCLOUDSQL_DB_HOST" desc:"Hostname or IP of the database server." introductionVersion:"pre5.0"`
|
||||
DBPort int `yaml:"db_port" env:"SHARING_USER_OWNCLOUDSQL_DB_PORT" desc:"Port that the database server is listening on." introductionVersion:"pre5.0"`
|
||||
DBName string `yaml:"db_name" env:"SHARING_USER_OWNCLOUDSQL_DB_NAME" desc:"Name of the database to be used." introductionVersion:"pre5.0"`
|
||||
UserStorageMountID string `yaml:"user_storage_mount_id" env:"SHARING_USER_OWNCLOUDSQL_USER_STORAGE_MOUNT_ID" desc:"Mount ID of the ownCloudSQL users storage for mapping ownCloud 10 shares." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
type UserSharingCS3Driver struct {
|
||||
ProviderAddr string `yaml:"provider_addr" env:"SHARING_USER_CS3_PROVIDER_ADDR" desc:"GRPC address of the STORAGE-SYSTEM service." introductionVersion:"pre5.0"`
|
||||
SystemUserID string `yaml:"system_user_id" env:"OCIS_SYSTEM_USER_ID;SHARING_USER_CS3_SYSTEM_USER_ID" desc:"ID of the oCIS STORAGE-SYSTEM system user. Admins need to set the ID for the STORAGE-SYSTEM system user in this config option which is then used to reference the user. Any reasonable long string is possible, preferably this would be an UUIDv4 format." introductionVersion:"pre5.0"`
|
||||
|
||||
@@ -49,12 +49,6 @@ func DefaultConfig() *config.Config {
|
||||
SystemUserIDP: "internal",
|
||||
MaxConcurrency: 1,
|
||||
},
|
||||
OwnCloudSQL: config.UserSharingOwnCloudSQLDriver{
|
||||
DBUsername: "owncloud",
|
||||
DBHost: "mysql",
|
||||
DBPort: 3306,
|
||||
DBName: "owncloud",
|
||||
},
|
||||
},
|
||||
PublicSharingDriver: "jsoncs3",
|
||||
PublicSharingDrivers: config.PublicSharingDrivers{
|
||||
@@ -69,7 +63,6 @@ func DefaultConfig() *config.Config {
|
||||
ProviderAddr: "com.owncloud.api.storage-system", // system storage
|
||||
SystemUserIDP: "internal",
|
||||
},
|
||||
// TODO implement and add owncloudsql publicshare driver
|
||||
},
|
||||
Events: config.Events{
|
||||
Addr: "127.0.0.1:9233",
|
||||
|
||||
@@ -54,15 +54,6 @@ func SharingConfigFromStruct(cfg *config.Config, logger log.Logger) (map[string]
|
||||
"enable_expired_shares_cleanup": cfg.UserSharingDrivers.SQL.EnableExpiredSharesCleanup,
|
||||
"janitor_run_interval": cfg.UserSharingDrivers.SQL.JanitorRunInterval,
|
||||
},
|
||||
"owncloudsql": map[string]interface{}{
|
||||
"gateway_addr": cfg.Reva.Address,
|
||||
"storage_mount_id": cfg.UserSharingDrivers.OwnCloudSQL.UserStorageMountID,
|
||||
"db_username": cfg.UserSharingDrivers.OwnCloudSQL.DBUsername,
|
||||
"db_password": cfg.UserSharingDrivers.OwnCloudSQL.DBPassword,
|
||||
"db_host": cfg.UserSharingDrivers.OwnCloudSQL.DBHost,
|
||||
"db_port": cfg.UserSharingDrivers.OwnCloudSQL.DBPort,
|
||||
"db_name": cfg.UserSharingDrivers.OwnCloudSQL.DBName,
|
||||
},
|
||||
"cs3": map[string]interface{}{
|
||||
"gateway_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
|
||||
"provider_addr": cfg.UserSharingDrivers.CS3.ProviderAddr,
|
||||
|
||||
@@ -24,7 +24,7 @@ type Config struct {
|
||||
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"STORAGE_USERS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
|
||||
GracefulShutdownTimeout int `yaml:"graceful_shutdown_timeout" env:"STORAGE_USERS_GRACEFUL_SHUTDOWN_TIMEOUT" desc:"The number of seconds to wait for the 'storage-users' service to shutdown cleanly before exiting with an error that gets logged. Note: This setting is only applicable when running the 'storage-users' service as a standalone service. See the text description for more details." introductionVersion:"pre5.0"`
|
||||
|
||||
Driver string `yaml:"driver" env:"STORAGE_USERS_DRIVER" desc:"The storage driver which should be used by the service. Defaults to 'ocis', Supported values are: 'ocis', 's3ng' and 'owncloudsql' (deprecated). The 'ocis' driver stores all data (blob and meta data) in an POSIX compliant volume. The 's3ng' driver stores metadata in a POSIX compliant volume and uploads blobs to the s3 bucket." introductionVersion:"pre5.0"`
|
||||
Driver string `yaml:"driver" env:"STORAGE_USERS_DRIVER" desc:"The storage driver which should be used by the service. Defaults to 'ocis', Supported values are: 'ocis' and 's3ng'. The 'ocis' driver stores all data (blob and meta data) in an POSIX compliant volume. The 's3ng' driver stores metadata in a POSIX compliant volume and uploads blobs to the s3 bucket." introductionVersion:"pre5.0"`
|
||||
Drivers Drivers `yaml:"drivers"`
|
||||
DataServerURL string `yaml:"data_server_url" env:"STORAGE_USERS_DATA_SERVER_URL" desc:"URL of the data server, needs to be reachable by the data gateway provided by the frontend service or the user if directly exposed." introductionVersion:"pre5.0"`
|
||||
DataGatewayURL string `yaml:"data_gateway_url" env:"STORAGE_USERS_DATA_GATEWAY_URL" desc:"URL of the data gateway server" introductionVersion:"pre5.0"`
|
||||
@@ -100,10 +100,9 @@ type CORS struct {
|
||||
|
||||
// Drivers combine all storage driver configurations
|
||||
type Drivers struct {
|
||||
OCIS OCISDriver `yaml:"ocis"`
|
||||
S3NG S3NGDriver `yaml:"s3ng"`
|
||||
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
|
||||
Posix PosixDriver `yaml:"posix"`
|
||||
OCIS OCISDriver `yaml:"ocis"`
|
||||
S3NG S3NGDriver `yaml:"s3ng"`
|
||||
Posix PosixDriver `yaml:"posix"`
|
||||
|
||||
S3 S3Driver `yaml:",omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
EOS EOSDriver `yaml:",omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
@@ -176,22 +175,6 @@ type S3NGDriver struct {
|
||||
DisableVersioning bool `yaml:"disable_versioning" env:"OCIS_DISABLE_VERSIONING" desc:"Disables versioning of files. When set to true, new uploads with the same filename will overwrite existing files instead of creating a new version." introductionVersion:"7.0.0"`
|
||||
}
|
||||
|
||||
// OwnCloudSQLDriver is the storage driver configuration when using 'owncloudsql' storage driver
|
||||
type OwnCloudSQLDriver struct {
|
||||
// Root is the absolute path to the location of the data
|
||||
Root string `yaml:"root" env:"STORAGE_USERS_OWNCLOUDSQL_DATADIR" desc:"The directory where the filesystem storage will store SQL migration data. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/storage/owncloud." introductionVersion:"pre5.0"`
|
||||
// ShareFolder defines the name of the folder jailing all shares
|
||||
ShareFolder string `yaml:"share_folder" env:"STORAGE_USERS_OWNCLOUDSQL_SHARE_FOLDER" desc:"Name of the folder jailing all shares." introductionVersion:"pre5.0"`
|
||||
UserLayout string `yaml:"user_layout" env:"STORAGE_USERS_OWNCLOUDSQL_LAYOUT" desc:"Path layout to use to navigate into a users folder in an owncloud data directory" introductionVersion:"pre5.0"`
|
||||
UploadInfoDir string `yaml:"upload_info_dir" env:"STORAGE_USERS_OWNCLOUDSQL_UPLOADINFO_DIR" desc:"The directory where the filesystem will store uploads temporarily. If not defined, the root directory derives from $OCIS_BASE_DATA_PATH/storage/uploadinfo." introductionVersion:"pre5.0"`
|
||||
DBUsername string `yaml:"db_username" env:"STORAGE_USERS_OWNCLOUDSQL_DB_USERNAME" desc:"Username for the database." introductionVersion:"pre5.0"`
|
||||
DBPassword string `yaml:"db_password" env:"STORAGE_USERS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database." introductionVersion:"pre5.0"`
|
||||
DBHost string `yaml:"db_host" env:"STORAGE_USERS_OWNCLOUDSQL_DB_HOST" desc:"Hostname or IP of the database server." introductionVersion:"pre5.0"`
|
||||
DBPort int `yaml:"db_port" env:"STORAGE_USERS_OWNCLOUDSQL_DB_PORT" desc:"Port that the database server is listening on." introductionVersion:"pre5.0"`
|
||||
DBName string `yaml:"db_name" env:"STORAGE_USERS_OWNCLOUDSQL_DB_NAME" desc:"Name of the database to be used." introductionVersion:"pre5.0"`
|
||||
UsersProviderEndpoint string `yaml:"users_provider_endpoint" env:"STORAGE_USERS_OWNCLOUDSQL_USERS_PROVIDER_ENDPOINT" desc:"Endpoint of the users provider." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
// PosixDriver is the storage driver configuration when using 'posix' storage driver
|
||||
type PosixDriver struct {
|
||||
// Root is the absolute path to the location of the data
|
||||
|
||||
@@ -94,18 +94,6 @@ func DefaultConfig() *config.Config {
|
||||
GracefulShutdownTimeout: 30,
|
||||
Driver: "ocis",
|
||||
Drivers: config.Drivers{
|
||||
OwnCloudSQL: config.OwnCloudSQLDriver{
|
||||
Root: filepath.Join(defaults.BaseDataPath(), "storage", "owncloud"),
|
||||
ShareFolder: "/Shares",
|
||||
UserLayout: "{{.Username}}",
|
||||
UploadInfoDir: filepath.Join(defaults.BaseDataPath(), "storage", "uploadinfo"),
|
||||
DBUsername: "owncloud",
|
||||
DBPassword: "owncloud",
|
||||
DBHost: "",
|
||||
DBPort: 3306,
|
||||
DBName: "owncloud",
|
||||
UsersProviderEndpoint: "com.owncloud.api.users",
|
||||
},
|
||||
S3NG: config.S3NGDriver{
|
||||
Propagator: "sync",
|
||||
Root: filepath.Join(defaults.BaseDataPath(), "storage", "users"),
|
||||
|
||||
@@ -137,29 +137,6 @@ func LocalHome(cfg *config.Config) map[string]interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// OwnCloudSQL is the config mapping for the OwnCloudSQL storage driver
|
||||
func OwnCloudSQL(cfg *config.Config) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"datadirectory": cfg.Drivers.OwnCloudSQL.Root,
|
||||
"upload_info_dir": cfg.Drivers.OwnCloudSQL.UploadInfoDir,
|
||||
"share_folder": cfg.Drivers.OwnCloudSQL.ShareFolder,
|
||||
"user_layout": cfg.Drivers.OwnCloudSQL.UserLayout,
|
||||
"enable_home": false,
|
||||
"dbusername": cfg.Drivers.OwnCloudSQL.DBUsername,
|
||||
"dbpassword": cfg.Drivers.OwnCloudSQL.DBPassword,
|
||||
"dbhost": cfg.Drivers.OwnCloudSQL.DBHost,
|
||||
"dbport": cfg.Drivers.OwnCloudSQL.DBPort,
|
||||
"dbname": cfg.Drivers.OwnCloudSQL.DBName,
|
||||
"userprovidersvc": cfg.Drivers.OwnCloudSQL.UsersProviderEndpoint,
|
||||
"tokens": map[string]interface{}{
|
||||
"download_endpoint": cfg.DataServerURL,
|
||||
"datagateway_endpoint": cfg.DataGatewayURL,
|
||||
"transfer_shared_secret": cfg.Commons.TransferSecret,
|
||||
"transfer_expires": cfg.TransferExpires,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Ocis is the config mapping for the Ocis storage driver
|
||||
func Ocis(cfg *config.Config) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
|
||||
@@ -5,31 +5,29 @@ import "github.com/owncloud/ocis/v2/services/storage-users/pkg/config"
|
||||
// StorageProviderDrivers are the drivers for the storage provider
|
||||
func StorageProviderDrivers(cfg *config.Config) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"eos": EOS(cfg),
|
||||
"eoshome": EOSHome(cfg),
|
||||
"eosgrpc": EOSGRPC(cfg),
|
||||
"local": Local(cfg),
|
||||
"localhome": LocalHome(cfg),
|
||||
"owncloudsql": OwnCloudSQL(cfg),
|
||||
"ocis": OcisNoEvents(cfg),
|
||||
"s3": S3(cfg),
|
||||
"s3ng": S3NGNoEvents(cfg),
|
||||
"posix": Posix(cfg, true),
|
||||
"eos": EOS(cfg),
|
||||
"eoshome": EOSHome(cfg),
|
||||
"eosgrpc": EOSGRPC(cfg),
|
||||
"local": Local(cfg),
|
||||
"localhome": LocalHome(cfg),
|
||||
"ocis": OcisNoEvents(cfg),
|
||||
"s3": S3(cfg),
|
||||
"s3ng": S3NGNoEvents(cfg),
|
||||
"posix": Posix(cfg, true),
|
||||
}
|
||||
}
|
||||
|
||||
// DataProviderDrivers are the drivers for the storage provider
|
||||
func DataProviderDrivers(cfg *config.Config) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"eos": EOS(cfg),
|
||||
"eoshome": EOSHome(cfg),
|
||||
"eosgrpc": EOSGRPC(cfg),
|
||||
"local": Local(cfg),
|
||||
"localhome": LocalHome(cfg),
|
||||
"owncloudsql": OwnCloudSQL(cfg),
|
||||
"ocis": Ocis(cfg),
|
||||
"s3": S3(cfg),
|
||||
"s3ng": S3NG(cfg),
|
||||
"posix": Posix(cfg, false),
|
||||
"eos": EOS(cfg),
|
||||
"eoshome": EOSHome(cfg),
|
||||
"eosgrpc": EOSGRPC(cfg),
|
||||
"local": Local(cfg),
|
||||
"localhome": LocalHome(cfg),
|
||||
"ocis": Ocis(cfg),
|
||||
"s3": S3(cfg),
|
||||
"s3ng": S3NG(cfg),
|
||||
"posix": Posix(cfg, false),
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ type Config struct {
|
||||
|
||||
SkipUserGroupsInToken bool `yaml:"skip_user_groups_in_token" env:"USERS_SKIP_USER_GROUPS_IN_TOKEN" desc:"Disables the loading of user's group memberships from the reva access token." introductionVersion:"pre5.0"`
|
||||
|
||||
Driver string `yaml:"driver" env:"USERS_DRIVER" desc:"The driver which should be used by the users service. Supported values are 'ldap' and 'owncloudsql'." introductionVersion:"pre5.0"`
|
||||
Driver string `yaml:"driver" env:"USERS_DRIVER" desc:"The driver which should be used by the users service. Supported value is 'ldap'." introductionVersion:"pre5.0"`
|
||||
Drivers Drivers `yaml:"drivers"`
|
||||
|
||||
Context context.Context `yaml:"-"`
|
||||
@@ -52,8 +52,7 @@ type GRPCConfig struct {
|
||||
}
|
||||
|
||||
type Drivers struct {
|
||||
LDAP LDAPDriver `yaml:"ldap"`
|
||||
OwnCloudSQL OwnCloudSQLDriver `yaml:"owncloudsql"`
|
||||
LDAP LDAPDriver `yaml:"ldap"`
|
||||
|
||||
JSON JSONDriver `yaml:"json,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
REST RESTProvider `yaml:"rest,omitempty"` // not supported by the oCIS product, therefore not part of docs
|
||||
@@ -113,18 +112,6 @@ type LDAPGroupSchema struct {
|
||||
Member string `yaml:"member" env:"OCIS_LDAP_GROUP_SCHEMA_MEMBER;USERS_LDAP_GROUP_SCHEMA_MEMBER" desc:"LDAP Attribute that is used for group members." introductionVersion:"pre5.0"`
|
||||
}
|
||||
|
||||
type OwnCloudSQLDriver struct {
|
||||
DBUsername string `yaml:"db_username" env:"USERS_OWNCLOUDSQL_DB_USERNAME" desc:"Database user to use for authenticating with the owncloud database." introductionVersion:"pre5.0"`
|
||||
DBPassword string `yaml:"db_password" env:"USERS_OWNCLOUDSQL_DB_PASSWORD" desc:"Password for the database user." introductionVersion:"pre5.0"`
|
||||
DBHost string `yaml:"db_host" env:"USERS_OWNCLOUDSQL_DB_HOST" desc:"Hostname of the database server." introductionVersion:"pre5.0"`
|
||||
DBPort int `yaml:"db_port" env:"USERS_OWNCLOUDSQL_DB_PORT" desc:"Network port to use for the database connection." introductionVersion:"pre5.0"`
|
||||
DBName string `yaml:"db_name" env:"USERS_OWNCLOUDSQL_DB_NAME" desc:"Name of the owncloud database." introductionVersion:"pre5.0"`
|
||||
IDP string `yaml:"idp" env:"USERS_OWNCLOUDSQL_IDP" desc:"The identity provider value to set in the userids of the CS3 user objects for users returned by this user provider." introductionVersion:"pre5.0"`
|
||||
Nobody int64 `yaml:"nobody" env:"USERS_OWNCLOUDSQL_NOBODY" desc:"Fallback number if no numeric UID and GID properties are provided." introductionVersion:"pre5.0"`
|
||||
JoinUsername bool `yaml:"join_username" env:"USERS_OWNCLOUDSQL_JOIN_USERNAME" desc:"Join the user properties table to read usernames" introductionVersion:"pre5.0"`
|
||||
JoinOwnCloudUUID bool `yaml:"join_owncloud_uuid" env:"USERS_OWNCLOUDSQL_JOIN_OWNCLOUD_UUID" desc:"Join the user properties table to read user IDs." introductionVersion:"pre5.0"`
|
||||
EnableMedialSearch bool `yaml:"enable_medial_search" env:"USERS_OWNCLOUDSQL_ENABLE_MEDIAL_SEARCH" desc:"Allow 'medial search' when searching for users instead of just doing a prefix search. This allows finding 'Alice' when searching for 'lic'." introductionVersion:"pre5.0"`
|
||||
}
|
||||
type RESTProvider struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
|
||||
@@ -77,18 +77,6 @@ func DefaultConfig() *config.Config {
|
||||
},
|
||||
},
|
||||
JSON: config.JSONDriver{},
|
||||
OwnCloudSQL: config.OwnCloudSQLDriver{
|
||||
DBUsername: "owncloud",
|
||||
DBPassword: "secret",
|
||||
DBHost: "mysql",
|
||||
DBPort: 3306,
|
||||
DBName: "owncloud",
|
||||
IDP: "https://localhost:9200",
|
||||
Nobody: 90,
|
||||
JoinUsername: false,
|
||||
JoinOwnCloudUUID: false,
|
||||
EnableMedialSearch: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,18 +30,6 @@ func UsersConfigFromStruct(cfg *config.Config) map[string]interface{} {
|
||||
"users": cfg.Drivers.JSON.File,
|
||||
},
|
||||
"ldap": ldapConfigFromString(cfg.Drivers.LDAP),
|
||||
"owncloudsql": map[string]interface{}{
|
||||
"dbusername": cfg.Drivers.OwnCloudSQL.DBUsername,
|
||||
"dbpassword": cfg.Drivers.OwnCloudSQL.DBPassword,
|
||||
"dbhost": cfg.Drivers.OwnCloudSQL.DBHost,
|
||||
"dbport": cfg.Drivers.OwnCloudSQL.DBPort,
|
||||
"dbname": cfg.Drivers.OwnCloudSQL.DBName,
|
||||
"idp": cfg.Drivers.OwnCloudSQL.IDP,
|
||||
"nobody": cfg.Drivers.OwnCloudSQL.Nobody,
|
||||
"join_username": cfg.Drivers.OwnCloudSQL.JoinUsername,
|
||||
"join_ownclouduuid": cfg.Drivers.OwnCloudSQL.JoinOwnCloudUUID,
|
||||
"enable_medial_search": cfg.Drivers.OwnCloudSQL.EnableMedialSearch,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -356,6 +356,26 @@ Feature: edit/search user including email
|
||||
"""
|
||||
|
||||
|
||||
Scenario: non-admin user's e-mail search term matches nobody when search is restricted to name, surname and username
|
||||
Given the config "GRAPH_LDAP_USER_SEARCH_ATTRIBUTES" has been set to "onPremisesSamAccountName,displayName,surname" for "graph" service
|
||||
When user "Brian" searches for user "%22alice@example.org%22" using Graph API
|
||||
Then the HTTP status code should be "200"
|
||||
And the JSON data of the response should match
|
||||
"""
|
||||
{
|
||||
"type": "object",
|
||||
"required": ["value"],
|
||||
"properties": {
|
||||
"value": {
|
||||
"type": "array",
|
||||
"minItems": 0,
|
||||
"maxItems": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
Scenario: non-admin user searches for a disabled users
|
||||
Given the user "Admin" has disabled user "Alice"
|
||||
When user "Brian" searches for user "alice" using Graph API
|
||||
|
||||
@@ -135,13 +135,32 @@ def main() -> int:
|
||||
subprocess.run(["pnpm", "exec", "playwright", "install", "--with-deps", "chromium"],
|
||||
cwd=web_dir, check=True)
|
||||
|
||||
vault_storage_needed = (
|
||||
os.environ.get("VAULT_STORAGE_NEEDED", "").lower() == "true"
|
||||
or os.environ.get("VAULT_MODE", "").lower() == "true"
|
||||
)
|
||||
|
||||
if os.environ.get("K8S", "").lower() == "true":
|
||||
# oCIS is already running as a Helm-deployed k8s cluster (see
|
||||
# .github/workflows/k8s.yml) -- unlike the flow below, there's no local
|
||||
# binary to build, init, or start. Just confirm it's up and point
|
||||
# Playwright straight at it.
|
||||
ocis_url = os.environ["TEST_SERVER_URL"]
|
||||
wait_for(lambda: ocis_healthy(ocis_url), 120, "ocis")
|
||||
if vault_storage_needed:
|
||||
wait_for(
|
||||
lambda: subprocess.run(
|
||||
["curl", "-sf", "http://localhost:19205/readyz"], capture_output=True
|
||||
).returncode == 0,
|
||||
120,
|
||||
"ocis proxy",
|
||||
)
|
||||
else:
|
||||
keycloak_enabled = os.environ.get("KEYCLOAK", "").lower() == "true"
|
||||
wait_for(
|
||||
lambda: ocis_healthy(ocis_url, use_basic_auth=not keycloak_enabled),
|
||||
120,
|
||||
"ocis",
|
||||
)
|
||||
print("ocis ready.")
|
||||
|
||||
playwright_env = {
|
||||
@@ -172,7 +191,6 @@ def main() -> int:
|
||||
oidc_iframe_needed = os.environ.get("OIDC_IFRAME_NEEDED", "").lower() == "true"
|
||||
collaboration_needed = os.environ.get("COLLABORATION_NEEDED", "").lower() == "true"
|
||||
federated_needed = os.environ.get("FEDERATED_NEEDED", "").lower() == "true"
|
||||
vault_storage_needed = os.environ.get("VAULT_STORAGE_NEEDED", "").lower() == "true"
|
||||
# MFA mode runs ocis behind keycloak with TOTP enforced
|
||||
keycloak_needed = keycloak_needed or mfa_needed or vault_storage_needed
|
||||
|
||||
|
||||
@@ -27,6 +27,11 @@ prepare-charts:
|
||||
bash setup.sh $(CHART_REPO)
|
||||
kubectl create namespace $(DOMAIN) || true
|
||||
kubectl create configmap -n $(DOMAIN) ocis-fonts-ttf --from-file=../ci/NotoSans.ttf || true
|
||||
kubectl create secret generic -n $(DOMAIN) ocis-admin-user \
|
||||
--from-literal=user-id=ddc2004c-0977-11eb-9d3f-a793888cd0f8 --from-literal=password=admin || true
|
||||
sed 's|https://ocis-server:9200|https://$(DOMAIN)|g' ../ci/ocis-config.json > $(CHART_REPO)/web-config.json
|
||||
kubectl create configmap -n $(DOMAIN) ocis-web-config \
|
||||
--from-file=web-config.json=$(CHART_REPO)/web-config.json || true
|
||||
kubectl create configmap -n $(DOMAIN) ocis-translations \
|
||||
--from-file=de_LC_MESSAGES_notifications.po=../translations/de/LC_MESSAGES/notifications.po \
|
||||
--from-file=es_LC_MESSAGES_notifications.po=../translations/es/LC_MESSAGES/notifications.po || true
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
- name: ocis-translations
|
||||
mountPath: /etc/ocis/translations
|
||||
{{- end -}}
|
||||
{{- if and (eq .appName "web") (not .Values.features.vault.enabled) }}
|
||||
- name: ocis-web-config
|
||||
mountPath: /etc/ocis-web-ui
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "ocis.extraVolumes" -}}
|
||||
@@ -37,23 +41,20 @@
|
||||
- key: es_LC_MESSAGES_notifications.po
|
||||
path: es/LC_MESSAGES/notifications.po
|
||||
{{- end -}}
|
||||
{{- if and (eq .appName "web") (not .Values.features.vault.enabled) }}
|
||||
- name: ocis-web-config
|
||||
configMap:
|
||||
name: ocis-web-config
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "ocis.extraEnvs" -}}
|
||||
- name: OCIS_LOG_FILE
|
||||
value: /logs/ocis.log
|
||||
{{- if eq .appName "idm" }}
|
||||
- name: IDM_ADMIN_PASSWORD
|
||||
value: admin
|
||||
{{- end -}}
|
||||
{{- if eq .appName "proxy" }}
|
||||
- name: PROXY_ENABLE_BASIC_AUTH
|
||||
value: "true"
|
||||
{{- end -}}
|
||||
{{- if eq .appName "audit" }}
|
||||
- name: AUDIT_LOG_TO_CONSOLE
|
||||
value: "false"
|
||||
{{- end -}}
|
||||
{{- if eq .appName "thumbnails" }}
|
||||
- name: THUMBNAILS_TXT_FONTMAP_FILE
|
||||
value: /etc/ocis/fontsMap.json
|
||||
@@ -68,6 +69,10 @@
|
||||
- name: OCIS_TRANSLATION_PATH
|
||||
value: /etc/ocis/translations
|
||||
{{- end -}}
|
||||
{{- if and (eq .appName "web") (not .Values.features.vault.enabled) }}
|
||||
- name: WEB_UI_CONFIG_FILE
|
||||
value: /etc/ocis-web-ui/web-config.json
|
||||
{{- end -}}
|
||||
{{- if .Values.features.vault.enabled }}
|
||||
{{- if eq .appName "proxy" }}
|
||||
- name: OCIS_ENABLE_VAULT_MODE
|
||||
|
||||
@@ -192,8 +192,23 @@ services:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
web:
|
||||
additionalInitContainers:
|
||||
- name: init-web-themes-dir
|
||||
image: busybox:stable
|
||||
imagePullPolicy: IfNotPresent
|
||||
securityContext:
|
||||
runAsNonRoot: false
|
||||
runAsUser: 0
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- mkdir -p /var/lib/ocis/web/assets/themes && chown -R 1000:1000 /var/lib/ocis/web/assets/themes
|
||||
volumeMounts:
|
||||
- name: web-data
|
||||
mountPath: /var/lib/ocis
|
||||
persistence:
|
||||
enabled: true
|
||||
chownInitContainer: true
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
antivirus:
|
||||
@@ -210,4 +225,5 @@ services:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
secretRefs:
|
||||
adminUserSecretRef: ocis-admin-user
|
||||
notificationsSmtpSecretRef: notifications-smtp-secret
|
||||
+18
-8
@@ -21,6 +21,7 @@ import (
|
||||
"crypto/aes"
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
@@ -195,11 +196,11 @@ func (ctx rsaEncrypterVerifier) encryptKey(cek []byte, alg KeyAlgorithm) (recipi
|
||||
func (ctx rsaEncrypterVerifier) encrypt(cek []byte, alg KeyAlgorithm) ([]byte, error) {
|
||||
switch alg {
|
||||
case RSA1_5:
|
||||
return rsa.EncryptPKCS1v15(RandReader, ctx.publicKey, cek)
|
||||
return rsa.EncryptPKCS1v15(randReader, ctx.publicKey, cek)
|
||||
case RSA_OAEP:
|
||||
return rsa.EncryptOAEP(sha1.New(), RandReader, ctx.publicKey, cek, []byte{})
|
||||
return rsa.EncryptOAEP(sha1.New(), randReader, ctx.publicKey, cek, []byte{})
|
||||
case RSA_OAEP_256:
|
||||
return rsa.EncryptOAEP(sha256.New(), RandReader, ctx.publicKey, cek, []byte{})
|
||||
return rsa.EncryptOAEP(sha256.New(), randReader, ctx.publicKey, cek, []byte{})
|
||||
}
|
||||
|
||||
return nil, ErrUnsupportedAlgorithm
|
||||
@@ -288,9 +289,9 @@ func (ctx rsaDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm
|
||||
// TODO(https://github.com/go-jose/go-jose/issues/40): As of go1.20, the
|
||||
// random parameter is legacy and ignored, and it can be nil.
|
||||
// https://cs.opensource.google/go/go/+/refs/tags/go1.20:src/crypto/rsa/pkcs1v15.go;l=263;bpv=0;bpt=1
|
||||
out, err = rsa.SignPKCS1v15(RandReader, ctx.privateKey, hash, hashed)
|
||||
out, err = rsa.SignPKCS1v15(randReader, ctx.privateKey, hash, hashed)
|
||||
case PS256, PS384, PS512:
|
||||
out, err = rsa.SignPSS(RandReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
|
||||
out, err = rsa.SignPSS(randReader, ctx.privateKey, hash, hashed, &rsa.PSSOptions{
|
||||
SaltLength: rsa.PSSSaltLengthEqualsHash,
|
||||
})
|
||||
}
|
||||
@@ -391,7 +392,7 @@ func (ctx ecKeyGenerator) keySize() int {
|
||||
|
||||
// Get a content encryption key for ECDH-ES
|
||||
func (ctx ecKeyGenerator) genKey() ([]byte, rawHeader, error) {
|
||||
priv, err := ecdsa.GenerateKey(ctx.publicKey.Curve, RandReader)
|
||||
priv, err := ecdsa.GenerateKey(ctx.publicKey.Curve, randReader)
|
||||
if err != nil {
|
||||
return nil, rawHeader{}, err
|
||||
}
|
||||
@@ -483,7 +484,7 @@ func (ctx edDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm)
|
||||
return Signature{}, ErrUnsupportedAlgorithm
|
||||
}
|
||||
|
||||
sig, err := ctx.privateKey.Sign(RandReader, payload, crypto.Hash(0))
|
||||
sig, err := ctx.privateKey.Sign(randReader, payload, crypto.Hash(0))
|
||||
if err != nil {
|
||||
return Signature{}, err
|
||||
}
|
||||
@@ -533,7 +534,7 @@ func (ctx ecDecrypterSigner) signPayload(payload []byte, alg SignatureAlgorithm)
|
||||
_, _ = hasher.Write(payload)
|
||||
hashed := hasher.Sum(nil)
|
||||
|
||||
r, s, err := ecdsa.Sign(RandReader, ctx.privateKey, hashed)
|
||||
r, s, err := ecdsa.Sign(randReader, ctx.privateKey, hashed)
|
||||
if err != nil {
|
||||
return Signature{}, err
|
||||
}
|
||||
@@ -571,12 +572,21 @@ func (ctx ecEncrypterVerifier) verifyPayload(payload []byte, signature []byte, a
|
||||
case ES256:
|
||||
keySize = 32
|
||||
hash = crypto.SHA256
|
||||
if ctx.publicKey.Curve != elliptic.P256() {
|
||||
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
|
||||
}
|
||||
case ES384:
|
||||
keySize = 48
|
||||
hash = crypto.SHA384
|
||||
if ctx.publicKey.Curve != elliptic.P384() {
|
||||
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
|
||||
}
|
||||
case ES512:
|
||||
keySize = 66
|
||||
hash = crypto.SHA512
|
||||
if ctx.publicKey.Curve != elliptic.P521() {
|
||||
return fmt.Errorf("go-jose/go-jose: signature uses different algorithm than public key")
|
||||
}
|
||||
default:
|
||||
return ErrUnsupportedAlgorithm
|
||||
}
|
||||
|
||||
+5
-1
@@ -51,6 +51,8 @@ func NewCBCHMAC(key []byte, newBlockCipher func([]byte) (cipher.Block, error)) (
|
||||
hash = sha512.New384
|
||||
case 32:
|
||||
hash = sha512.New
|
||||
default:
|
||||
return nil, errors.New("go-jose/go-jose: invalid key size for CBC-HMAC")
|
||||
}
|
||||
|
||||
return &cbcAEAD{
|
||||
@@ -176,7 +178,9 @@ func padBuffer(buffer []byte, blockSize int) []byte {
|
||||
|
||||
// Remove padding
|
||||
func unpadBuffer(buffer []byte, blockSize int) ([]byte, error) {
|
||||
if len(buffer)%blockSize != 0 {
|
||||
// A padded buffer can't be empty because an empty input is padded with
|
||||
// `blockSize` bytes, resulting in a non-empty ciphertext.
|
||||
if len(buffer) == 0 || len(buffer)%blockSize != 0 {
|
||||
return nil, errors.New("go-jose/go-jose: invalid padding")
|
||||
}
|
||||
|
||||
|
||||
+72
-31
@@ -258,6 +258,10 @@ func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
|
||||
}
|
||||
|
||||
recipientInfo, err = makeJWERecipient(recipient.Algorithm, recipient.Key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if recipient.KeyID != "" {
|
||||
recipientInfo.keyID = recipient.KeyID
|
||||
}
|
||||
@@ -270,10 +274,8 @@ func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
ctx.recipients = append(ctx.recipients, recipientInfo)
|
||||
}
|
||||
return err
|
||||
ctx.recipients = append(ctx.recipients, recipientInfo)
|
||||
return nil
|
||||
}
|
||||
|
||||
func makeJWERecipient(alg KeyAlgorithm, encryptionKey interface{}) (recipientKeyInfo, error) {
|
||||
@@ -426,6 +428,13 @@ func (ctx *genericEncrypter) Options() EncrypterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
func validateContentEncryptionKeySize(cek []byte, cipher contentCipher) error {
|
||||
if len(cek) != cipher.keySize() {
|
||||
return ErrInvalidKeySize
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Decrypt and validate the object and return the plaintext. This
|
||||
// function does not support multi-recipient. If you desire multi-recipient
|
||||
// decryption use DecryptMulti instead.
|
||||
@@ -490,21 +499,23 @@ func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error)
|
||||
recipientHeaders := obj.mergedHeaders(&recipient)
|
||||
|
||||
cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
|
||||
if err == nil {
|
||||
// Found a valid CEK -- let's try to decrypt.
|
||||
plaintext, err = cipher.decrypt(cek, authData, parts)
|
||||
if err != nil {
|
||||
return nil, ErrCryptoFailure
|
||||
}
|
||||
|
||||
if plaintext == nil {
|
||||
err = validateContentEncryptionKeySize(cek, cipher)
|
||||
if err != nil {
|
||||
return nil, ErrCryptoFailure
|
||||
}
|
||||
|
||||
// The "zip" header parameter may only be present in the protected header.
|
||||
if comp := obj.protected.getCompression(); comp != "" {
|
||||
plaintext, err = decompress(comp, plaintext)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
|
||||
}
|
||||
// Found a valid CEK -- let's try to decrypt.
|
||||
plaintext, err = cipher.decrypt(cek, authData, parts)
|
||||
if err != nil {
|
||||
return nil, ErrCryptoFailure
|
||||
}
|
||||
|
||||
plaintext, err = obj.decompress(plaintext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
@@ -559,31 +570,42 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade
|
||||
var plaintext []byte
|
||||
var headers rawHeader
|
||||
|
||||
if len(obj.recipients) == 0 {
|
||||
return -1, Header{}, nil, errors.New("go-jose/go-jose: no recipients")
|
||||
}
|
||||
|
||||
// Loop sets `err` in the function scope; don't shadow it.
|
||||
for i, recipient := range obj.recipients {
|
||||
recipientHeaders := obj.mergedHeaders(&recipient)
|
||||
|
||||
cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
|
||||
if err == nil {
|
||||
// Found a valid CEK -- let's try to decrypt.
|
||||
plaintext, err = cipher.decrypt(cek, authData, parts)
|
||||
if err == nil {
|
||||
index = i
|
||||
headers = recipientHeaders
|
||||
break
|
||||
}
|
||||
var cek []byte
|
||||
cek, err = decrypter.decryptKey(recipientHeaders, &recipient, generator)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
err = validateContentEncryptionKeySize(cek, cipher)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Found a valid CEK -- let's try to decrypt.
|
||||
plaintext, err = cipher.decrypt(cek, authData, parts)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
index = i
|
||||
headers = recipientHeaders
|
||||
break
|
||||
}
|
||||
|
||||
if plaintext == nil {
|
||||
if err != nil {
|
||||
return -1, Header{}, nil, ErrCryptoFailure
|
||||
}
|
||||
|
||||
// The "zip" header parameter may only be present in the protected header.
|
||||
if comp := obj.protected.getCompression(); comp != "" {
|
||||
plaintext, err = decompress(comp, plaintext)
|
||||
if err != nil {
|
||||
return -1, Header{}, nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
|
||||
}
|
||||
plaintext, err = obj.decompress(plaintext)
|
||||
if err != nil {
|
||||
return -1, Header{}, nil, err
|
||||
}
|
||||
|
||||
sanitized, err := headers.sanitized()
|
||||
@@ -593,3 +615,22 @@ func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Heade
|
||||
|
||||
return index, sanitized, plaintext, err
|
||||
}
|
||||
|
||||
// decompress decompresses plaintext using the protected "zip" header, if present.
|
||||
// It returns plaintext unchanged when there is no protected header or "zip" value.
|
||||
func (obj JSONWebEncryption) decompress(plaintext []byte) ([]byte, error) {
|
||||
if obj.protected == nil {
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
comp := obj.protected.getCompression()
|
||||
if comp == "" {
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
plaintext, err := decompress(comp, plaintext)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: failed to decompress plaintext: %v", err)
|
||||
}
|
||||
return plaintext, nil
|
||||
}
|
||||
+13
-6
@@ -140,6 +140,10 @@ const (
|
||||
parseArrayValue // parsing array value
|
||||
)
|
||||
|
||||
// This limits the max nesting depth to prevent stack overflow.
|
||||
// This is permitted by https://tools.ietf.org/html/rfc7159#section-9
|
||||
const maxNestingDepth = 10000
|
||||
|
||||
// reset prepares the scanner for use.
|
||||
// It must be called before calling s.step.
|
||||
func (s *scanner) reset() {
|
||||
@@ -170,8 +174,13 @@ func (s *scanner) eof() int {
|
||||
}
|
||||
|
||||
// pushParseState pushes a new parse state p onto the parse stack.
|
||||
func (s *scanner) pushParseState(p int) {
|
||||
s.parseState = append(s.parseState, p)
|
||||
// an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned.
|
||||
func (s *scanner) pushParseState(c byte, newParseState int, successState int) int {
|
||||
s.parseState = append(s.parseState, newParseState)
|
||||
if len(s.parseState) <= maxNestingDepth {
|
||||
return successState
|
||||
}
|
||||
return s.error(c, "exceeded max depth")
|
||||
}
|
||||
|
||||
// popParseState pops a parse state (already obtained) off the stack
|
||||
@@ -211,12 +220,10 @@ func stateBeginValue(s *scanner, c byte) int {
|
||||
switch c {
|
||||
case '{':
|
||||
s.step = stateBeginStringOrEmpty
|
||||
s.pushParseState(parseObjectKey)
|
||||
return scanBeginObject
|
||||
return s.pushParseState(c, parseObjectKey, scanBeginObject)
|
||||
case '[':
|
||||
s.step = stateBeginValueOrEmpty
|
||||
s.pushParseState(parseArrayValue)
|
||||
return scanBeginArray
|
||||
return s.pushParseState(c, parseArrayValue, scanBeginArray)
|
||||
case '"':
|
||||
s.step = stateInString
|
||||
return scanBeginLiteral
|
||||
|
||||
+17
-9
@@ -153,6 +153,10 @@ func ParseEncryptedJSON(
|
||||
keyEncryptionAlgorithms []KeyAlgorithm,
|
||||
contentEncryption []ContentEncryption,
|
||||
) (*JSONWebEncryption, error) {
|
||||
if len(input) == 0 {
|
||||
return nil, errEmptyInput
|
||||
}
|
||||
|
||||
var parsed rawJSONWebEncryption
|
||||
err := json.Unmarshal([]byte(input), &parsed)
|
||||
if err != nil {
|
||||
@@ -198,15 +202,6 @@ func (parsed *rawJSONWebEncryption) sanitized(
|
||||
}
|
||||
}
|
||||
|
||||
// Note: this must be called _after_ we parse the protected header,
|
||||
// otherwise fields from the protected header will not get picked up.
|
||||
var err error
|
||||
mergedHeaders := obj.mergedHeaders(nil)
|
||||
obj.Header, err = mergedHeaders.sanitized()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders)
|
||||
}
|
||||
|
||||
if len(parsed.Recipients) == 0 {
|
||||
obj.recipients = []recipientInfo{
|
||||
{
|
||||
@@ -260,6 +255,15 @@ func (parsed *rawJSONWebEncryption) sanitized(
|
||||
}
|
||||
}
|
||||
|
||||
// Note: this must be called _after_ we parse the protected header,
|
||||
// otherwise fields from the protected header will not get picked up.
|
||||
mergedHeaders := obj.mergedHeaders(nil)
|
||||
var err error
|
||||
obj.Header, err = mergedHeaders.sanitized()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %w", err)
|
||||
}
|
||||
|
||||
obj.iv = parsed.Iv.bytes()
|
||||
obj.ciphertext = parsed.Ciphertext.bytes()
|
||||
obj.tag = parsed.Tag.bytes()
|
||||
@@ -291,6 +295,10 @@ func ParseEncryptedCompact(
|
||||
var parts [5]string
|
||||
var ok bool
|
||||
|
||||
if len(input) == 0 {
|
||||
return nil, errEmptyInput
|
||||
}
|
||||
|
||||
for i := range 4 {
|
||||
parts[i], input, ok = strings.Cut(input, ".")
|
||||
if !ok {
|
||||
|
||||
+217
-47
@@ -107,7 +107,7 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) {
|
||||
|
||||
switch key := k.Key.(type) {
|
||||
case ed25519.PublicKey:
|
||||
raw = fromEdPublicKey(key)
|
||||
raw, err = fromEdPublicKey(key)
|
||||
case *ecdsa.PublicKey:
|
||||
raw, err = fromEcPublicKey(key)
|
||||
case *rsa.PublicKey:
|
||||
@@ -177,13 +177,29 @@ func (k JSONWebKey) MarshalJSON() ([]byte, error) {
|
||||
// UnmarshalJSON reads a key from its JSON representation.
|
||||
//
|
||||
// Returns ErrUnsupportedKeyType for unrecognized or unsupported "kty" header values.
|
||||
func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
|
||||
//
|
||||
// Directly unmarshaling a JWK is not safe for untrusted input.
|
||||
func (k *JSONWebKey) UnmarshalJSON(data []byte) error {
|
||||
return k.unmarshalJSON(data, true)
|
||||
}
|
||||
|
||||
// unmarshalJSON reads a key from its JSON representation.
|
||||
//
|
||||
// If allowPrivate is false, a JWK with private key material is rejected and the
|
||||
// function is safe for use against untrusted input.
|
||||
func (k *JSONWebKey) unmarshalJSON(data []byte, allowPrivate bool) (err error) {
|
||||
var raw rawJSONWebKey
|
||||
err = json.Unmarshal(data, &raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !allowPrivate &&
|
||||
(raw.K != nil || raw.D != nil || raw.P != nil || raw.Q != nil ||
|
||||
raw.Dp != nil || raw.Dq != nil || raw.Qi != nil) {
|
||||
return errors.New("go-jose/go-jose: JWK contains private parameters")
|
||||
}
|
||||
|
||||
certs, err := parseCertificateChain(raw.X5c)
|
||||
if err != nil {
|
||||
return fmt.Errorf("go-jose/go-jose: failed to unmarshal x5c field: %s", err)
|
||||
@@ -207,21 +223,29 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
|
||||
case "EC":
|
||||
if raw.D != nil {
|
||||
key, err = raw.ecPrivateKey()
|
||||
if err == nil {
|
||||
keyPub = key.(*ecdsa.PrivateKey).Public()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key.(*ecdsa.PrivateKey).Public()
|
||||
} else {
|
||||
key, err = raw.ecPublicKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key
|
||||
}
|
||||
case "RSA":
|
||||
if raw.D != nil {
|
||||
key, err = raw.rsaPrivateKey()
|
||||
if err == nil {
|
||||
keyPub = key.(*rsa.PrivateKey).Public()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key.(*rsa.PrivateKey).Public()
|
||||
} else {
|
||||
key, err = raw.rsaPublicKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key
|
||||
}
|
||||
case "oct":
|
||||
@@ -229,25 +253,28 @@ func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
|
||||
return errors.New("go-jose/go-jose: invalid JWK, found 'oct' (symmetric) key with cert chain")
|
||||
}
|
||||
key, err = raw.symmetricKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "OKP":
|
||||
if raw.Crv == "Ed25519" {
|
||||
if raw.D != nil {
|
||||
key, err = raw.edPrivateKey()
|
||||
if err == nil {
|
||||
keyPub = key.(ed25519.PrivateKey).Public()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key.(ed25519.PrivateKey).Public()
|
||||
} else {
|
||||
key, err = raw.edPublicKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
keyPub = key
|
||||
}
|
||||
}
|
||||
case "":
|
||||
// kty MUST be present
|
||||
err = fmt.Errorf("go-jose/go-jose: missing json web key type")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
return fmt.Errorf("go-jose/go-jose: missing json web key type")
|
||||
}
|
||||
|
||||
if key == nil {
|
||||
@@ -388,11 +415,12 @@ func rsaThumbprintInput(n *big.Int, e int) (string, error) {
|
||||
|
||||
func edThumbprintInput(ed ed25519.PublicKey) (string, error) {
|
||||
crv := "Ed25519"
|
||||
if len(ed) > 32 {
|
||||
return "", errors.New("go-jose/go-jose: invalid elliptic key (too large)")
|
||||
err := validateEd25519PublicKey(ed)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf(edThumbprintTemplate, crv,
|
||||
newFixedSizeBuffer(ed, 32).base64()), nil
|
||||
newFixedSizeBuffer(ed, ed25519.PublicKeySize).base64()), nil
|
||||
}
|
||||
|
||||
// Thumbprint computes the JWK Thumbprint of a key using the
|
||||
@@ -493,23 +521,39 @@ func (k *JSONWebKey) Valid() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// MaxRSAModulusBits is the largest RSA modulus size, in bits, that will be
|
||||
// accepted when parsing a JWK. Applications that need larger keys can raise
|
||||
// this limit.
|
||||
//
|
||||
// If modifying MaxRSAModulusBits, do it before any parsing occurs.
|
||||
var MaxRSAModulusBits = 4096
|
||||
|
||||
func (key rawJSONWebKey) rsaPublicKey() (*rsa.PublicKey, error) {
|
||||
if key.N == nil || key.E == nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, missing n/e values")
|
||||
}
|
||||
|
||||
n := key.N.bigInt()
|
||||
if n.BitLen() > MaxRSAModulusBits {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large")
|
||||
}
|
||||
|
||||
return &rsa.PublicKey{
|
||||
N: key.N.bigInt(),
|
||||
N: n,
|
||||
E: key.E.toInt(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func fromEdPublicKey(pub ed25519.PublicKey) *rawJSONWebKey {
|
||||
func fromEdPublicKey(pub ed25519.PublicKey) (*rawJSONWebKey, error) {
|
||||
err := validateEd25519PublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rawJSONWebKey{
|
||||
Kty: "OKP",
|
||||
Crv: "Ed25519",
|
||||
X: newBuffer(pub),
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func fromRsaPublicKey(pub *rsa.PublicKey) *rawJSONWebKey {
|
||||
@@ -604,21 +648,36 @@ func (key rawJSONWebKey) edPrivateKey() (ed25519.PrivateKey, error) {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed25519 private key, missing %s value(s)", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
privateKey := make([]byte, ed25519.PrivateKeySize)
|
||||
copy(privateKey[0:32], key.D.bytes())
|
||||
copy(privateKey[32:], key.X.bytes())
|
||||
rv := ed25519.PrivateKey(privateKey)
|
||||
return rv, nil
|
||||
publicKey := key.X.bytes()
|
||||
err := validateEd25519PublicKey(publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
seed := key.D.bytes()
|
||||
if len(seed) != ed25519.SeedSize {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed25519 private key, wrong length for d")
|
||||
}
|
||||
|
||||
privateKey := ed25519.NewKeyFromSeed(seed)
|
||||
derivedPublicKey := privateKey.Public().(ed25519.PublicKey)
|
||||
if !bytes.Equal(derivedPublicKey, publicKey) {
|
||||
return nil, errors.New("go-jose/go-jose: invalid Ed25519 private key, x does not match d")
|
||||
}
|
||||
|
||||
return privateKey, nil
|
||||
}
|
||||
|
||||
func (key rawJSONWebKey) edPublicKey() (ed25519.PublicKey, error) {
|
||||
if key.X == nil {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid Ed key, missing x value")
|
||||
}
|
||||
publicKey := make([]byte, ed25519.PublicKeySize)
|
||||
copy(publicKey[0:32], key.X.bytes())
|
||||
rv := ed25519.PublicKey(publicKey)
|
||||
return rv, nil
|
||||
publicKey := key.X.bytes()
|
||||
err := validateEd25519PublicKey(publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ed25519.PublicKey(bytes.Clone(publicKey)), nil
|
||||
}
|
||||
|
||||
func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
|
||||
@@ -642,16 +701,23 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", "))
|
||||
}
|
||||
|
||||
n := key.N.bigInt()
|
||||
if n.BitLen() > MaxRSAModulusBits {
|
||||
return nil, fmt.Errorf("go-jose/go-jose: invalid RSA key, modulus too large")
|
||||
}
|
||||
|
||||
p, q := key.P.bigInt(), key.Q.bigInt()
|
||||
if p.BitLen()+q.BitLen() > n.BitLen()+1 || new(big.Int).Mul(p, q).Cmp(n) != 0 {
|
||||
return nil, errors.New("go-jose/go-jose: invalid RSA private key, p * q != n")
|
||||
}
|
||||
|
||||
rv := &rsa.PrivateKey{
|
||||
PublicKey: rsa.PublicKey{
|
||||
N: key.N.bigInt(),
|
||||
N: n,
|
||||
E: key.E.toInt(),
|
||||
},
|
||||
D: key.D.bigInt(),
|
||||
Primes: []*big.Int{
|
||||
key.P.bigInt(),
|
||||
key.Q.bigInt(),
|
||||
},
|
||||
D: key.D.bigInt(),
|
||||
Primes: []*big.Int{p, q},
|
||||
}
|
||||
|
||||
if key.Dp != nil {
|
||||
@@ -669,9 +735,17 @@ func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
|
||||
}
|
||||
|
||||
func fromEdPrivateKey(ed ed25519.PrivateKey) (*rawJSONWebKey, error) {
|
||||
raw := fromEdPublicKey(ed25519.PublicKey(ed[32:]))
|
||||
if len(ed) != ed25519.PrivateKeySize {
|
||||
return nil, errors.New("go-jose/go-jose: invalid Ed25519 private key length")
|
||||
}
|
||||
|
||||
raw.D = newBuffer(ed[0:32])
|
||||
publicKey := ed.Public().(ed25519.PublicKey)
|
||||
raw, err := fromEdPublicKey(publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
raw.D = newBuffer(ed.Seed())
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
@@ -810,7 +884,7 @@ var (
|
||||
ErrJWKSKidNotFound = errors.New("go-jose/go-jose: JWK with matching kid not found in JWK Set")
|
||||
)
|
||||
|
||||
func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
|
||||
func tryJWKS(key interface{}, header Header) (interface{}, error) {
|
||||
var jwks JSONWebKeySet
|
||||
|
||||
switch jwksType := key.(type) {
|
||||
@@ -823,16 +897,8 @@ func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// Determine the KID to search for from the headers.
|
||||
var kid string
|
||||
for _, header := range headers {
|
||||
if header.KeyID != "" {
|
||||
kid = header.KeyID
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If no KID is specified in the headers, reject.
|
||||
// If no KID is specified in the header, reject.
|
||||
kid := header.KeyID
|
||||
if kid == "" {
|
||||
return nil, ErrJWKSKidNotFound
|
||||
}
|
||||
@@ -846,3 +912,107 @@ func tryJWKS(key interface{}, headers ...Header) (interface{}, error) {
|
||||
|
||||
return keys[0].Key, nil
|
||||
}
|
||||
|
||||
// weakEd25519PublicKeys contains the low-order Ed25519 encodings accepted by
|
||||
// Go's verifier that must not be accepted as JOSE verification keys.
|
||||
var weakEd25519PublicKeys = map[[ed25519.PublicKeySize]byte]struct{}{
|
||||
{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
}: {},
|
||||
{
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
|
||||
}: {},
|
||||
{
|
||||
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
}: {},
|
||||
{
|
||||
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
|
||||
}: {},
|
||||
{
|
||||
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
|
||||
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
|
||||
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
|
||||
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05,
|
||||
}: {},
|
||||
{
|
||||
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
|
||||
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
|
||||
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
|
||||
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x85,
|
||||
}: {},
|
||||
{
|
||||
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
|
||||
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
|
||||
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
|
||||
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a,
|
||||
}: {},
|
||||
{
|
||||
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
|
||||
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
|
||||
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
|
||||
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0xfa,
|
||||
}: {},
|
||||
{
|
||||
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
|
||||
}: {},
|
||||
{
|
||||
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
}: {},
|
||||
{
|
||||
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
|
||||
}: {},
|
||||
{
|
||||
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
}: {},
|
||||
{
|
||||
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
|
||||
}: {},
|
||||
{
|
||||
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
}: {},
|
||||
}
|
||||
|
||||
func validateEd25519PublicKey(publicKey ed25519.PublicKey) error {
|
||||
if len(publicKey) != ed25519.PublicKeySize {
|
||||
return fmt.Errorf("go-jose/go-jose: invalid Ed25519 public key, wrong length for x")
|
||||
}
|
||||
|
||||
var encoded [ed25519.PublicKeySize]byte
|
||||
copy(encoded[:], publicKey)
|
||||
_, ok := weakEd25519PublicKeys[encoded]
|
||||
if ok {
|
||||
return errors.New("go-jose/go-jose: invalid Ed25519 public key, low-order point")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+29
-17
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/go-jose/go-jose/v4/json"
|
||||
)
|
||||
@@ -89,12 +90,12 @@ func ParseSigned(
|
||||
signature string,
|
||||
signatureAlgorithms []SignatureAlgorithm,
|
||||
) (*JSONWebSignature, error) {
|
||||
signature = stripWhitespace(signature)
|
||||
if strings.HasPrefix(signature, "{") {
|
||||
trimmed := strings.TrimLeftFunc(signature, unicode.IsSpace)
|
||||
if strings.HasPrefix(trimmed, "{") {
|
||||
return ParseSignedJSON(signature, signatureAlgorithms)
|
||||
}
|
||||
|
||||
return parseSignedCompact(signature, nil, signatureAlgorithms)
|
||||
return parseSignedCompact(stripWhitespace(signature), nil, signatureAlgorithms)
|
||||
}
|
||||
|
||||
// ParseSignedCompact parses a message in JWS Compact Serialization. Validation fails if the JWS is
|
||||
@@ -186,6 +187,10 @@ func ParseSignedJSON(
|
||||
input string,
|
||||
signatureAlgorithms []SignatureAlgorithm,
|
||||
) (*JSONWebSignature, error) {
|
||||
if len(input) == 0 {
|
||||
return nil, errEmptyInput
|
||||
}
|
||||
|
||||
var parsed rawJSONWebSignature
|
||||
err := json.Unmarshal([]byte(input), &parsed)
|
||||
if err != nil {
|
||||
@@ -270,17 +275,18 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
|
||||
Signature: parsed.Signature,
|
||||
}
|
||||
|
||||
var err error
|
||||
signature.Header, err = signature.mergedHeaders().sanitized()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
alg := SignatureAlgorithm(signature.Header.Algorithm)
|
||||
mergedHeaders := signature.mergedHeaders()
|
||||
alg := mergedHeaders.getSignatureAlgorithm()
|
||||
if !containsSignatureAlgorithm(signatureAlgorithms, alg) {
|
||||
return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms)
|
||||
}
|
||||
|
||||
var err error
|
||||
signature.Header, err = mergedHeaders.sanitized()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if signature.header != nil {
|
||||
signature.Unprotected, err = signature.header.sanitized()
|
||||
if err != nil {
|
||||
@@ -318,17 +324,20 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
|
||||
return nil, ErrUnprotectedNonce
|
||||
}
|
||||
|
||||
var err error
|
||||
obj.Signatures[i].Header, err = obj.Signatures[i].mergedHeaders().sanitized()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
obj.Signatures[i].header = sig.Header
|
||||
|
||||
alg := SignatureAlgorithm(obj.Signatures[i].Header.Algorithm)
|
||||
mergedHeaders := obj.Signatures[i].mergedHeaders()
|
||||
alg := mergedHeaders.getSignatureAlgorithm()
|
||||
if !containsSignatureAlgorithm(signatureAlgorithms, alg) {
|
||||
return nil, newErrUnexpectedSignatureAlgorithm(alg, signatureAlgorithms)
|
||||
}
|
||||
|
||||
var err error
|
||||
obj.Signatures[i].Header, err = mergedHeaders.sanitized()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if obj.Signatures[i].header != nil {
|
||||
obj.Signatures[i].Unprotected, err = obj.Signatures[i].header.sanitized()
|
||||
if err != nil {
|
||||
@@ -354,7 +363,6 @@ func (parsed *rawJSONWebSignature) sanitized(signatureAlgorithms []SignatureAlgo
|
||||
// Copy value of sig
|
||||
original := sig
|
||||
|
||||
obj.Signatures[i].header = sig.Header
|
||||
obj.Signatures[i].original = &original
|
||||
}
|
||||
|
||||
@@ -369,6 +377,10 @@ func parseSignedCompact(
|
||||
payload []byte,
|
||||
signatureAlgorithms []SignatureAlgorithm,
|
||||
) (*JSONWebSignature, error) {
|
||||
if len(input) == 0 {
|
||||
return nil, errEmptyInput
|
||||
}
|
||||
|
||||
protected, s, ok := strings.Cut(input, tokenDelim)
|
||||
if !ok { // no period found
|
||||
return nil, fmt.Errorf("go-jose/go-jose: compact JWS format must have three parts")
|
||||
|
||||
+5
@@ -46,6 +46,11 @@ func newOpaqueSigner(alg SignatureAlgorithm, signer OpaqueSigner) (recipientSigI
|
||||
return recipientSigInfo{}, ErrUnsupportedAlgorithm
|
||||
}
|
||||
|
||||
pk := signer.Public()
|
||||
if pk != nil && !pk.IsPublic() {
|
||||
return recipientSigInfo{}, ErrNotPublic
|
||||
}
|
||||
|
||||
return recipientSigInfo{
|
||||
sigAlg: alg,
|
||||
publicKey: signer.Public,
|
||||
|
||||
+17
-20
@@ -80,6 +80,12 @@ var (
|
||||
|
||||
// ErrUnsupportedCriticalHeader is returned when a header is marked critical but not supported by go-jose.
|
||||
ErrUnsupportedCriticalHeader = errors.New("go-jose/go-jose: unsupported critical header")
|
||||
|
||||
// errEmptyInput is returned when go-jose was asked to parse an empty string.
|
||||
errEmptyInput = errors.New("go-jose/go-jose: empty input")
|
||||
|
||||
// ErrNotPublic indicates a private key was passed where a public key was expected
|
||||
ErrNotPublic = errors.New("go-jose/go-jose: public key was unexpectedly not public")
|
||||
)
|
||||
|
||||
// Key management algorithms
|
||||
@@ -291,9 +297,10 @@ func (parsed rawHeader) getEPK() (*JSONWebKey, error) {
|
||||
if v == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var epk *JSONWebKey
|
||||
err := json.Unmarshal(*v, &epk)
|
||||
if err != nil {
|
||||
// RFC 7518 Section 4.6.1.1: the "epk" header is the ephemeral public key
|
||||
// of the originator. Reject private key material before parsing it.
|
||||
epk := new(JSONWebKey)
|
||||
if err := epk.unmarshalJSON(*v, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return epk, nil
|
||||
@@ -319,20 +326,6 @@ func (parsed rawHeader) getTag() (*byteBuffer, error) {
|
||||
return parsed.getByteBuffer(headerTag)
|
||||
}
|
||||
|
||||
// getJWK extracts parsed "jwk" from the raw JSON.
|
||||
func (parsed rawHeader) getJWK() (*JSONWebKey, error) {
|
||||
v := parsed[headerJWK]
|
||||
if v == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var jwk *JSONWebKey
|
||||
err := json.Unmarshal(*v, &jwk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return jwk, nil
|
||||
}
|
||||
|
||||
// getCritical extracts parsed "crit" from the raw JSON. If omitted, it
|
||||
// returns an empty slice.
|
||||
func (parsed rawHeader) getCritical() ([]string, error) {
|
||||
@@ -418,10 +411,14 @@ func (parsed rawHeader) sanitized() (h Header, err error) {
|
||||
}
|
||||
switch k {
|
||||
case headerJWK:
|
||||
var jwk *JSONWebKey
|
||||
err = json.Unmarshal(*v, &jwk)
|
||||
// RFC 7515 Section 4.1.3 and RFC 7516 Section 4.1.5: the "jwk"
|
||||
// header is the public key that corresponds to the key used to
|
||||
// sign the JWS or encrypt the JWE. Reject private key material
|
||||
// before parsing it.
|
||||
jwk := new(JSONWebKey)
|
||||
err = jwk.unmarshalJSON(*v, false)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("failed to unmarshal JWK: %v: %#v", err, string(*v))
|
||||
err = fmt.Errorf("failed to unmarshal JWK: %w", err)
|
||||
return
|
||||
}
|
||||
h.JSONWebKey = jwk
|
||||
|
||||
+65
-46
@@ -130,6 +130,8 @@ type payloadVerifier interface {
|
||||
verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error
|
||||
}
|
||||
|
||||
var errInvalidVerificationKey = errors.New("go-jose/go-jose: invalid verification key")
|
||||
|
||||
type genericSigner struct {
|
||||
recipients []recipientSigInfo
|
||||
nonceSource NonceSource
|
||||
@@ -138,11 +140,21 @@ type genericSigner struct {
|
||||
}
|
||||
|
||||
type recipientSigInfo struct {
|
||||
sigAlg SignatureAlgorithm
|
||||
sigAlg SignatureAlgorithm
|
||||
// publicKey returns a synthetic JSONWebKey for the signer.
|
||||
// For opaque signers, it calls OpaqueSigner.Public().
|
||||
publicKey func() *JSONWebKey
|
||||
signer payloadSigner
|
||||
}
|
||||
|
||||
// getPublicKey gets the public key, with a nil check on the func.
|
||||
func (r recipientSigInfo) getPublicKey() *JSONWebKey {
|
||||
if r.publicKey == nil {
|
||||
return nil
|
||||
}
|
||||
return r.publicKey()
|
||||
}
|
||||
|
||||
func staticPublicKey(jwk *JSONWebKey) func() *JSONWebKey {
|
||||
return func() *JSONWebKey {
|
||||
return jwk
|
||||
@@ -178,14 +190,23 @@ func NewMultiSigner(sigs []SigningKey, opts *SignerOptions) (Signer, error) {
|
||||
func newVerifier(verificationKey interface{}) (payloadVerifier, error) {
|
||||
switch verificationKey := verificationKey.(type) {
|
||||
case ed25519.PublicKey:
|
||||
if len(verificationKey) == 0 {
|
||||
return nil, errInvalidVerificationKey
|
||||
}
|
||||
return &edEncrypterVerifier{
|
||||
publicKey: verificationKey,
|
||||
}, nil
|
||||
case *rsa.PublicKey:
|
||||
if verificationKey == nil {
|
||||
return nil, errInvalidVerificationKey
|
||||
}
|
||||
return &rsaEncrypterVerifier{
|
||||
publicKey: verificationKey,
|
||||
}, nil
|
||||
case *ecdsa.PublicKey:
|
||||
if verificationKey == nil {
|
||||
return nil, errInvalidVerificationKey
|
||||
}
|
||||
return &ecEncrypterVerifier{
|
||||
publicKey: verificationKey,
|
||||
}, nil
|
||||
@@ -196,6 +217,9 @@ func newVerifier(verificationKey interface{}) (payloadVerifier, error) {
|
||||
case JSONWebKey:
|
||||
return newVerifier(verificationKey.Key)
|
||||
case *JSONWebKey:
|
||||
if verificationKey == nil {
|
||||
return nil, errInvalidVerificationKey
|
||||
}
|
||||
return newVerifier(verificationKey.Key)
|
||||
case OpaqueVerifier:
|
||||
return &opaqueVerifier{verifier: verificationKey}, nil
|
||||
@@ -240,18 +264,18 @@ func newJWKSigner(alg SignatureAlgorithm, signingKey JSONWebKey) (recipientSigIn
|
||||
if err != nil {
|
||||
return recipientSigInfo{}, err
|
||||
}
|
||||
if recipient.publicKey != nil && recipient.publicKey() != nil {
|
||||
if recipientPubKey := recipient.getPublicKey(); recipientPubKey != nil {
|
||||
// This should be impossible, but let's check anyway.
|
||||
if !recipientPubKey.IsPublic() {
|
||||
return recipientSigInfo{}, ErrNotPublic
|
||||
}
|
||||
|
||||
// recipient.publicKey is a JWK synthesized for embedding when recipientSigInfo
|
||||
// was created for the inner key (such as a RSA or ECDSA public key). It contains
|
||||
// the pub key for embedding, but doesn't have extra params like key id.
|
||||
publicKey := signingKey
|
||||
publicKey.Key = recipient.publicKey().Key
|
||||
publicKey.Key = recipientPubKey.Key
|
||||
recipient.publicKey = staticPublicKey(&publicKey)
|
||||
|
||||
// This should be impossible, but let's check anyway.
|
||||
if !recipient.publicKey().IsPublic() {
|
||||
return recipientSigInfo{}, errors.New("go-jose/go-jose: public key was unexpectedly not public")
|
||||
}
|
||||
}
|
||||
return recipient, nil
|
||||
}
|
||||
@@ -266,7 +290,7 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) {
|
||||
headerAlgorithm: string(recipient.sigAlg),
|
||||
}
|
||||
|
||||
if recipient.publicKey != nil && recipient.publicKey() != nil {
|
||||
if recipientPubKey := recipient.getPublicKey(); recipientPubKey != nil {
|
||||
// We want to embed the JWK or set the kid header, but not both. Having a protected
|
||||
// header that contains an embedded JWK while also simultaneously containing the kid
|
||||
// header is confusing, and at least in ACME the two are considered to be mutually
|
||||
@@ -274,11 +298,11 @@ func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) {
|
||||
// result of the JOSE spec. We've decided that this library will only include one or
|
||||
// the other to avoid this confusion.
|
||||
//
|
||||
// See https://github.com/go-jose/go-jose/issues/157 for more context.
|
||||
// See https://github.com/square/go-jose/issues/157 for more context.
|
||||
if ctx.embedJWK {
|
||||
protected[headerJWK] = recipient.publicKey()
|
||||
protected[headerJWK] = recipientPubKey
|
||||
} else {
|
||||
keyID := recipient.publicKey().KeyID
|
||||
keyID := recipientPubKey.KeyID
|
||||
if keyID != "" {
|
||||
protected[headerKeyID] = keyID
|
||||
}
|
||||
@@ -390,7 +414,13 @@ func (obj JSONWebSignature) UnsafePayloadWithoutVerification() []byte {
|
||||
// The verificationKey argument must have one of the types allowed for the
|
||||
// verificationKey argument of JSONWebSignature.Verify().
|
||||
func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey interface{}) error {
|
||||
key, err := tryJWKS(verificationKey, obj.headers()...)
|
||||
if len(obj.Signatures) > 1 {
|
||||
return errors.New("go-jose/go-jose: too many signatures in payload; expecting only one")
|
||||
}
|
||||
|
||||
signature := obj.Signatures[0]
|
||||
|
||||
key, err := tryJWKS(verificationKey, signature.Header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -399,12 +429,6 @@ func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey inter
|
||||
return err
|
||||
}
|
||||
|
||||
if len(obj.Signatures) > 1 {
|
||||
return errors.New("go-jose/go-jose: too many signatures in payload; expecting only one")
|
||||
}
|
||||
|
||||
signature := obj.Signatures[0]
|
||||
|
||||
if signature.header != nil {
|
||||
// Per https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.11,
|
||||
// 4.1.11. "crit" (Critical) Header Parameter
|
||||
@@ -432,11 +456,11 @@ func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey inter
|
||||
headers := signature.mergedHeaders()
|
||||
alg := headers.getSignatureAlgorithm()
|
||||
err = verifier.verifyPayload(input, signature.Signature, alg)
|
||||
if err == nil {
|
||||
return nil
|
||||
if err != nil {
|
||||
return ErrCryptoFailure
|
||||
}
|
||||
|
||||
return ErrCryptoFailure
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyMulti validates (one of the multiple) signatures on the object and
|
||||
@@ -467,16 +491,6 @@ func (obj JSONWebSignature) VerifyMulti(verificationKey interface{}) (int, Signa
|
||||
// The verificationKey argument must have one of the types allowed for the
|
||||
// verificationKey argument of JSONWebSignature.Verify().
|
||||
func (obj JSONWebSignature) DetachedVerifyMulti(payload []byte, verificationKey interface{}) (int, Signature, error) {
|
||||
key, err := tryJWKS(verificationKey, obj.headers()...)
|
||||
if err != nil {
|
||||
return -1, Signature{}, err
|
||||
}
|
||||
verifier, err := newVerifier(key)
|
||||
if err != nil {
|
||||
return -1, Signature{}, err
|
||||
}
|
||||
|
||||
outer:
|
||||
for i, signature := range obj.Signatures {
|
||||
if signature.header != nil {
|
||||
// Per https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1.11,
|
||||
@@ -484,20 +498,31 @@ outer:
|
||||
// "When used, this Header Parameter MUST be integrity
|
||||
// protected; therefore, it MUST occur only within the JWS
|
||||
// Protected Header."
|
||||
err = signature.header.checkNoCritical()
|
||||
err := signature.header.checkNoCritical()
|
||||
if err != nil {
|
||||
continue outer
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if signature.protected != nil {
|
||||
// Check for only supported critical headers
|
||||
err = signature.protected.checkSupportedCritical(supportedCritical)
|
||||
err := signature.protected.checkSupportedCritical(supportedCritical)
|
||||
if err != nil {
|
||||
continue outer
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// If the verification key is a JWK Set, pick a key based on this signature's
|
||||
// "kid" header. If no match, skip this signature.
|
||||
key, err := tryJWKS(verificationKey, signature.Header)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
verifier, err := newVerifier(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
input, err := obj.computeAuthData(payload, &signature)
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -506,18 +531,12 @@ outer:
|
||||
headers := signature.mergedHeaders()
|
||||
alg := headers.getSignatureAlgorithm()
|
||||
err = verifier.verifyPayload(input, signature.Signature, alg)
|
||||
if err == nil {
|
||||
return i, signature, nil
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
return i, signature, nil
|
||||
}
|
||||
|
||||
return -1, Signature{}, ErrCryptoFailure
|
||||
}
|
||||
|
||||
func (obj JSONWebSignature) headers() []Header {
|
||||
headers := make([]Header, len(obj.Signatures))
|
||||
for i, sig := range obj.Signatures {
|
||||
headers[i] = sig.Header
|
||||
}
|
||||
return headers
|
||||
}
|
||||
+5
-5
@@ -34,8 +34,8 @@ import (
|
||||
josecipher "github.com/go-jose/go-jose/v4/cipher"
|
||||
)
|
||||
|
||||
// RandReader is a cryptographically secure random number generator (stubbed out in tests).
|
||||
var RandReader = rand.Reader
|
||||
// randReader is a cryptographically secure random number generator (stubbed out in tests).
|
||||
var randReader = rand.Reader
|
||||
|
||||
const (
|
||||
// RFC7518 recommends a minimum of 1,000 iterations:
|
||||
@@ -153,7 +153,7 @@ func getPbkdf2Params(alg KeyAlgorithm) (int, func() hash.Hash) {
|
||||
// getRandomSalt generates a new salt of the given size.
|
||||
func getRandomSalt(size int) ([]byte, error) {
|
||||
salt := make([]byte, size)
|
||||
_, err := io.ReadFull(RandReader, salt)
|
||||
_, err := io.ReadFull(randReader, salt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -198,7 +198,7 @@ func newSymmetricSigner(sigAlg SignatureAlgorithm, key []byte) (recipientSigInfo
|
||||
// Generate a random key for the given content cipher
|
||||
func (ctx randomKeyGenerator) genKey() ([]byte, rawHeader, error) {
|
||||
key := make([]byte, ctx.size)
|
||||
_, err := io.ReadFull(RandReader, key)
|
||||
_, err := io.ReadFull(randReader, key)
|
||||
if err != nil {
|
||||
return nil, rawHeader{}, err
|
||||
}
|
||||
@@ -238,7 +238,7 @@ func (ctx aeadContentCipher) encrypt(key, aad, pt []byte) (*aeadParts, error) {
|
||||
|
||||
// Initialize a new nonce
|
||||
iv := make([]byte, aead.NonceSize())
|
||||
_, err = io.ReadFull(RandReader, iv)
|
||||
_, err = io.ReadFull(randReader, iv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
# This containerfile can be used to run the go-jose tests and cli
|
||||
|
||||
FROM golang:1.27-trixie
|
||||
ENV GOTOOLCHAIN=local
|
||||
|
||||
COPY . /src
|
||||
WORKDIR /src
|
||||
|
||||
# Install the jose-util cli, which will also build the library
|
||||
RUN go build -o /usr/local/bin/jose-util ./jose-util
|
||||
|
||||
# By default, run the tests
|
||||
CMD ["go", "test", "./..."]
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# Threat model
|
||||
|
||||
## What this project does and where untrusted input enters
|
||||
go-jose is a Go implementation of JOSE family of algorithms.
|
||||
|
||||
It is a library which will parse attacker-controlled data in network-reachable
|
||||
services.
|
||||
|
||||
## Components that matter most / least
|
||||
The primary attack surface of interest is parsing and validating JWS, JWE, JWK,
|
||||
etc when this library is used to implement authentication and authorization.
|
||||
|
||||
## How to exercise it
|
||||
Testing is primarily done by Golang unit tests, which can be run with the
|
||||
tests.Container file's default CMD.
|
||||
|
||||
## How you rate severity
|
||||
Any authentication bypass enabled by a go-jose issue is a high+ severity.
|
||||
|
||||
Denial-of-service attacks are of interest when the functions may be used in a protocol like OIDC, ACME, etc
|
||||
which could have a server processing attacker-controlled data.
|
||||
|
||||
## Anything to leave alone
|
||||
Any bug which only affects the jose-util CLI tool, but it can be used to exercise the library.
|
||||
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flate
|
||||
|
||||
// Sort sorts data.
|
||||
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
|
||||
// data.Less and data.Swap. The sort is not guaranteed to be stable.
|
||||
func sortByFreq(data []literalNode) {
|
||||
n := len(data)
|
||||
quickSortByFreq(data, 0, n, maxDepth(n))
|
||||
}
|
||||
|
||||
func quickSortByFreq(data []literalNode, a, b, maxDepth int) {
|
||||
for b-a > 12 { // Use ShellSort for slices <= 12 elements
|
||||
if maxDepth == 0 {
|
||||
heapSort(data, a, b)
|
||||
return
|
||||
}
|
||||
maxDepth--
|
||||
mlo, mhi := doPivotByFreq(data, a, b)
|
||||
// Avoiding recursion on the larger subproblem guarantees
|
||||
// a stack depth of at most lg(b-a).
|
||||
if mlo-a < b-mhi {
|
||||
quickSortByFreq(data, a, mlo, maxDepth)
|
||||
a = mhi // i.e., quickSortByFreq(data, mhi, b)
|
||||
} else {
|
||||
quickSortByFreq(data, mhi, b, maxDepth)
|
||||
b = mlo // i.e., quickSortByFreq(data, a, mlo)
|
||||
}
|
||||
}
|
||||
if b-a > 1 {
|
||||
// Do ShellSort pass with gap 6
|
||||
// It could be written in this simplified form cause b-a <= 12
|
||||
for i := a + 6; i < b; i++ {
|
||||
if data[i].freq == data[i-6].freq && data[i].literal < data[i-6].literal || data[i].freq < data[i-6].freq {
|
||||
data[i], data[i-6] = data[i-6], data[i]
|
||||
}
|
||||
}
|
||||
insertionSortByFreq(data, a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func doPivotByFreq(data []literalNode, lo, hi int) (midlo, midhi int) {
|
||||
m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow.
|
||||
if hi-lo > 40 {
|
||||
// Tukey's ``Ninther,'' median of three medians of three.
|
||||
s := (hi - lo) / 8
|
||||
medianOfThreeSortByFreq(data, lo, lo+s, lo+2*s)
|
||||
medianOfThreeSortByFreq(data, m, m-s, m+s)
|
||||
medianOfThreeSortByFreq(data, hi-1, hi-1-s, hi-1-2*s)
|
||||
}
|
||||
medianOfThreeSortByFreq(data, lo, m, hi-1)
|
||||
|
||||
// Invariants are:
|
||||
// data[lo] = pivot (set up by ChoosePivot)
|
||||
// data[lo < i < a] < pivot
|
||||
// data[a <= i < b] <= pivot
|
||||
// data[b <= i < c] unexamined
|
||||
// data[c <= i < hi-1] > pivot
|
||||
// data[hi-1] >= pivot
|
||||
pivot := lo
|
||||
a, c := lo+1, hi-1
|
||||
|
||||
for ; a < c && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ {
|
||||
}
|
||||
b := a
|
||||
for {
|
||||
for ; b < c && (data[pivot].freq == data[b].freq && data[pivot].literal > data[b].literal || data[pivot].freq > data[b].freq); b++ { // data[b] <= pivot
|
||||
}
|
||||
for ; b < c && (data[pivot].freq == data[c-1].freq && data[pivot].literal < data[c-1].literal || data[pivot].freq < data[c-1].freq); c-- { // data[c-1] > pivot
|
||||
}
|
||||
if b >= c {
|
||||
break
|
||||
}
|
||||
// data[b] > pivot; data[c-1] <= pivot
|
||||
data[b], data[c-1] = data[c-1], data[b]
|
||||
b++
|
||||
c--
|
||||
}
|
||||
// If hi-c<3 then there are duplicates (by property of median of nine).
|
||||
// Let's be a bit more conservative, and set border to 5.
|
||||
protect := hi-c < 5
|
||||
if !protect && hi-c < (hi-lo)/4 {
|
||||
// Lets test some points for equality to pivot
|
||||
dups := 0
|
||||
if data[pivot].freq == data[hi-1].freq && data[pivot].literal > data[hi-1].literal || data[pivot].freq > data[hi-1].freq { // data[hi-1] = pivot
|
||||
data[c], data[hi-1] = data[hi-1], data[c]
|
||||
c++
|
||||
dups++
|
||||
}
|
||||
if data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq { // data[b-1] = pivot
|
||||
b--
|
||||
dups++
|
||||
}
|
||||
// m-lo = (hi-lo)/2 > 6
|
||||
// b-lo > (hi-lo)*3/4-1 > 8
|
||||
// ==> m < b ==> data[m] <= pivot
|
||||
if data[m].freq == data[pivot].freq && data[m].literal > data[pivot].literal || data[m].freq > data[pivot].freq { // data[m] = pivot
|
||||
data[m], data[b-1] = data[b-1], data[m]
|
||||
b--
|
||||
dups++
|
||||
}
|
||||
// if at least 2 points are equal to pivot, assume skewed distribution
|
||||
protect = dups > 1
|
||||
}
|
||||
if protect {
|
||||
// Protect against a lot of duplicates
|
||||
// Add invariant:
|
||||
// data[a <= i < b] unexamined
|
||||
// data[b <= i < c] = pivot
|
||||
for {
|
||||
for ; a < b && (data[b-1].freq == data[pivot].freq && data[b-1].literal > data[pivot].literal || data[b-1].freq > data[pivot].freq); b-- { // data[b] == pivot
|
||||
}
|
||||
for ; a < b && (data[a].freq == data[pivot].freq && data[a].literal < data[pivot].literal || data[a].freq < data[pivot].freq); a++ { // data[a] < pivot
|
||||
}
|
||||
if a >= b {
|
||||
break
|
||||
}
|
||||
// data[a] == pivot; data[b-1] < pivot
|
||||
data[a], data[b-1] = data[b-1], data[a]
|
||||
a++
|
||||
b--
|
||||
}
|
||||
}
|
||||
// Swap pivot into middle
|
||||
data[pivot], data[b-1] = data[b-1], data[pivot]
|
||||
return b - 1, c
|
||||
}
|
||||
|
||||
// Insertion sort
|
||||
func insertionSortByFreq(data []literalNode, a, b int) {
|
||||
for i := a + 1; i < b; i++ {
|
||||
for j := i; j > a && (data[j].freq == data[j-1].freq && data[j].literal < data[j-1].literal || data[j].freq < data[j-1].freq); j-- {
|
||||
data[j], data[j-1] = data[j-1], data[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// quickSortByFreq, loosely following Bentley and McIlroy,
|
||||
// ``Engineering a Sort Function,'' SP&E November 1993.
|
||||
|
||||
// medianOfThreeSortByFreq moves the median of the three values data[m0], data[m1], data[m2] into data[m1].
|
||||
func medianOfThreeSortByFreq(data []literalNode, m1, m0, m2 int) {
|
||||
// sort 3 elements
|
||||
if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq {
|
||||
data[m1], data[m0] = data[m0], data[m1]
|
||||
}
|
||||
// data[m0] <= data[m1]
|
||||
if data[m2].freq == data[m1].freq && data[m2].literal < data[m1].literal || data[m2].freq < data[m1].freq {
|
||||
data[m2], data[m1] = data[m1], data[m2]
|
||||
// data[m0] <= data[m2] && data[m1] < data[m2]
|
||||
if data[m1].freq == data[m0].freq && data[m1].literal < data[m0].literal || data[m1].freq < data[m0].freq {
|
||||
data[m1], data[m0] = data[m0], data[m1]
|
||||
}
|
||||
}
|
||||
// now data[m0] <= data[m1] <= data[m2]
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package flate
|
||||
|
||||
// Sort sorts data.
|
||||
// It makes one call to data.Len to determine n, and O(n*log(n)) calls to
|
||||
// data.Less and data.Swap. The sort is not guaranteed to be stable.
|
||||
func sortByLiteral(data []literalNode) {
|
||||
n := len(data)
|
||||
quickSort(data, 0, n, maxDepth(n))
|
||||
}
|
||||
|
||||
func quickSort(data []literalNode, a, b, maxDepth int) {
|
||||
for b-a > 12 { // Use ShellSort for slices <= 12 elements
|
||||
if maxDepth == 0 {
|
||||
heapSort(data, a, b)
|
||||
return
|
||||
}
|
||||
maxDepth--
|
||||
mlo, mhi := doPivot(data, a, b)
|
||||
// Avoiding recursion on the larger subproblem guarantees
|
||||
// a stack depth of at most lg(b-a).
|
||||
if mlo-a < b-mhi {
|
||||
quickSort(data, a, mlo, maxDepth)
|
||||
a = mhi // i.e., quickSort(data, mhi, b)
|
||||
} else {
|
||||
quickSort(data, mhi, b, maxDepth)
|
||||
b = mlo // i.e., quickSort(data, a, mlo)
|
||||
}
|
||||
}
|
||||
if b-a > 1 {
|
||||
// Do ShellSort pass with gap 6
|
||||
// It could be written in this simplified form cause b-a <= 12
|
||||
for i := a + 6; i < b; i++ {
|
||||
if data[i].literal < data[i-6].literal {
|
||||
data[i], data[i-6] = data[i-6], data[i]
|
||||
}
|
||||
}
|
||||
insertionSort(data, a, b)
|
||||
}
|
||||
}
|
||||
func heapSort(data []literalNode, a, b int) {
|
||||
first := a
|
||||
lo := 0
|
||||
hi := b - a
|
||||
|
||||
// Build heap with greatest element at top.
|
||||
for i := (hi - 1) / 2; i >= 0; i-- {
|
||||
siftDown(data, i, hi, first)
|
||||
}
|
||||
|
||||
// Pop elements, largest first, into end of data.
|
||||
for i := hi - 1; i >= 0; i-- {
|
||||
data[first], data[first+i] = data[first+i], data[first]
|
||||
siftDown(data, lo, i, first)
|
||||
}
|
||||
}
|
||||
|
||||
// siftDown implements the heap property on data[lo, hi).
|
||||
// first is an offset into the array where the root of the heap lies.
|
||||
func siftDown(data []literalNode, lo, hi, first int) {
|
||||
root := lo
|
||||
for {
|
||||
child := 2*root + 1
|
||||
if child >= hi {
|
||||
break
|
||||
}
|
||||
if child+1 < hi && data[first+child].literal < data[first+child+1].literal {
|
||||
child++
|
||||
}
|
||||
if data[first+root].literal > data[first+child].literal {
|
||||
return
|
||||
}
|
||||
data[first+root], data[first+child] = data[first+child], data[first+root]
|
||||
root = child
|
||||
}
|
||||
}
|
||||
func doPivot(data []literalNode, lo, hi int) (midlo, midhi int) {
|
||||
m := int(uint(lo+hi) >> 1) // Written like this to avoid integer overflow.
|
||||
if hi-lo > 40 {
|
||||
// Tukey's ``Ninther,'' median of three medians of three.
|
||||
s := (hi - lo) / 8
|
||||
medianOfThree(data, lo, lo+s, lo+2*s)
|
||||
medianOfThree(data, m, m-s, m+s)
|
||||
medianOfThree(data, hi-1, hi-1-s, hi-1-2*s)
|
||||
}
|
||||
medianOfThree(data, lo, m, hi-1)
|
||||
|
||||
// Invariants are:
|
||||
// data[lo] = pivot (set up by ChoosePivot)
|
||||
// data[lo < i < a] < pivot
|
||||
// data[a <= i < b] <= pivot
|
||||
// data[b <= i < c] unexamined
|
||||
// data[c <= i < hi-1] > pivot
|
||||
// data[hi-1] >= pivot
|
||||
pivot := lo
|
||||
a, c := lo+1, hi-1
|
||||
|
||||
for ; a < c && data[a].literal < data[pivot].literal; a++ {
|
||||
}
|
||||
b := a
|
||||
for {
|
||||
for ; b < c && data[pivot].literal > data[b].literal; b++ { // data[b] <= pivot
|
||||
}
|
||||
for ; b < c && data[pivot].literal < data[c-1].literal; c-- { // data[c-1] > pivot
|
||||
}
|
||||
if b >= c {
|
||||
break
|
||||
}
|
||||
// data[b] > pivot; data[c-1] <= pivot
|
||||
data[b], data[c-1] = data[c-1], data[b]
|
||||
b++
|
||||
c--
|
||||
}
|
||||
// If hi-c<3 then there are duplicates (by property of median of nine).
|
||||
// Let's be a bit more conservative, and set border to 5.
|
||||
protect := hi-c < 5
|
||||
if !protect && hi-c < (hi-lo)/4 {
|
||||
// Lets test some points for equality to pivot
|
||||
dups := 0
|
||||
if data[pivot].literal > data[hi-1].literal { // data[hi-1] = pivot
|
||||
data[c], data[hi-1] = data[hi-1], data[c]
|
||||
c++
|
||||
dups++
|
||||
}
|
||||
if data[b-1].literal > data[pivot].literal { // data[b-1] = pivot
|
||||
b--
|
||||
dups++
|
||||
}
|
||||
// m-lo = (hi-lo)/2 > 6
|
||||
// b-lo > (hi-lo)*3/4-1 > 8
|
||||
// ==> m < b ==> data[m] <= pivot
|
||||
if data[m].literal > data[pivot].literal { // data[m] = pivot
|
||||
data[m], data[b-1] = data[b-1], data[m]
|
||||
b--
|
||||
dups++
|
||||
}
|
||||
// if at least 2 points are equal to pivot, assume skewed distribution
|
||||
protect = dups > 1
|
||||
}
|
||||
if protect {
|
||||
// Protect against a lot of duplicates
|
||||
// Add invariant:
|
||||
// data[a <= i < b] unexamined
|
||||
// data[b <= i < c] = pivot
|
||||
for {
|
||||
for ; a < b && data[b-1].literal > data[pivot].literal; b-- { // data[b] == pivot
|
||||
}
|
||||
for ; a < b && data[a].literal < data[pivot].literal; a++ { // data[a] < pivot
|
||||
}
|
||||
if a >= b {
|
||||
break
|
||||
}
|
||||
// data[a] == pivot; data[b-1] < pivot
|
||||
data[a], data[b-1] = data[b-1], data[a]
|
||||
a++
|
||||
b--
|
||||
}
|
||||
}
|
||||
// Swap pivot into middle
|
||||
data[pivot], data[b-1] = data[b-1], data[pivot]
|
||||
return b - 1, c
|
||||
}
|
||||
|
||||
// Insertion sort
|
||||
func insertionSort(data []literalNode, a, b int) {
|
||||
for i := a + 1; i < b; i++ {
|
||||
for j := i; j > a && data[j].literal < data[j-1].literal; j-- {
|
||||
data[j], data[j-1] = data[j-1], data[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maxDepth returns a threshold at which quicksort should switch
|
||||
// to heapsort. It returns 2*ceil(lg(n+1)).
|
||||
func maxDepth(n int) int {
|
||||
var depth int
|
||||
for i := n; i > 0; i >>= 1 {
|
||||
depth++
|
||||
}
|
||||
return depth * 2
|
||||
}
|
||||
|
||||
// medianOfThree moves the median of the three values data[m0], data[m1], data[m2] into data[m1].
|
||||
func medianOfThree(data []literalNode, m1, m0, m2 int) {
|
||||
// sort 3 elements
|
||||
if data[m1].literal < data[m0].literal {
|
||||
data[m1], data[m0] = data[m0], data[m1]
|
||||
}
|
||||
// data[m0] <= data[m1]
|
||||
if data[m2].literal < data[m1].literal {
|
||||
data[m2], data[m1] = data[m1], data[m2]
|
||||
// data[m0] <= data[m2] && data[m1] < data[m2]
|
||||
if data[m1].literal < data[m0].literal {
|
||||
data[m1], data[m0] = data[m0], data[m1]
|
||||
}
|
||||
}
|
||||
// now data[m0] <= data[m1] <= data[m2]
|
||||
}
|
||||
vendor/github.com/owncloud/reva/v2/internal/grpc/services/publicshareprovider/publicshareprovider.go
Generated
Vendored
+6
-1
@@ -353,7 +353,12 @@ func (s *service) CreatePublicShare(ctx context.Context, req *link.CreatePublicS
|
||||
share, err := s.sm.CreatePublicShare(ctx, user, resourceInfo, req.GetGrant())
|
||||
switch {
|
||||
case err != nil:
|
||||
log.Error().Err(err).Interface("request", req).Msg("could not write public share")
|
||||
// don't log the request: its grant carries the link password in plain text
|
||||
log.Error().Err(err).
|
||||
Interface("resource_id", sRes.GetInfo().GetId()).
|
||||
Interface("permissions", grant.GetPermissions().GetPermissions()).
|
||||
Bool("password_protected", len(setPassword) > 0).
|
||||
Msg("could not write public share")
|
||||
res.Status = status.NewInternal(ctx, "error persisting public share:"+err.Error())
|
||||
default:
|
||||
res.Status = status.NewOK(ctx)
|
||||
|
||||
Generated
Vendored
+1
-1
@@ -115,7 +115,7 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
|
||||
// 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 {
|
||||
if err := coord.StartPostprocessing(evstream, ac); err != nil {
|
||||
return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
+86
-16
@@ -24,6 +24,7 @@ import (
|
||||
"io"
|
||||
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -31,14 +32,15 @@ import (
|
||||
authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1"
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/owncloud/reva/v2/pkg/appauth"
|
||||
"github.com/owncloud/reva/v2/pkg/appauth/manager/registry"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sethvargo/go-password/password"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"google.golang.org/protobuf/encoding/prototext"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
@@ -77,16 +79,82 @@ func New(m map[string]interface{}) (appauth.Manager, error) {
|
||||
|
||||
manager.config = c
|
||||
|
||||
// Purge expired tokens on startup so they don't accumulate over time.
|
||||
// This runs before the manager is shared, so no lock is needed.
|
||||
if len(manager.passwords) == 0 {
|
||||
return manager, nil
|
||||
}
|
||||
// Both steps run before the manager is shared, so no lock is needed.
|
||||
// Re-key buckets written by older versions under UserId.String(), then
|
||||
// purge expired tokens so they don't accumulate over time.
|
||||
changed := manager.migrateLegacyKeys()
|
||||
|
||||
if !c.KeepExpiredTokensOnLoad {
|
||||
manager.purgeExpiredTokens()
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
// A failed save is not fatal: the in-memory state is correct and
|
||||
// the next start repeats the migration.
|
||||
_ = manager.save()
|
||||
}
|
||||
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
// userKey returns the key of the bucket that holds the app passwords of a user.
|
||||
// It does not use UserId.String(): that is the protobuf text format, and
|
||||
// protobuf-go varies its whitespace between binaries, so the same user gets a
|
||||
// different key after a rebuild and loses access to the stored app passwords.
|
||||
func userKey(id *userpb.UserId) string {
|
||||
return id.GetIdp() + "|" + id.GetOpaqueId()
|
||||
}
|
||||
|
||||
// migrateLegacyKeys re-keys the buckets that older versions stored under
|
||||
// UserId.String(). It parses each such key back into a user id and moves the
|
||||
// bucket under userKey. Buckets of the same user that differ only in whitespace
|
||||
// are merged. It reports whether it changed anything.
|
||||
// Must be called before the manager is shared (no lock needed).
|
||||
func (mgr *jsonManager) migrateLegacyKeys() bool {
|
||||
migrated := make(map[string]map[string]*apppb.AppPassword, len(mgr.passwords))
|
||||
changed := false
|
||||
// Keys that are already stable are copied first, so that on a conflict
|
||||
// their tokens win over the tokens of a legacy bucket.
|
||||
var legacy []string
|
||||
for key, tokens := range mgr.passwords {
|
||||
if isLegacyKey(key) {
|
||||
legacy = append(legacy, key)
|
||||
continue
|
||||
}
|
||||
migrated[key] = tokens
|
||||
}
|
||||
for _, key := range legacy {
|
||||
id := &userpb.UserId{}
|
||||
if err := prototext.Unmarshal([]byte(key), id); err != nil {
|
||||
// Not a user id in text format, keep the bucket as it is.
|
||||
migrated[key] = mgr.passwords[key]
|
||||
continue
|
||||
}
|
||||
newKey := userKey(id)
|
||||
if migrated[newKey] == nil {
|
||||
migrated[newKey] = make(map[string]*apppb.AppPassword, len(mgr.passwords[key]))
|
||||
}
|
||||
for hash, pw := range mgr.passwords[key] {
|
||||
if _, exists := migrated[newKey][hash]; !exists {
|
||||
migrated[newKey][hash] = pw
|
||||
}
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
mgr.passwords = migrated
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// isLegacyKey reports whether key looks like the text form of a user id.
|
||||
func isLegacyKey(key string) bool {
|
||||
return strings.Contains(key, "opaque_id:") || strings.Contains(key, "idp:")
|
||||
}
|
||||
|
||||
func (c *config) init() {
|
||||
if c.File == "" {
|
||||
c.File = "/var/tmp/reva/appauth.json"
|
||||
@@ -153,6 +221,7 @@ func (mgr *jsonManager) GenerateAppPassword(ctx context.Context, scope map[strin
|
||||
return nil, errors.Wrap(err, "error creating new token")
|
||||
}
|
||||
userID := ctxpkg.ContextMustGetUser(ctx).GetId()
|
||||
uKey := userKey(userID)
|
||||
ctime := now()
|
||||
|
||||
password := string(tokenHashed)
|
||||
@@ -168,14 +237,14 @@ func (mgr *jsonManager) GenerateAppPassword(ctx context.Context, scope map[strin
|
||||
mgr.Lock()
|
||||
defer mgr.Unlock()
|
||||
|
||||
mgr.purgeExpiredUserTokens(userID.String())
|
||||
mgr.purgeExpiredUserTokens(uKey)
|
||||
|
||||
// check if user has some previous password
|
||||
if _, ok := mgr.passwords[userID.String()]; !ok {
|
||||
mgr.passwords[userID.String()] = make(map[string]*apppb.AppPassword)
|
||||
if _, ok := mgr.passwords[uKey]; !ok {
|
||||
mgr.passwords[uKey] = make(map[string]*apppb.AppPassword)
|
||||
}
|
||||
|
||||
mgr.passwords[userID.String()][password] = appPass
|
||||
mgr.passwords[uKey][password] = appPass
|
||||
|
||||
err = mgr.save()
|
||||
if err != nil {
|
||||
@@ -188,23 +257,23 @@ func (mgr *jsonManager) GenerateAppPassword(ctx context.Context, scope map[strin
|
||||
}
|
||||
|
||||
func (mgr *jsonManager) ListAppPasswords(ctx context.Context) ([]*apppb.AppPassword, error) {
|
||||
userID := ctxpkg.ContextMustGetUser(ctx).GetId()
|
||||
uKey := userKey(ctxpkg.ContextMustGetUser(ctx).GetId())
|
||||
mgr.RLock()
|
||||
defer mgr.RUnlock()
|
||||
appPasswords := []*apppb.AppPassword{}
|
||||
for _, pw := range mgr.passwords[userID.String()] {
|
||||
for _, pw := range mgr.passwords[uKey] {
|
||||
appPasswords = append(appPasswords, pw)
|
||||
}
|
||||
return appPasswords, nil
|
||||
}
|
||||
|
||||
func (mgr *jsonManager) InvalidateAppPassword(ctx context.Context, password string) error {
|
||||
userID := ctxpkg.ContextMustGetUser(ctx).GetId()
|
||||
uKey := userKey(ctxpkg.ContextMustGetUser(ctx).GetId())
|
||||
mgr.Lock()
|
||||
defer mgr.Unlock()
|
||||
|
||||
// see if user has a list of passwords
|
||||
appPasswords, ok := mgr.passwords[userID.String()]
|
||||
appPasswords, ok := mgr.passwords[uKey]
|
||||
if !ok || len(appPasswords) == 0 {
|
||||
return errtypes.NotFound("password not found")
|
||||
}
|
||||
@@ -212,11 +281,11 @@ func (mgr *jsonManager) InvalidateAppPassword(ctx context.Context, password stri
|
||||
if _, ok := appPasswords[password]; !ok {
|
||||
return errtypes.NotFound("password not found")
|
||||
}
|
||||
delete(mgr.passwords[userID.String()], password)
|
||||
delete(mgr.passwords[uKey], password)
|
||||
|
||||
// if user has 0 passwords, delete user key from state map
|
||||
if len(mgr.passwords[userID.String()]) == 0 {
|
||||
delete(mgr.passwords, userID.String())
|
||||
if len(mgr.passwords[uKey]) == 0 {
|
||||
delete(mgr.passwords, uKey)
|
||||
}
|
||||
|
||||
return mgr.save()
|
||||
@@ -227,8 +296,9 @@ func (mgr *jsonManager) GetAppPassword(ctx context.Context, userID *userpb.UserI
|
||||
// Expired tokens are skipped before the expensive bcrypt comparison so
|
||||
// that accumulated expired tokens do not slow down authentication.
|
||||
// A read lock allows concurrent GetAppPassword calls.
|
||||
uKey := userKey(userID)
|
||||
mgr.RLock()
|
||||
appPasswords, ok := mgr.passwords[userID.String()]
|
||||
appPasswords, ok := mgr.passwords[uKey]
|
||||
if !ok {
|
||||
mgr.RUnlock()
|
||||
return nil, errtypes.NotFound("password not found")
|
||||
@@ -259,7 +329,7 @@ func (mgr *jsonManager) GetAppPassword(ctx context.Context, userID *userpb.UserI
|
||||
mgr.Lock()
|
||||
defer mgr.Unlock()
|
||||
|
||||
if current, ok := mgr.passwords[userID.String()][matchedHash]; ok {
|
||||
if current, ok := mgr.passwords[uKey][matchedHash]; ok {
|
||||
current.Utime = now()
|
||||
if err := mgr.save(); err != nil {
|
||||
return nil, errors.Wrap(err, "error saving file")
|
||||
|
||||
-1
@@ -29,7 +29,6 @@ import (
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/nextcloud"
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/ocmshares"
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/oidc"
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/owncloudsql"
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/publicshares"
|
||||
_ "github.com/owncloud/reva/v2/pkg/auth/manager/serviceaccounts"
|
||||
// Add your own here
|
||||
|
||||
Generated
Vendored
-165
@@ -1,165 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package accounts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Accounts represents oc10-style Accounts
|
||||
type Accounts struct {
|
||||
driver string
|
||||
db *sql.DB
|
||||
joinUsername, joinUUID, enableMedialSearch bool
|
||||
selectSQL string
|
||||
}
|
||||
|
||||
// NewMysql returns a new accounts instance connecting to a MySQL database
|
||||
func NewMysql(dsn string, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) {
|
||||
sqldb, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error connecting to the database")
|
||||
}
|
||||
|
||||
// FIXME make configurable
|
||||
sqldb.SetConnMaxLifetime(time.Minute * 3)
|
||||
sqldb.SetConnMaxIdleTime(time.Second * 30)
|
||||
sqldb.SetMaxOpenConns(100)
|
||||
sqldb.SetMaxIdleConns(10)
|
||||
|
||||
err = sqldb.Ping()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error connecting to the database")
|
||||
}
|
||||
|
||||
return New("mysql", sqldb, joinUsername, joinUUID, enableMedialSearch)
|
||||
}
|
||||
|
||||
// New returns a new accounts instance connecting to the given sql.DB
|
||||
func New(driver string, sqldb *sql.DB, joinUsername, joinUUID, enableMedialSearch bool) (*Accounts, error) {
|
||||
|
||||
sel := "SELECT id, email, user_id, display_name, quota, last_login, backend, home, state, password"
|
||||
from := `
|
||||
FROM oc_accounts a
|
||||
LEFT JOIN oc_users u
|
||||
ON a.user_id=u.uid
|
||||
`
|
||||
if joinUsername {
|
||||
sel += ", p.configvalue AS username"
|
||||
from += `LEFT JOIN oc_preferences p
|
||||
ON a.user_id=p.userid
|
||||
AND p.appid='core'
|
||||
AND p.configkey='username'`
|
||||
} else {
|
||||
// fallback to user_id as username
|
||||
sel += ", user_id AS username"
|
||||
}
|
||||
if joinUUID {
|
||||
sel += ", p2.configvalue AS ownclouduuid"
|
||||
from += `LEFT JOIN oc_preferences p2
|
||||
ON a.user_id=p2.userid
|
||||
AND p2.appid='core'
|
||||
AND p2.configkey='ownclouduuid'`
|
||||
} else {
|
||||
// fallback to user_id as ownclouduuid
|
||||
sel += ", user_id AS ownclouduuid"
|
||||
}
|
||||
|
||||
return &Accounts{
|
||||
driver: driver,
|
||||
db: sqldb,
|
||||
joinUsername: joinUsername,
|
||||
joinUUID: joinUUID,
|
||||
enableMedialSearch: enableMedialSearch,
|
||||
selectSQL: sel + from,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Account stores information about accounts.
|
||||
type Account struct {
|
||||
ID uint64
|
||||
Email sql.NullString
|
||||
UserID string
|
||||
DisplayName sql.NullString
|
||||
Quota sql.NullString
|
||||
LastLogin int
|
||||
Backend string
|
||||
Home string
|
||||
State int8
|
||||
PasswordHash string // from oc_users
|
||||
Username sql.NullString // optional comes from the oc_preferences
|
||||
OwnCloudUUID sql.NullString // optional comes from the oc_preferences
|
||||
}
|
||||
|
||||
func (as *Accounts) rowToAccount(ctx context.Context, row Scannable) (*Account, error) {
|
||||
a := Account{}
|
||||
if err := row.Scan(&a.ID, &a.Email, &a.UserID, &a.DisplayName, &a.Quota, &a.LastLogin, &a.Backend, &a.Home, &a.State, &a.PasswordHash, &a.Username, &a.OwnCloudUUID); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("could not scan row, skipping")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// Scannable describes the interface providing a Scan method
|
||||
type Scannable interface {
|
||||
Scan(...interface{}) error
|
||||
}
|
||||
|
||||
// GetAccountByLogin fetches an account by mail or username
|
||||
func (as *Accounts) GetAccountByLogin(ctx context.Context, login string) (*Account, error) {
|
||||
var row *sql.Row
|
||||
username := strings.ToLower(login) // usernames are lowercased in owncloud classic
|
||||
if as.joinUsername {
|
||||
row = as.db.QueryRowContext(ctx, as.selectSQL+" WHERE a.email=? OR a.lower_user_id=? OR p.configvalue=?", login, username, login)
|
||||
} else {
|
||||
row = as.db.QueryRowContext(ctx, as.selectSQL+" WHERE a.email=? OR a.lower_user_id=?", login, username)
|
||||
}
|
||||
|
||||
return as.rowToAccount(ctx, row)
|
||||
}
|
||||
|
||||
// GetAccountGroups reads the groups for an account
|
||||
func (as *Accounts) GetAccountGroups(ctx context.Context, uid string) ([]string, error) {
|
||||
rows, err := as.db.QueryContext(ctx, "SELECT gid FROM oc_group_user WHERE uid=?", uid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var group string
|
||||
groups := []string{}
|
||||
for rows.Next() {
|
||||
if err := rows.Scan(&group); err != nil {
|
||||
appctx.GetLogger(ctx).Error().Err(err).Msg("could not scan row, skipping")
|
||||
continue
|
||||
}
|
||||
groups = append(groups, group)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return groups, nil
|
||||
}
|
||||
Generated
Vendored
BIN
Binary file not shown.
-192
@@ -1,192 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
authpb "github.com/cs3org/go-cs3apis/cs3/auth/provider/v1beta1"
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"github.com/owncloud/reva/v2/pkg/auth"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/manager/owncloudsql/accounts"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/manager/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/auth/scope"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
// Provides mysql drivers
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
func init() {
|
||||
registry.Register("owncloudsql", NewMysql)
|
||||
}
|
||||
|
||||
type manager struct {
|
||||
c *config
|
||||
db *accounts.Accounts
|
||||
}
|
||||
|
||||
type config struct {
|
||||
DbUsername string `mapstructure:"dbusername"`
|
||||
DbPassword string `mapstructure:"dbpassword"`
|
||||
DbHost string `mapstructure:"dbhost"`
|
||||
DbPort int `mapstructure:"dbport"`
|
||||
DbName string `mapstructure:"dbname"`
|
||||
Idp string `mapstructure:"idp"`
|
||||
Nobody int64 `mapstructure:"nobody"`
|
||||
LegacySalt string `mapstructure:"legacy_salt"`
|
||||
JoinUsername bool `mapstructure:"join_username"`
|
||||
JoinOwnCloudUUID bool `mapstructure:"join_ownclouduuid"`
|
||||
}
|
||||
|
||||
// NewMysql returns a new auth manager connection to an owncloud mysql database
|
||||
func NewMysql(m map[string]interface{}) (auth.Manager, error) {
|
||||
mgr := &manager{}
|
||||
err := mgr.Configure(m)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "error creating a new auth manager")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mgr.db, err = accounts.NewMysql(
|
||||
fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mgr.c.DbUsername, mgr.c.DbPassword, mgr.c.DbHost, mgr.c.DbPort, mgr.c.DbName),
|
||||
mgr.c.JoinUsername,
|
||||
mgr.c.JoinOwnCloudUUID,
|
||||
false,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return mgr, nil
|
||||
}
|
||||
|
||||
func (m *manager) Configure(ml map[string]interface{}) error {
|
||||
c, err := parseConfig(ml)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if c.Nobody == 0 {
|
||||
c.Nobody = 99
|
||||
}
|
||||
|
||||
m.c = c
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseConfig(m map[string]interface{}) (*config, error) {
|
||||
c := &config{}
|
||||
if err := mapstructure.Decode(m, &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *manager) Authenticate(ctx context.Context, login, clientSecret string) (*user.User, map[string]*authpb.Scope, error) {
|
||||
log := appctx.GetLogger(ctx)
|
||||
|
||||
// 1. find user by login
|
||||
|
||||
account, err := m.db.GetAccountByLogin(ctx, login)
|
||||
if err != nil {
|
||||
return nil, nil, errtypes.NotFound(login)
|
||||
}
|
||||
// 2. verify the user password
|
||||
if !m.verify(clientSecret, account.PasswordHash) {
|
||||
return nil, nil, errtypes.InvalidCredentials(login)
|
||||
}
|
||||
|
||||
userID := &user.UserId{
|
||||
Idp: m.c.Idp,
|
||||
OpaqueId: account.OwnCloudUUID.String,
|
||||
Type: user.UserType_USER_TYPE_PRIMARY, // TODO: assign the appropriate user type for guest accounts
|
||||
}
|
||||
|
||||
u := &user.User{
|
||||
Id: userID,
|
||||
// TODO add more claims from the StandardClaims, eg EmailVerified and lastlogin
|
||||
Username: account.Username.String,
|
||||
Mail: account.Email.String,
|
||||
DisplayName: account.DisplayName.String,
|
||||
//UidNumber: uidNumber,
|
||||
//GidNumber: gidNumber,
|
||||
}
|
||||
|
||||
if u.Groups, err = m.db.GetAccountGroups(ctx, account.UserID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var scopes map[string]*authpb.Scope
|
||||
if userID != nil && (userID.Type == user.UserType_USER_TYPE_LIGHTWEIGHT || userID.Type == user.UserType_USER_TYPE_FEDERATED) {
|
||||
scopes, err = scope.AddLightweightAccountScope(authpb.Role_ROLE_OWNER, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
} else {
|
||||
scopes, err = scope.AddOwnerScope(nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
// do not log password hash
|
||||
account.PasswordHash = "***redacted***"
|
||||
log.Debug().Interface("account", account).Interface("user", u).Msg("authenticated user")
|
||||
|
||||
return u, scopes, nil
|
||||
}
|
||||
|
||||
func (m *manager) verify(password, hash string) bool {
|
||||
splitHash := strings.SplitN(hash, "|", 2)
|
||||
switch len(splitHash) {
|
||||
case 2:
|
||||
if splitHash[0] == "1" {
|
||||
return m.verifyHashV1(password, splitHash[1])
|
||||
}
|
||||
case 1:
|
||||
return m.legacyHashVerify(password, hash)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *manager) legacyHashVerify(password, hash string) bool {
|
||||
// TODO rehash $newHash = $this->hash($message);
|
||||
switch len(hash) {
|
||||
case 60: // legacy PHPass hash
|
||||
return nil == bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+m.c.LegacySalt))
|
||||
case 40: // legacy sha1 hash
|
||||
h := sha1.Sum([]byte(password))
|
||||
return hmac.Equal([]byte(hash), []byte(hex.EncodeToString(h[:])))
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (m *manager) verifyHashV1(password, hash string) bool {
|
||||
// TODO implement password_needs_rehash
|
||||
return nil == bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
}
|
||||
-1
@@ -23,6 +23,5 @@ import (
|
||||
_ "github.com/owncloud/reva/v2/pkg/publicshare/manager/cs3"
|
||||
_ "github.com/owncloud/reva/v2/pkg/publicshare/manager/json"
|
||||
_ "github.com/owncloud/reva/v2/pkg/publicshare/manager/memory"
|
||||
_ "github.com/owncloud/reva/v2/pkg/publicshare/manager/owncloudsql"
|
||||
// Add your own here
|
||||
)
|
||||
Generated
Vendored
-226
@@ -1,226 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/jellydator/ttlcache/v2"
|
||||
)
|
||||
|
||||
// DBShare stores information about user and public shares.
|
||||
type DBShare struct {
|
||||
ID string
|
||||
UIDOwner string
|
||||
UIDInitiator string
|
||||
ItemStorage string
|
||||
FileSource string
|
||||
ItemType string // 'file' or 'folder'
|
||||
ShareWith string
|
||||
Token string
|
||||
Expiration string
|
||||
Permissions int
|
||||
ShareType int
|
||||
ShareName string
|
||||
STime int
|
||||
FileTarget string
|
||||
RejectedBy string
|
||||
State int
|
||||
Parent int
|
||||
}
|
||||
|
||||
// UserConverter describes an interface for converting user ids to names and back
|
||||
type UserConverter interface {
|
||||
UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error)
|
||||
UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error)
|
||||
}
|
||||
|
||||
// GatewayUserConverter converts usernames and ids using the gateway
|
||||
type GatewayUserConverter struct {
|
||||
gwAddr string
|
||||
|
||||
IDCache *ttlcache.Cache
|
||||
NameCache *ttlcache.Cache
|
||||
}
|
||||
|
||||
// NewGatewayUserConverter returns a instance of GatewayUserConverter
|
||||
func NewGatewayUserConverter(gwAddr string) *GatewayUserConverter {
|
||||
IDCache := ttlcache.NewCache()
|
||||
_ = IDCache.SetTTL(30 * time.Second)
|
||||
IDCache.SkipTTLExtensionOnHit(true)
|
||||
NameCache := ttlcache.NewCache()
|
||||
_ = NameCache.SetTTL(30 * time.Second)
|
||||
NameCache.SkipTTLExtensionOnHit(true)
|
||||
|
||||
return &GatewayUserConverter{
|
||||
gwAddr: gwAddr,
|
||||
IDCache: IDCache,
|
||||
NameCache: NameCache,
|
||||
}
|
||||
}
|
||||
|
||||
// UserIDToUserName converts a user ID to an username
|
||||
func (c *GatewayUserConverter) UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error) {
|
||||
username, err := c.NameCache.Get(userid.String())
|
||||
if err == nil {
|
||||
return username.(string), nil
|
||||
}
|
||||
|
||||
gwConn, err := pool.GetGatewayServiceClient(c.gwAddr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
getUserResponse, err := gwConn.GetUser(ctx, &userpb.GetUserRequest{
|
||||
UserId: userid,
|
||||
SkipFetchingUserGroups: true,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if getUserResponse.Status.Code != rpc.Code_CODE_OK {
|
||||
return "", status.NewErrorFromCode(getUserResponse.Status.Code, "gateway")
|
||||
}
|
||||
_ = c.NameCache.Set(userid.String(), getUserResponse.User.Username)
|
||||
return getUserResponse.User.Username, nil
|
||||
}
|
||||
|
||||
// UserNameToUserID converts a username to an user ID
|
||||
func (c *GatewayUserConverter) UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error) {
|
||||
id, err := c.IDCache.Get(username)
|
||||
if err == nil {
|
||||
return id.(*userpb.UserId), nil
|
||||
}
|
||||
|
||||
gwConn, err := pool.GetGatewayServiceClient(c.gwAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
getUserResponse, err := gwConn.GetUserByClaim(ctx, &userpb.GetUserByClaimRequest{
|
||||
Claim: "username",
|
||||
Value: username,
|
||||
SkipFetchingUserGroups: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if getUserResponse.Status.Code != rpc.Code_CODE_OK {
|
||||
return nil, status.NewErrorFromCode(getUserResponse.Status.Code, "gateway")
|
||||
}
|
||||
_ = c.IDCache.Set(username, getUserResponse.User.Id)
|
||||
return getUserResponse.User.Id, nil
|
||||
}
|
||||
|
||||
func resourceTypeToItem(r provider.ResourceType) string {
|
||||
switch r {
|
||||
case provider.ResourceType_RESOURCE_TYPE_FILE:
|
||||
return "file"
|
||||
case provider.ResourceType_RESOURCE_TYPE_CONTAINER:
|
||||
return "folder"
|
||||
case provider.ResourceType_RESOURCE_TYPE_REFERENCE:
|
||||
return "reference"
|
||||
case provider.ResourceType_RESOURCE_TYPE_SYMLINK:
|
||||
return "symlink"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func sharePermToInt(p *provider.ResourcePermissions) int {
|
||||
return int(conversions.RoleFromResourcePermissions(p, true).OCSPermissions())
|
||||
}
|
||||
|
||||
func intTosharePerm(p int) (*provider.ResourcePermissions, error) {
|
||||
perms, err := conversions.NewPermissions(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return conversions.RoleFromOCSPermissions(perms, nil).CS3ResourcePermissions(), nil
|
||||
}
|
||||
|
||||
func formatUserID(u *userpb.UserId) string {
|
||||
return u.OpaqueId
|
||||
}
|
||||
|
||||
// ConvertToCS3PublicShare converts a DBShare to a CS3API public share
|
||||
func (m *mgr) ConvertToCS3PublicShare(ctx context.Context, s DBShare) (*link.PublicShare, error) {
|
||||
ts := &typespb.Timestamp{
|
||||
Seconds: uint64(s.STime),
|
||||
}
|
||||
permissions, err := intTosharePerm(s.Permissions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner, err := m.userConverter.UserNameToUserID(ctx, s.UIDOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var creator *userpb.UserId
|
||||
if s.UIDOwner == s.UIDInitiator {
|
||||
creator = owner
|
||||
} else {
|
||||
creator, err = m.userConverter.UserNameToUserID(ctx, s.UIDOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
pwd := false
|
||||
if s.ShareWith != "" {
|
||||
pwd = true
|
||||
}
|
||||
var expires *typespb.Timestamp
|
||||
if s.Expiration != "" {
|
||||
t, err := time.Parse("2006-01-02 15:04:05", s.Expiration)
|
||||
if err != nil {
|
||||
t, err = time.Parse("2006-01-02 15:04:05-07:00", s.Expiration)
|
||||
}
|
||||
if err == nil {
|
||||
expires = &typespb.Timestamp{
|
||||
Seconds: uint64(t.Unix()),
|
||||
}
|
||||
}
|
||||
}
|
||||
return &link.PublicShare{
|
||||
Id: &link.PublicShareId{
|
||||
OpaqueId: s.ID,
|
||||
},
|
||||
ResourceId: &provider.ResourceId{
|
||||
SpaceId: s.ItemStorage,
|
||||
OpaqueId: s.FileSource,
|
||||
},
|
||||
Permissions: &link.PublicSharePermissions{Permissions: permissions},
|
||||
Owner: owner,
|
||||
Creator: creator,
|
||||
Token: s.Token,
|
||||
DisplayName: s.ShareName,
|
||||
PasswordProtected: pwd,
|
||||
Expiration: expires,
|
||||
Ctime: ts,
|
||||
Mtime: ts,
|
||||
}, nil
|
||||
}
|
||||
Generated
Vendored
-533
@@ -1,533 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
// Package owncloudsql implements a publiclink share manager backed by an existing ownCloud 10 database
|
||||
//
|
||||
// The SQL queries use `coalesce({column_identifier}, ”) as {column_identifier}` to read an emptystring
|
||||
// instead of null values, which better fits the golang default values.
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/publicshare"
|
||||
"github.com/owncloud/reva/v2/pkg/publicshare/manager/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/sharedconf"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
// Provides mysql drivers
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
const (
|
||||
publicShareType = 3
|
||||
)
|
||||
|
||||
func init() {
|
||||
registry.Register("owncloudsql", NewMysql)
|
||||
}
|
||||
|
||||
// Config configures an owncloudsql publicshare manager
|
||||
type Config struct {
|
||||
GatewayAddr string `mapstructure:"gateway_addr"`
|
||||
DbUsername string `mapstructure:"db_username"`
|
||||
DbPassword string `mapstructure:"db_password"`
|
||||
DbHost string `mapstructure:"db_host"`
|
||||
DbPort int `mapstructure:"db_port"`
|
||||
DbName string `mapstructure:"db_name"`
|
||||
EnableExpiredSharesCleanup bool `mapstructure:"enable_expired_shares_cleanup"`
|
||||
SharePasswordHashCost int `mapstructure:"password_hash_cost"`
|
||||
}
|
||||
|
||||
type mgr struct {
|
||||
driver string
|
||||
db *sql.DB
|
||||
c Config
|
||||
userConverter UserConverter
|
||||
}
|
||||
|
||||
// NewMysql returns a new publicshare manager connection to a mysql database
|
||||
func NewMysql(m map[string]interface{}) (publicshare.Manager, error) {
|
||||
c, err := parseConfig(m)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "error creating a new manager")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userConverter := NewGatewayUserConverter(sharedconf.GetGatewaySVC(c.GatewayAddr))
|
||||
|
||||
return New("mysql", db, *c, userConverter)
|
||||
}
|
||||
|
||||
// New returns a new Cache instance connecting to the given sql.DB
|
||||
func New(driver string, db *sql.DB, c Config, userConverter UserConverter) (publicshare.Manager, error) {
|
||||
if c.SharePasswordHashCost == 0 {
|
||||
c.SharePasswordHashCost = bcrypt.DefaultCost
|
||||
}
|
||||
return &mgr{
|
||||
driver: driver,
|
||||
db: db,
|
||||
c: c,
|
||||
userConverter: userConverter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseConfig(m map[string]interface{}) (*Config, error) {
|
||||
c := &Config{}
|
||||
if err := mapstructure.Decode(m, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *mgr) CreatePublicShare(ctx context.Context, u *user.User, rInfo *provider.ResourceInfo, g *link.Grant) (*link.PublicShare, error) {
|
||||
|
||||
tkn := utils.RandString(15)
|
||||
now := time.Now().Unix()
|
||||
|
||||
displayName := tkn
|
||||
if rInfo.ArbitraryMetadata != nil && rInfo.ArbitraryMetadata.Metadata["name"] != "" {
|
||||
displayName = rInfo.ArbitraryMetadata.Metadata["name"]
|
||||
}
|
||||
createdAt := &typespb.Timestamp{
|
||||
Seconds: uint64(now),
|
||||
}
|
||||
|
||||
creator := u.Username
|
||||
owner, err := m.userConverter.UserIDToUserName(ctx, rInfo.Owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
permissions := sharePermToInt(g.Permissions.Permissions)
|
||||
itemType := resourceTypeToItem(rInfo.Type)
|
||||
|
||||
itemSource := rInfo.Id.OpaqueId
|
||||
fileSource, err := strconv.ParseUint(itemSource, 10, 64)
|
||||
if err != nil {
|
||||
// it can be the case that the item source may be a character string
|
||||
// we leave fileSource blank in that case
|
||||
fileSource = 0
|
||||
}
|
||||
|
||||
columns := "share_type,uid_owner,uid_initiator,item_type,item_source,file_source,permissions,stime,token,share_name"
|
||||
placeholders := "?,?,?,?,?,?,?,?,?,?"
|
||||
params := []interface{}{publicShareType, owner, creator, itemType, itemSource, fileSource, permissions, now, tkn, displayName}
|
||||
|
||||
var passwordProtected bool
|
||||
password := g.Password
|
||||
if password != "" {
|
||||
password, err = hashPassword(password, m.c.SharePasswordHashCost)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not hash share password")
|
||||
}
|
||||
passwordProtected = true
|
||||
|
||||
columns += ",share_with"
|
||||
placeholders += ",?"
|
||||
params = append(params, password)
|
||||
}
|
||||
|
||||
if g.Expiration != nil && g.Expiration.Seconds != 0 {
|
||||
t := time.Unix(int64(g.Expiration.Seconds), 0)
|
||||
columns += ",expiration"
|
||||
placeholders += ",?"
|
||||
params = append(params, t)
|
||||
}
|
||||
|
||||
query := "INSERT INTO oc_share (" + columns + ") VALUES (" + placeholders + ")"
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := stmt.Exec(params...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lastID, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &link.PublicShare{
|
||||
Id: &link.PublicShareId{
|
||||
OpaqueId: strconv.FormatInt(lastID, 10),
|
||||
},
|
||||
Owner: rInfo.GetOwner(),
|
||||
Creator: u.Id,
|
||||
ResourceId: rInfo.Id,
|
||||
Token: tkn,
|
||||
Permissions: g.Permissions,
|
||||
Ctime: createdAt,
|
||||
Mtime: createdAt,
|
||||
PasswordProtected: passwordProtected,
|
||||
Expiration: g.Expiration,
|
||||
DisplayName: displayName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// owncloud 10 prefixes the hash with `1|`
|
||||
func hashPassword(password string, cost int) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
|
||||
return "1|" + string(bytes), err
|
||||
}
|
||||
|
||||
// UpdatePublicShare updates the expiration date, permissions and Mtime
|
||||
func (m *mgr) UpdatePublicShare(ctx context.Context, u *user.User, req *link.UpdatePublicShareRequest) (*link.PublicShare, error) {
|
||||
query := "update oc_share set "
|
||||
paramsMap := map[string]interface{}{}
|
||||
params := []interface{}{}
|
||||
|
||||
now := time.Now().Unix()
|
||||
uid := u.Username
|
||||
|
||||
switch req.GetUpdate().GetType() {
|
||||
case link.UpdatePublicShareRequest_Update_TYPE_DISPLAYNAME:
|
||||
paramsMap["share_name"] = req.Update.GetDisplayName()
|
||||
case link.UpdatePublicShareRequest_Update_TYPE_PERMISSIONS:
|
||||
paramsMap["permissions"] = sharePermToInt(req.Update.GetGrant().GetPermissions().Permissions)
|
||||
case link.UpdatePublicShareRequest_Update_TYPE_EXPIRATION:
|
||||
paramsMap["expiration"] = time.Unix(int64(req.Update.GetGrant().Expiration.Seconds), 0)
|
||||
case link.UpdatePublicShareRequest_Update_TYPE_PASSWORD:
|
||||
if req.Update.GetGrant().Password == "" {
|
||||
paramsMap["share_with"] = ""
|
||||
} else {
|
||||
h, err := hashPassword(req.Update.GetGrant().Password, m.c.SharePasswordHashCost)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not hash share password")
|
||||
}
|
||||
paramsMap["share_with"] = h
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid update type: %v", req.GetUpdate().GetType())
|
||||
}
|
||||
|
||||
for k, v := range paramsMap {
|
||||
query += k + "=?"
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
switch {
|
||||
case req.Ref.GetId() != nil:
|
||||
query += ",stime=? where id=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, now, req.Ref.GetId().OpaqueId, uid, uid)
|
||||
case req.Ref.GetToken() != "":
|
||||
query += ",stime=? where token=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, now, req.Ref.GetToken(), uid, uid)
|
||||
default:
|
||||
return nil, errtypes.NotFound(req.Ref.String())
|
||||
}
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = stmt.Exec(params...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m.GetPublicShare(ctx, u, req.Ref, false)
|
||||
}
|
||||
|
||||
func (m *mgr) GetPublicShare(ctx context.Context, u *user.User, ref *link.PublicShareReference, sign bool) (share *link.PublicShare, err error) {
|
||||
|
||||
ps, err := m.getWithPassword(ctx, ref)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if publicshare.IsExpired(&ps.PublicShare) {
|
||||
if err := m.cleanupExpiredShares(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errtypes.NotFound("public share has expired")
|
||||
}
|
||||
|
||||
if ps.PublicShare.PasswordProtected && sign {
|
||||
err = publicshare.AddSignature(&ps.PublicShare, ps.Password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &ps.PublicShare, nil
|
||||
}
|
||||
|
||||
func (m *mgr) getWithPassword(ctx context.Context, ref *link.PublicShareReference) (*publicshare.WithPassword, error) {
|
||||
switch {
|
||||
case ref.GetToken() != "":
|
||||
return m.getByToken(ctx, ref.GetToken())
|
||||
case ref.GetId().GetOpaqueId() != "":
|
||||
return m.getByID(ctx, ref.GetId().GetOpaqueId())
|
||||
default:
|
||||
return nil, errtypes.BadRequest("neither id nor token given")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *mgr) getByToken(ctx context.Context, token string) (*publicshare.WithPassword, error) {
|
||||
s, err := getByToken(m.db, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ps, err := m.ConvertToCS3PublicShare(ctx, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := &publicshare.WithPassword{
|
||||
Password: strings.TrimPrefix(s.ShareWith, "1|"),
|
||||
}
|
||||
proto.Merge(&ret.PublicShare, ps)
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func getByToken(db *sql.DB, token string) (DBShare, error) {
|
||||
s := DBShare{Token: token}
|
||||
query := `SELECT
|
||||
coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator,
|
||||
coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source,
|
||||
coalesce(item_type, '') as item_type,
|
||||
coalesce(expiration, '') as expiration, coalesce(share_name, '') as share_name,
|
||||
s.id, s.stime, s.permissions, fc.storage as storage
|
||||
FROM oc_share s
|
||||
LEFT JOIN oc_filecache fc ON fc.fileid = file_source
|
||||
WHERE share_type=? AND token=?`
|
||||
if err := db.QueryRow(query, publicShareType, token).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.ItemType, &s.Expiration, &s.ShareName, &s.ID, &s.STime, &s.Permissions, &s.ItemStorage); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return s, errtypes.NotFound(token)
|
||||
}
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *mgr) getByID(ctx context.Context, id string) (*publicshare.WithPassword, error) {
|
||||
s := DBShare{ID: id}
|
||||
query := `SELECT
|
||||
coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator,
|
||||
coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source,
|
||||
coalesce(item_type, '') as item_type, coalesce(token,'') as token,
|
||||
coalesce(expiration, '') as expiration, coalesce(share_name, '') as share_name,
|
||||
s.stime, s.permissions, fc.storage as storage
|
||||
FROM oc_share s
|
||||
LEFT JOIN oc_filecache fc ON fc.fileid = file_source
|
||||
WHERE share_type=? AND id=?`
|
||||
if err := m.db.QueryRow(query, publicShareType, id).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.ItemType, &s.Token, &s.Expiration, &s.ShareName, &s.STime, &s.Permissions, &s.ItemStorage); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, errtypes.NotFound(id)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
ps, err := m.ConvertToCS3PublicShare(ctx, s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret := &publicshare.WithPassword{
|
||||
Password: strings.TrimPrefix(s.ShareWith, "1|"),
|
||||
}
|
||||
proto.Merge(&ret.PublicShare, ps)
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (m *mgr) ListPublicShares(ctx context.Context, u *user.User, filters []*link.ListPublicSharesRequest_Filter, sign bool) ([]*link.PublicShare, error) {
|
||||
uid := u.Username
|
||||
// FIXME instead of joining we may want to have to do a stat call ... if we want to store shares from other providers? or just Dump()? and be done with migration?
|
||||
query := `SELECT
|
||||
coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator,
|
||||
coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source,
|
||||
coalesce(item_type, '') as item_type, coalesce(token,'') as token,
|
||||
coalesce(expiration, '') as expiration, coalesce(share_name, '') as share_name,
|
||||
s.id, s.stime, s.permissions, fc.storage as storage
|
||||
FROM oc_share s
|
||||
LEFT JOIN oc_filecache fc ON fc.fileid = file_source
|
||||
WHERE (uid_owner=? or uid_initiator=?)
|
||||
AND (share_type=?)`
|
||||
var resourceFilters, ownerFilters, creatorFilters, storageFilters string
|
||||
var resourceParams, ownerParams, creatorParams, storageParams []interface{}
|
||||
params := []interface{}{uid, uid, publicShareType}
|
||||
|
||||
for _, f := range filters {
|
||||
switch f.Type {
|
||||
case link.ListPublicSharesRequest_Filter_TYPE_RESOURCE_ID:
|
||||
if len(resourceFilters) != 0 {
|
||||
resourceFilters += " OR "
|
||||
}
|
||||
resourceFilters += "item_source=?"
|
||||
resourceParams = append(resourceParams, f.GetResourceId().GetOpaqueId())
|
||||
case link.ListPublicSharesRequest_Filter_TYPE_OWNER:
|
||||
if len(ownerFilters) != 0 {
|
||||
ownerFilters += " OR "
|
||||
}
|
||||
ownerFilters += "(uid_owner=?)"
|
||||
ownerParams = append(ownerParams, formatUserID(f.GetOwner()))
|
||||
case link.ListPublicSharesRequest_Filter_TYPE_CREATOR:
|
||||
if len(creatorFilters) != 0 {
|
||||
creatorFilters += " OR "
|
||||
}
|
||||
creatorFilters += "(uid_initiator=?)"
|
||||
creatorParams = append(creatorParams, formatUserID(f.GetCreator()))
|
||||
case publicshare.StorageIDFilterType:
|
||||
if len(storageFilters) != 0 {
|
||||
storageFilters += " OR "
|
||||
}
|
||||
storageFilters += "(storage=?)"
|
||||
storageParams = append(storageParams, f.GetResourceId().GetStorageId())
|
||||
}
|
||||
}
|
||||
if resourceFilters != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, resourceFilters)
|
||||
params = append(params, resourceParams...)
|
||||
}
|
||||
if ownerFilters != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, ownerFilters)
|
||||
params = append(params, ownerParams...)
|
||||
}
|
||||
if creatorFilters != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, creatorFilters)
|
||||
params = append(params, creatorParams...)
|
||||
}
|
||||
if storageFilters != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, storageFilters)
|
||||
params = append(params, storageParams...)
|
||||
}
|
||||
|
||||
rows, err := m.db.Query(query, params...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var s DBShare
|
||||
shares := []*link.PublicShare{}
|
||||
for rows.Next() {
|
||||
if err := rows.Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.ItemType, &s.Token, &s.Expiration, &s.ShareName, &s.ID, &s.STime, &s.Permissions, &s.ItemStorage); err != nil {
|
||||
continue
|
||||
}
|
||||
var cs3Share *link.PublicShare
|
||||
if cs3Share, err = m.ConvertToCS3PublicShare(ctx, s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if publicshare.IsExpired(cs3Share) {
|
||||
_ = m.cleanupExpiredShares()
|
||||
} else {
|
||||
if cs3Share.PasswordProtected && sign {
|
||||
if err := publicshare.AddSignature(cs3Share, strings.TrimPrefix(s.ShareWith, "1|")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
shares = append(shares, cs3Share)
|
||||
}
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
func (m *mgr) RevokePublicShare(ctx context.Context, u *user.User, ref *link.PublicShareReference) error {
|
||||
uid := u.Username
|
||||
query := "delete from oc_share where "
|
||||
params := []interface{}{}
|
||||
|
||||
switch {
|
||||
case ref.GetId() != nil && ref.GetId().OpaqueId != "":
|
||||
query += "id=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, ref.GetId().OpaqueId, uid, uid)
|
||||
case ref.GetToken() != "":
|
||||
query += "token=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, ref.GetToken(), uid, uid)
|
||||
default:
|
||||
return errtypes.NotFound(ref.String())
|
||||
}
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := stmt.Exec(params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowCnt, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rowCnt == 0 {
|
||||
return errtypes.NotFound(ref.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mgr) GetPublicShareByToken(ctx context.Context, token string, auth *link.PublicShareAuthentication, sign bool) (*link.PublicShare, error) {
|
||||
ps, err := m.getByToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if publicshare.IsExpired(&ps.PublicShare) {
|
||||
if err := m.cleanupExpiredShares(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errtypes.NotFound("public share has expired")
|
||||
}
|
||||
|
||||
if ps.PublicShare.PasswordProtected {
|
||||
if !publicshare.Authenticate(&ps.PublicShare, ps.Password, auth) {
|
||||
return nil, errtypes.InvalidCredentials("access denied")
|
||||
}
|
||||
}
|
||||
|
||||
return &ps.PublicShare, nil
|
||||
}
|
||||
|
||||
func (m *mgr) cleanupExpiredShares() error {
|
||||
if !m.c.EnableExpiredSharesCleanup {
|
||||
return nil
|
||||
}
|
||||
|
||||
query := "DELETE FROM oc_share WHERE expiration IS NOT NULL AND expiration < ?"
|
||||
params := []interface{}{time.Now().Format("2006-01-02 03:04:05")}
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = stmt.Exec(params...); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
BIN
Binary file not shown.
+98
-22
@@ -20,6 +20,7 @@ package pool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -45,7 +46,9 @@ import (
|
||||
"github.com/owncloud/reva/v2/pkg/registry"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sercand/kuberesolver/v5"
|
||||
mRegistry "go-micro.dev/v4/registry"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/connectivity"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -82,6 +85,27 @@ func GetSelector[T any](k string, id string, f func(cc grpc.ClientConnInterface)
|
||||
return newSelector
|
||||
}
|
||||
|
||||
// cachedClient pairs a grpc client with the connection backing it, so Next
|
||||
// can check the connection's health before handing the client back out.
|
||||
type cachedClient[T any] struct {
|
||||
conn *grpc.ClientConn
|
||||
client T
|
||||
}
|
||||
|
||||
// healthy reports whether the cached connection is safe to hand out again.
|
||||
// A connection only becomes TransientFailure or Shutdown after a real RPC on
|
||||
// it has already failed - a connection that was never used for an RPC stays
|
||||
// Idle, so it is treated as healthy here (there is no way to probe
|
||||
// reachability without using it).
|
||||
func (c cachedClient[T]) healthy() bool {
|
||||
switch c.conn.GetState() {
|
||||
case connectivity.TransientFailure, connectivity.Connecting, connectivity.Shutdown:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
type Selector[T any] struct {
|
||||
id string
|
||||
clientFactory func(cc grpc.ClientConnInterface) T
|
||||
@@ -101,47 +125,99 @@ func (s *Selector[T]) Next(opts ...Option) (T, error) {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
target := s.id
|
||||
// if the target is given as a recognized gRPC URI, skip registry lookup
|
||||
// see https://github.com/grpc/grpc/blob/master/doc/naming.md#name-syntax
|
||||
prefix := strings.SplitN(s.id, ":", 2)[0]
|
||||
switch {
|
||||
case prefix == "dns":
|
||||
fallthrough
|
||||
case prefix == "unix":
|
||||
fallthrough
|
||||
case prefix == "kubernetes":
|
||||
// use target as is and skip registry lookup
|
||||
case prefix == "dns", prefix == "unix", prefix == "kubernetes":
|
||||
// use the id as is and skip registry lookup
|
||||
return s.loadOrNewClient(s.id, allOpts)
|
||||
case options.registry != nil:
|
||||
// use service registry to look up address
|
||||
// use the service registry to look up every known node, and pick
|
||||
// the first one that is ready
|
||||
services, err := options.registry.GetService(s.id)
|
||||
if err != nil {
|
||||
return *new(T), fmt.Errorf("%s: %w", s.id, err)
|
||||
}
|
||||
|
||||
nodeAddress, err := registry.GetNodeAddress(services)
|
||||
if err != nil {
|
||||
return *new(T), fmt.Errorf("%s: %w", s.id, err)
|
||||
}
|
||||
target = nodeAddress
|
||||
targets := shuffledTargets(services)
|
||||
return s.nextHealthy(targets, allOpts)
|
||||
default:
|
||||
// if no registry is available, use the target as is
|
||||
// if no registry is available, use the id as is
|
||||
return s.loadOrNewClient(s.id, allOpts)
|
||||
}
|
||||
}
|
||||
|
||||
// nextHealthy walks targets in the given order. It returns the client for
|
||||
// the first target that is ready. A target with no cache entry is also a
|
||||
// candidate, since Next has no way to know its state without dialing it. If
|
||||
// no target is ready, nextHealthy reuses the first one found, so the caller
|
||||
// gets a real error from a real attempt instead of a fabricated one.
|
||||
func (s *Selector[T]) nextHealthy(targets []string, opts []Option) (T, error) {
|
||||
if len(targets) == 0 {
|
||||
return *new(T), fmt.Errorf("%s: no nodes found in registry", s.id)
|
||||
}
|
||||
var fallback *cachedClient[T]
|
||||
for _, target := range targets {
|
||||
cached, ok := s.clientMap.Load(target)
|
||||
if !ok {
|
||||
return s.newClient(target, opts)
|
||||
}
|
||||
|
||||
cc := cached.(cachedClient[T])
|
||||
if cc.healthy() {
|
||||
return cc.client, nil
|
||||
}
|
||||
if fallback == nil {
|
||||
fallback = &cc
|
||||
}
|
||||
}
|
||||
|
||||
existingClient, ok := s.clientMap.Load(target)
|
||||
if ok {
|
||||
return existingClient.(T), nil
|
||||
}
|
||||
return fallback.client, nil
|
||||
}
|
||||
|
||||
conn, err := NewConn(target, allOpts...)
|
||||
// loadOrNewClient returns the cached client for target, creating a new one if
|
||||
// none exists yet. It does not check health: target was not looked up
|
||||
// through the registry, so there is no alternative node to fall back to.
|
||||
func (s *Selector[T]) loadOrNewClient(target string, opts []Option) (T, error) {
|
||||
if cached, ok := s.clientMap.Load(target); ok {
|
||||
return cached.(cachedClient[T]).client, nil
|
||||
}
|
||||
return s.newClient(target, opts)
|
||||
}
|
||||
|
||||
// newClient creates a new connection to target, wraps it in a client and caches
|
||||
// both under target.
|
||||
func (s *Selector[T]) newClient(target string, opts []Option) (T, error) {
|
||||
conn, err := NewConn(target, opts...)
|
||||
if err != nil {
|
||||
return *new(T), errors.Wrap(err, fmt.Sprintf("could not create connection for %s to %s", s.id, target))
|
||||
}
|
||||
|
||||
newClient := s.clientFactory(conn)
|
||||
s.clientMap.Store(target, newClient)
|
||||
newClient := cachedClient[T]{conn: conn, client: s.clientFactory(conn)}
|
||||
// if another goroutine already created a client for this target, use it instead
|
||||
if existing, loaded := s.clientMap.LoadOrStore(target, newClient); loaded {
|
||||
_ = conn.Close()
|
||||
return existing.(cachedClient[T]).client, nil
|
||||
}
|
||||
|
||||
return newClient, nil
|
||||
return newClient.client, nil
|
||||
}
|
||||
|
||||
// shuffledTargets flattens every node address out of services and returns
|
||||
// them in random order, so repeated calls spread load across all known
|
||||
// nodes instead of always preferring the same one.
|
||||
func shuffledTargets(services []*mRegistry.Service) []string {
|
||||
var targets []string
|
||||
for _, svc := range services {
|
||||
for _, node := range svc.Nodes {
|
||||
targets = append(targets, node.Address)
|
||||
}
|
||||
}
|
||||
rand.Shuffle(len(targets), func(i, j int) {
|
||||
targets[i], targets[j] = targets[j], targets[i]
|
||||
})
|
||||
return targets
|
||||
}
|
||||
|
||||
// GatewaySelector returns a Selector[gateway.GatewayAPIClient].
|
||||
|
||||
-1
@@ -24,6 +24,5 @@ import (
|
||||
_ "github.com/owncloud/reva/v2/pkg/share/manager/json"
|
||||
_ "github.com/owncloud/reva/v2/pkg/share/manager/jsoncs3"
|
||||
_ "github.com/owncloud/reva/v2/pkg/share/manager/memory"
|
||||
_ "github.com/owncloud/reva/v2/pkg/share/manager/owncloudsql"
|
||||
// Add your own here
|
||||
)
|
||||
-301
@@ -1,301 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
grouppb "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
userprovider "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/jellydator/ttlcache/v2"
|
||||
)
|
||||
|
||||
// DBShare stores information about user and public shares.
|
||||
type DBShare struct {
|
||||
ID string
|
||||
UIDOwner string
|
||||
UIDInitiator string
|
||||
ItemStorage string
|
||||
FileSource string
|
||||
ShareWith string
|
||||
Token string
|
||||
Expiration string
|
||||
Permissions int
|
||||
ShareType int
|
||||
ShareName string
|
||||
STime int
|
||||
FileTarget string
|
||||
RejectedBy string
|
||||
State int
|
||||
Parent int
|
||||
}
|
||||
|
||||
// UserConverter describes an interface for converting user ids to names and back
|
||||
type UserConverter interface {
|
||||
UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error)
|
||||
UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error)
|
||||
GetUser(userid *userpb.UserId) (*userpb.User, error)
|
||||
}
|
||||
|
||||
// GatewayUserConverter converts usernames and ids using the gateway
|
||||
type GatewayUserConverter struct {
|
||||
gwAddr string
|
||||
|
||||
IDCache *ttlcache.Cache
|
||||
NameCache *ttlcache.Cache
|
||||
}
|
||||
|
||||
// NewGatewayUserConverter returns a instance of GatewayUserConverter
|
||||
func NewGatewayUserConverter(gwAddr string) *GatewayUserConverter {
|
||||
IDCache := ttlcache.NewCache()
|
||||
_ = IDCache.SetTTL(30 * time.Second)
|
||||
IDCache.SkipTTLExtensionOnHit(true)
|
||||
NameCache := ttlcache.NewCache()
|
||||
_ = NameCache.SetTTL(30 * time.Second)
|
||||
NameCache.SkipTTLExtensionOnHit(true)
|
||||
|
||||
return &GatewayUserConverter{
|
||||
gwAddr: gwAddr,
|
||||
IDCache: IDCache,
|
||||
NameCache: NameCache,
|
||||
}
|
||||
}
|
||||
|
||||
// UserIDToUserName converts a user ID to an username
|
||||
func (c *GatewayUserConverter) UserIDToUserName(ctx context.Context, userid *userpb.UserId) (string, error) {
|
||||
username, err := c.NameCache.Get(userid.String())
|
||||
if err == nil {
|
||||
return username.(string), nil
|
||||
}
|
||||
|
||||
gwConn, err := pool.GetGatewayServiceClient(c.gwAddr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
getUserResponse, err := gwConn.GetUser(ctx, &userprovider.GetUserRequest{
|
||||
UserId: userid,
|
||||
SkipFetchingUserGroups: true,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if getUserResponse.Status.Code != rpc.Code_CODE_OK {
|
||||
return "", status.NewErrorFromCode(getUserResponse.Status.Code, "gateway")
|
||||
}
|
||||
_ = c.NameCache.Set(userid.String(), getUserResponse.User.Username)
|
||||
return getUserResponse.User.Username, nil
|
||||
}
|
||||
|
||||
// UserNameToUserID converts a username to an user ID
|
||||
func (c *GatewayUserConverter) UserNameToUserID(ctx context.Context, username string) (*userpb.UserId, error) {
|
||||
id, err := c.IDCache.Get(username)
|
||||
if err == nil {
|
||||
return id.(*userpb.UserId), nil
|
||||
}
|
||||
|
||||
gwConn, err := pool.GetGatewayServiceClient(c.gwAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
getUserResponse, err := gwConn.GetUserByClaim(ctx, &userpb.GetUserByClaimRequest{
|
||||
Claim: "username",
|
||||
Value: username,
|
||||
SkipFetchingUserGroups: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if getUserResponse.Status.Code != rpc.Code_CODE_OK {
|
||||
return nil, status.NewErrorFromCode(getUserResponse.Status.Code, "gateway")
|
||||
}
|
||||
_ = c.IDCache.Set(username, getUserResponse.User.Id)
|
||||
return getUserResponse.User.Id, nil
|
||||
}
|
||||
|
||||
// GetUser gets the user
|
||||
func (c *GatewayUserConverter) GetUser(userid *userpb.UserId) (*userpb.User, error) {
|
||||
gwc, err := pool.GetGatewayServiceClient(c.gwAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return utils.GetUser(userid, gwc)
|
||||
}
|
||||
|
||||
func (m *mgr) formatGrantee(ctx context.Context, g *provider.Grantee) (int, string, error) {
|
||||
var granteeType int
|
||||
var formattedID string
|
||||
switch g.Type {
|
||||
case provider.GranteeType_GRANTEE_TYPE_USER:
|
||||
granteeType = 0
|
||||
var err error
|
||||
formattedID, err = m.userConverter.UserIDToUserName(ctx, g.GetUserId())
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
case provider.GranteeType_GRANTEE_TYPE_GROUP:
|
||||
granteeType = 1
|
||||
formattedID = formatGroupID(g.GetGroupId())
|
||||
default:
|
||||
granteeType = -1
|
||||
}
|
||||
return granteeType, formattedID, nil
|
||||
}
|
||||
|
||||
func (m *mgr) extractGrantee(ctx context.Context, t int, g string) (*provider.Grantee, error) {
|
||||
var grantee provider.Grantee
|
||||
switch t {
|
||||
case 0:
|
||||
userid, err := m.userConverter.UserNameToUserID(ctx, g)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grantee.Type = provider.GranteeType_GRANTEE_TYPE_USER
|
||||
grantee.Id = &provider.Grantee_UserId{UserId: userid}
|
||||
case 1, 2:
|
||||
grantee.Type = provider.GranteeType_GRANTEE_TYPE_GROUP
|
||||
grantee.Id = &provider.Grantee_GroupId{GroupId: extractGroupID(g)}
|
||||
default:
|
||||
grantee.Type = provider.GranteeType_GRANTEE_TYPE_INVALID
|
||||
}
|
||||
return &grantee, nil
|
||||
}
|
||||
|
||||
func resourceTypeToItem(r provider.ResourceType) string {
|
||||
switch r {
|
||||
case provider.ResourceType_RESOURCE_TYPE_FILE:
|
||||
return "file"
|
||||
case provider.ResourceType_RESOURCE_TYPE_CONTAINER:
|
||||
return "folder"
|
||||
case provider.ResourceType_RESOURCE_TYPE_REFERENCE:
|
||||
return "reference"
|
||||
case provider.ResourceType_RESOURCE_TYPE_SYMLINK:
|
||||
return "symlink"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func sharePermToInt(p *provider.ResourcePermissions) int {
|
||||
return int(conversions.RoleFromResourcePermissions(p, false).OCSPermissions())
|
||||
}
|
||||
|
||||
func intTosharePerm(p int) (*provider.ResourcePermissions, error) {
|
||||
perms, err := conversions.NewPermissions(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return conversions.RoleFromOCSPermissions(perms, nil).CS3ResourcePermissions(), nil
|
||||
}
|
||||
|
||||
func intToShareState(g int) collaboration.ShareState {
|
||||
switch g {
|
||||
case 0:
|
||||
return collaboration.ShareState_SHARE_STATE_ACCEPTED
|
||||
case 1:
|
||||
return collaboration.ShareState_SHARE_STATE_PENDING
|
||||
case 2:
|
||||
return collaboration.ShareState_SHARE_STATE_REJECTED
|
||||
default:
|
||||
return collaboration.ShareState_SHARE_STATE_INVALID
|
||||
}
|
||||
}
|
||||
|
||||
func formatUserID(u *userpb.UserId) string {
|
||||
return u.OpaqueId
|
||||
}
|
||||
|
||||
func formatGroupID(u *grouppb.GroupId) string {
|
||||
return u.OpaqueId
|
||||
}
|
||||
|
||||
func extractGroupID(u string) *grouppb.GroupId {
|
||||
return &grouppb.GroupId{OpaqueId: u}
|
||||
}
|
||||
|
||||
func (m *mgr) convertToCS3Share(ctx context.Context, s DBShare, storageMountID string) (*collaboration.Share, error) {
|
||||
ts := &typespb.Timestamp{
|
||||
Seconds: uint64(s.STime),
|
||||
}
|
||||
permissions, err := intTosharePerm(s.Permissions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grantee, err := m.extractGrantee(ctx, s.ShareType, s.ShareWith)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner, err := m.userConverter.UserNameToUserID(ctx, s.UIDOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var creator *userpb.UserId
|
||||
if s.UIDOwner == s.UIDInitiator {
|
||||
creator = owner
|
||||
} else {
|
||||
creator, err = m.userConverter.UserNameToUserID(ctx, s.UIDOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &collaboration.Share{
|
||||
Id: &collaboration.ShareId{
|
||||
OpaqueId: s.ID,
|
||||
},
|
||||
ResourceId: &provider.ResourceId{
|
||||
SpaceId: s.ItemStorage,
|
||||
OpaqueId: s.FileSource,
|
||||
},
|
||||
Permissions: &collaboration.SharePermissions{Permissions: permissions},
|
||||
Grantee: grantee,
|
||||
Owner: owner,
|
||||
Creator: creator,
|
||||
Ctime: ts,
|
||||
Mtime: ts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *mgr) convertToCS3ReceivedShare(ctx context.Context, s DBShare, storageMountID string) (*collaboration.ReceivedShare, error) {
|
||||
share, err := m.convertToCS3Share(ctx, s, storageMountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var state collaboration.ShareState
|
||||
if s.RejectedBy != "" {
|
||||
state = collaboration.ShareState_SHARE_STATE_REJECTED
|
||||
} else {
|
||||
state = intToShareState(s.State)
|
||||
}
|
||||
return &collaboration.ReceivedShare{
|
||||
Share: share,
|
||||
State: state,
|
||||
MountPoint: &provider.Reference{Path: strings.TrimLeft(s.FileTarget, "/")},
|
||||
}, nil
|
||||
}
|
||||
-674
@@ -1,674 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
|
||||
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/owncloud/reva/v2/pkg/errtypes"
|
||||
"github.com/owncloud/reva/v2/pkg/share"
|
||||
"github.com/owncloud/reva/v2/pkg/share/manager/registry"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/genproto/protobuf/field_mask"
|
||||
|
||||
// Provides mysql drivers
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
const (
|
||||
shareTypeUser = 0
|
||||
shareTypeGroup = 1
|
||||
)
|
||||
|
||||
func init() {
|
||||
registry.Register("owncloudsql", NewMysql)
|
||||
}
|
||||
|
||||
type config struct {
|
||||
GatewayAddr string `mapstructure:"gateway_addr"`
|
||||
StorageMountID string `mapstructure:"storage_mount_id"`
|
||||
DbUsername string `mapstructure:"db_username"`
|
||||
DbPassword string `mapstructure:"db_password"`
|
||||
DbHost string `mapstructure:"db_host"`
|
||||
DbPort int `mapstructure:"db_port"`
|
||||
DbName string `mapstructure:"db_name"`
|
||||
}
|
||||
|
||||
type mgr struct {
|
||||
driver string
|
||||
db *sql.DB
|
||||
storageMountID string
|
||||
userConverter UserConverter
|
||||
}
|
||||
|
||||
// NewMysql returns a new share manager connection to a mysql database
|
||||
func NewMysql(m map[string]interface{}) (share.Manager, error) {
|
||||
c, err := parseConfig(m)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "error creating a new manager")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", c.DbUsername, c.DbPassword, c.DbHost, c.DbPort, c.DbName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userConverter := NewGatewayUserConverter(c.GatewayAddr)
|
||||
|
||||
return New("mysql", db, c.StorageMountID, userConverter)
|
||||
}
|
||||
|
||||
// New returns a new Cache instance connecting to the given sql.DB
|
||||
func New(driver string, db *sql.DB, storageMountID string, userConverter UserConverter) (share.Manager, error) {
|
||||
return &mgr{
|
||||
driver: driver,
|
||||
db: db,
|
||||
storageMountID: storageMountID,
|
||||
userConverter: userConverter,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseConfig(m map[string]interface{}) (*config, error) {
|
||||
c := &config{}
|
||||
if err := mapstructure.Decode(m, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (m *mgr) Share(ctx context.Context, md *provider.ResourceInfo, g *collaboration.ShareGrant) (*collaboration.Share, error) {
|
||||
user := ctxpkg.ContextMustGetUser(ctx)
|
||||
|
||||
// do not allow share to myself or the owner if share is for a user
|
||||
// TODO(labkode): should not this be caught already at the gw level?
|
||||
if g.Grantee.Type == provider.GranteeType_GRANTEE_TYPE_USER &&
|
||||
(utils.UserEqual(g.Grantee.GetUserId(), user.Id) || utils.UserEqual(g.Grantee.GetUserId(), md.Owner)) {
|
||||
return nil, errtypes.BadRequest("owncloudsql: owner/creator and grantee are the same")
|
||||
}
|
||||
|
||||
// check if share already exists.
|
||||
key := &collaboration.ShareKey{
|
||||
Owner: md.Owner,
|
||||
ResourceId: md.Id,
|
||||
Grantee: g.Grantee,
|
||||
}
|
||||
_, err := m.getByKey(ctx, key)
|
||||
|
||||
// share already exists
|
||||
if err == nil {
|
||||
return nil, errtypes.AlreadyExists(key.String())
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
ts := &typespb.Timestamp{
|
||||
Seconds: uint64(now),
|
||||
}
|
||||
|
||||
owner, err := m.userConverter.UserIDToUserName(ctx, md.Owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shareType, shareWith, err := m.formatGrantee(ctx, g.Grantee)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
itemType := resourceTypeToItem(md.Type)
|
||||
targetPath := path.Join("/", path.Base(md.Path))
|
||||
permissions := sharePermToInt(g.Permissions.Permissions)
|
||||
itemSource := md.Id.OpaqueId
|
||||
fileSource, err := strconv.ParseUint(itemSource, 10, 64)
|
||||
if err != nil {
|
||||
// it can be the case that the item source may be a character string
|
||||
// we leave fileSource blank in that case
|
||||
fileSource = 0
|
||||
}
|
||||
|
||||
stmtString := "INSERT INTO oc_share (share_type,uid_owner,uid_initiator,item_type,item_source,file_source,permissions,stime,share_with,file_target) VALUES (?,?,?,?,?,?,?,?,?,?)"
|
||||
stmtValues := []interface{}{shareType, owner, user.Username, itemType, itemSource, fileSource, permissions, now, shareWith, targetPath}
|
||||
|
||||
stmt, err := m.db.Prepare(stmtString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := stmt.ExecContext(ctx, stmtValues...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lastID, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &collaboration.Share{
|
||||
Id: &collaboration.ShareId{
|
||||
OpaqueId: strconv.FormatInt(lastID, 10),
|
||||
},
|
||||
ResourceId: md.Id,
|
||||
Permissions: g.Permissions,
|
||||
Grantee: g.Grantee,
|
||||
Owner: md.Owner,
|
||||
Creator: user.Id,
|
||||
Ctime: ts,
|
||||
Mtime: ts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *mgr) GetShare(ctx context.Context, ref *collaboration.ShareReference) (*collaboration.Share, error) {
|
||||
var s *collaboration.Share
|
||||
var err error
|
||||
switch {
|
||||
case ref.GetId() != nil:
|
||||
s, err = m.getByID(ctx, ref.GetId())
|
||||
case ref.GetKey() != nil:
|
||||
s, err = m.getByKey(ctx, ref.GetKey())
|
||||
default:
|
||||
err = errtypes.NotFound(ref.String())
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (m *mgr) Unshare(ctx context.Context, ref *collaboration.ShareReference) error {
|
||||
uid := ctxpkg.ContextMustGetUser(ctx).Username
|
||||
var query string
|
||||
params := []interface{}{}
|
||||
switch {
|
||||
case ref.GetId() != nil:
|
||||
query = "DELETE FROM oc_share where id=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, ref.GetId().OpaqueId, uid, uid)
|
||||
case ref.GetKey() != nil:
|
||||
key := ref.GetKey()
|
||||
shareType, shareWith, err := m.formatGrantee(ctx, key.Grantee)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
owner := formatUserID(key.Owner)
|
||||
query = "DELETE FROM oc_share WHERE uid_owner=? AND file_source=? AND share_type=? AND share_with=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, owner, key.ResourceId.OpaqueId, shareType, shareWith, uid, uid)
|
||||
default:
|
||||
return errtypes.NotFound(ref.String())
|
||||
}
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := stmt.ExecContext(ctx, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rowCnt, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rowCnt == 0 {
|
||||
return errtypes.NotFound(ref.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mgr) UpdateShare(ctx context.Context, ref *collaboration.ShareReference, p *collaboration.SharePermissions, updated *collaboration.Share, fieldMask *field_mask.FieldMask) (*collaboration.Share, error) {
|
||||
permissions := sharePermToInt(p.Permissions)
|
||||
uid := ctxpkg.ContextMustGetUser(ctx).Username
|
||||
|
||||
var query string
|
||||
params := []interface{}{}
|
||||
switch {
|
||||
case ref.GetId() != nil:
|
||||
query = "update oc_share set permissions=?,stime=? where id=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, permissions, time.Now().Unix(), ref.GetId().OpaqueId, uid, uid)
|
||||
case ref.GetKey() != nil:
|
||||
key := ref.GetKey()
|
||||
shareType, shareWith, err := m.formatGrantee(ctx, key.Grantee)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
owner := formatUserID(key.Owner)
|
||||
query = "update oc_share set permissions=?,stime=? where (uid_owner=? or uid_initiator=?) AND file_source=? AND share_type=? AND share_with=? AND (uid_owner=? or uid_initiator=?)"
|
||||
params = append(params, permissions, time.Now().Unix(), owner, owner, key.ResourceId.OpaqueId, shareType, shareWith, uid, uid)
|
||||
default:
|
||||
return nil, errtypes.NotFound(ref.String())
|
||||
}
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = stmt.ExecContext(ctx, params...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m.GetShare(ctx, ref)
|
||||
}
|
||||
|
||||
func (m *mgr) ListShares(ctx context.Context, filters []*collaboration.Filter) ([]*collaboration.Share, error) {
|
||||
uid := ctxpkg.ContextMustGetUser(ctx).Username
|
||||
query := `
|
||||
SELECT
|
||||
coalesce(s.uid_owner, '') as uid_owner, coalesce(s.uid_initiator, '') as uid_initiator,
|
||||
coalesce(s.share_with, '') as share_with, coalesce(s.file_source, '') as file_source,
|
||||
s.file_target, s.id, s.stime, s.permissions, s.share_type, fc.storage as storage
|
||||
FROM oc_share s
|
||||
LEFT JOIN oc_filecache fc ON fc.fileid = file_source
|
||||
WHERE (uid_owner=? or uid_initiator=?)
|
||||
`
|
||||
params := []interface{}{uid, uid}
|
||||
|
||||
var (
|
||||
filterQuery string
|
||||
filterParams []interface{}
|
||||
err error
|
||||
)
|
||||
if len(filters) == 0 {
|
||||
filterQuery += "(share_type=? OR share_type=?)"
|
||||
params = append(params, shareTypeUser)
|
||||
params = append(params, shareTypeGroup)
|
||||
} else {
|
||||
filterQuery, filterParams, err = translateFilters(filters)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params = append(params, filterParams...)
|
||||
}
|
||||
|
||||
if filterQuery != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, filterQuery)
|
||||
}
|
||||
|
||||
rows, err := m.db.QueryContext(ctx, query, params...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var s DBShare
|
||||
shares := []*collaboration.Share{}
|
||||
for rows.Next() {
|
||||
if err := rows.Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.ID, &s.STime, &s.Permissions, &s.ShareType, &s.ItemStorage); err != nil {
|
||||
continue
|
||||
}
|
||||
share, err := m.convertToCS3Share(ctx, s, m.storageMountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shares = append(shares, share)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
// we list the shares that are targeted to the user in context or to the user groups.
|
||||
func (m *mgr) ListReceivedShares(ctx context.Context, filters []*collaboration.Filter, forUser *userpb.UserId) ([]*collaboration.ReceivedShare, error) {
|
||||
user := ctxpkg.ContextMustGetUser(ctx)
|
||||
if user.GetId().GetType() == userpb.UserType_USER_TYPE_SERVICE {
|
||||
u, err := m.userConverter.GetUser(forUser)
|
||||
if err != nil {
|
||||
return nil, errtypes.BadRequest("user not found")
|
||||
}
|
||||
user = u
|
||||
}
|
||||
uid := user.Username
|
||||
|
||||
params := []interface{}{uid, uid, uid}
|
||||
for _, v := range user.Groups {
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
homeConcat := ""
|
||||
if m.driver == "mysql" { // mysql concat
|
||||
homeConcat = "storages.id = CONCAT('home::', s.uid_owner)"
|
||||
} else { // sqlite3 concat
|
||||
homeConcat = "storages.id = 'home::' || s.uid_owner"
|
||||
}
|
||||
userSelect := ""
|
||||
if len(user.Groups) > 0 {
|
||||
userSelect = "AND ((share_type != 1 AND share_with=?) OR (share_type = 1 AND share_with in (?" + strings.Repeat(",?", len(user.Groups)-1) + ")))"
|
||||
} else {
|
||||
userSelect = "AND (share_type != 1 AND share_with=?)"
|
||||
}
|
||||
query := `
|
||||
WITH results AS
|
||||
(
|
||||
SELECT s.*, storages.numeric_id FROM oc_share s
|
||||
LEFT JOIN oc_storages storages ON ` + homeConcat + `
|
||||
WHERE (uid_owner != ? AND uid_initiator != ?) ` + userSelect + `
|
||||
)
|
||||
SELECT COALESCE(r.uid_owner, '') AS uid_owner, COALESCE(r.uid_initiator, '') AS uid_initiator, COALESCE(r.share_with, '')
|
||||
AS share_with, COALESCE(r.file_source, '') AS file_source, COALESCE(r2.file_target, r.file_target), r.id, r.stime, r.permissions, r.share_type, COALESCE(r2.accepted, r.accepted),
|
||||
r.numeric_id, COALESCE(r.parent, -1) AS parent FROM results r LEFT JOIN results r2 ON r.id = r2.parent WHERE r.parent IS NULL`
|
||||
|
||||
filterQuery, filterParams, err := translateFilters(filters)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params = append(params, filterParams...)
|
||||
|
||||
if filterQuery != "" {
|
||||
query = fmt.Sprintf("%s AND (%s)", query, filterQuery)
|
||||
}
|
||||
query += ";"
|
||||
rows, err := m.db.QueryContext(ctx, query, params...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var s DBShare
|
||||
shares := []*collaboration.ReceivedShare{}
|
||||
for rows.Next() {
|
||||
if err := rows.Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.ID, &s.STime, &s.Permissions, &s.ShareType, &s.State, &s.ItemStorage, &s.Parent); err != nil {
|
||||
continue
|
||||
}
|
||||
share, err := m.convertToCS3ReceivedShare(ctx, s, m.storageMountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shares = append(shares, share)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return shares, nil
|
||||
}
|
||||
|
||||
func (m *mgr) GetReceivedShare(ctx context.Context, ref *collaboration.ShareReference) (*collaboration.ReceivedShare, error) {
|
||||
var s *collaboration.ReceivedShare
|
||||
var err error
|
||||
switch {
|
||||
case ref.GetId() != nil:
|
||||
s, err = m.getReceivedByID(ctx, ref.GetId())
|
||||
case ref.GetKey() != nil:
|
||||
s, err = m.getReceivedByKey(ctx, ref.GetKey())
|
||||
default:
|
||||
err = errtypes.NotFound(ref.String())
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return s, nil
|
||||
|
||||
}
|
||||
|
||||
func (m *mgr) UpdateReceivedShare(ctx context.Context, receivedShare *collaboration.ReceivedShare, fieldMask *field_mask.FieldMask, _ *userpb.UserId) (*collaboration.ReceivedShare, error) {
|
||||
// TODO: How to inject the uid when a UserId is set? override it in the ctx? Add parameter to GetReceivedShare?
|
||||
rs, err := m.GetReceivedShare(ctx, &collaboration.ShareReference{Spec: &collaboration.ShareReference_Id{Id: receivedShare.Share.Id}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fields := []string{}
|
||||
params := []interface{}{}
|
||||
for i := range fieldMask.Paths {
|
||||
switch fieldMask.Paths[i] {
|
||||
case "state":
|
||||
rs.State = receivedShare.State
|
||||
fields = append(fields, "accepted=?")
|
||||
switch rs.State {
|
||||
case collaboration.ShareState_SHARE_STATE_REJECTED:
|
||||
params = append(params, 2)
|
||||
case collaboration.ShareState_SHARE_STATE_ACCEPTED:
|
||||
params = append(params, 0)
|
||||
}
|
||||
case "mount_point":
|
||||
fields = append(fields, "file_target=?")
|
||||
rs.MountPoint = receivedShare.MountPoint
|
||||
params = append(params, rs.MountPoint.Path)
|
||||
case "hidden":
|
||||
continue
|
||||
default:
|
||||
return nil, errtypes.NotSupported("updating " + fieldMask.Paths[i] + " is not supported")
|
||||
}
|
||||
}
|
||||
|
||||
if len(fields) == 0 {
|
||||
return nil, fmt.Errorf("no valid field provided in the fieldmask")
|
||||
}
|
||||
|
||||
updateReceivedShare := func(column string) error {
|
||||
query := "update oc_share set "
|
||||
query += strings.Join(fields, ",")
|
||||
query += fmt.Sprintf(" where %s=?", column)
|
||||
params := append(params, rs.Share.Id.OpaqueId)
|
||||
|
||||
stmt, err := m.db.Prepare(query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := stmt.ExecContext(ctx, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
affected, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected < 1 {
|
||||
return fmt.Errorf("No rows updated")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = updateReceivedShare("parent") // Try to update the child state in case of group shares first
|
||||
if err != nil {
|
||||
err = updateReceivedShare("id")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return rs, nil
|
||||
}
|
||||
|
||||
func (m *mgr) getByID(ctx context.Context, id *collaboration.ShareId) (*collaboration.Share, error) {
|
||||
uid := ctxpkg.ContextMustGetUser(ctx).Username
|
||||
s := DBShare{ID: id.OpaqueId}
|
||||
query := "select coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator, coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source, file_target, stime, permissions, share_type FROM oc_share WHERE id=? AND (uid_owner=? or uid_initiator=?)"
|
||||
if err := m.db.QueryRowContext(ctx, query, id.OpaqueId, uid, uid).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.STime, &s.Permissions, &s.ShareType); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, errtypes.NotFound(id.OpaqueId)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return m.convertToCS3Share(ctx, s, m.storageMountID)
|
||||
}
|
||||
|
||||
func (m *mgr) getByKey(ctx context.Context, key *collaboration.ShareKey) (*collaboration.Share, error) {
|
||||
owner, err := m.userConverter.UserIDToUserName(ctx, key.Owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uid := ctxpkg.ContextMustGetUser(ctx).Username
|
||||
|
||||
s := DBShare{}
|
||||
shareType, shareWith, err := m.formatGrantee(ctx, key.Grantee)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query := "select coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator, coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source, file_target, id, stime, permissions, share_type FROM oc_share WHERE uid_owner=? AND file_source=? AND share_type=? AND share_with=? AND (uid_owner=? or uid_initiator=?)"
|
||||
if err = m.db.QueryRowContext(ctx, query, owner, key.ResourceId.StorageId, shareType, shareWith, uid, uid).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.ID, &s.STime, &s.Permissions, &s.ShareType); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, errtypes.NotFound(key.String())
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return m.convertToCS3Share(ctx, s, m.storageMountID)
|
||||
}
|
||||
|
||||
func (m *mgr) getReceivedByID(ctx context.Context, id *collaboration.ShareId) (*collaboration.ReceivedShare, error) {
|
||||
user := ctxpkg.ContextMustGetUser(ctx)
|
||||
uid := user.Username
|
||||
|
||||
params := []interface{}{id.OpaqueId, id.OpaqueId, uid}
|
||||
for _, v := range user.Groups {
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
homeConcat := ""
|
||||
if m.driver == "mysql" { // mysql concat
|
||||
homeConcat = "storages.id = CONCAT('home::', s.uid_owner)"
|
||||
} else { // sqlite3 concat
|
||||
homeConcat = "storages.id = 'home::' || s.uid_owner"
|
||||
}
|
||||
userSelect := ""
|
||||
if len(user.Groups) > 0 {
|
||||
userSelect = "AND ((share_type != 1 AND share_with=?) OR (share_type = 1 AND share_with in (?" + strings.Repeat(",?", len(user.Groups)-1) + ")))"
|
||||
} else {
|
||||
userSelect = "AND (share_type != 1 AND share_with=?)"
|
||||
}
|
||||
|
||||
query := `
|
||||
WITH results AS
|
||||
(
|
||||
SELECT s.*, storages.numeric_id
|
||||
FROM oc_share s
|
||||
LEFT JOIN oc_storages storages ON ` + homeConcat + `
|
||||
WHERE s.id=? OR s.parent=? ` + userSelect + `
|
||||
)
|
||||
SELECT COALESCE(r.uid_owner, '') AS uid_owner, COALESCE(r.uid_initiator, '') AS uid_initiator, COALESCE(r.share_with, '')
|
||||
AS share_with, COALESCE(r.file_source, '') AS file_source, COALESCE(r2.file_target, r.file_target), r.id, r.stime, r.permissions, r.share_type, COALESCE(r2.accepted, r.accepted),
|
||||
r.numeric_id, COALESCE(r.parent, -1) AS parent
|
||||
FROM results r
|
||||
LEFT JOIN results r2 ON r.id = r2.parent
|
||||
WHERE r.parent IS NULL;
|
||||
`
|
||||
|
||||
s := DBShare{}
|
||||
if err := m.db.QueryRowContext(ctx, query, params...).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.ID, &s.STime, &s.Permissions, &s.ShareType, &s.State, &s.ItemStorage, &s.Parent); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, errtypes.NotFound(id.OpaqueId)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return m.convertToCS3ReceivedShare(ctx, s, m.storageMountID)
|
||||
}
|
||||
|
||||
func (m *mgr) getReceivedByKey(ctx context.Context, key *collaboration.ShareKey) (*collaboration.ReceivedShare, error) {
|
||||
user := ctxpkg.ContextMustGetUser(ctx)
|
||||
uid := user.Username
|
||||
|
||||
shareType, shareWith, err := m.formatGrantee(ctx, key.Grantee)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
params := []interface{}{uid, formatUserID(key.Owner), key.ResourceId.StorageId, key.ResourceId.OpaqueId, shareType, shareWith, shareWith}
|
||||
for _, v := range user.Groups {
|
||||
params = append(params, v)
|
||||
}
|
||||
|
||||
s := DBShare{}
|
||||
query := "select coalesce(uid_owner, '') as uid_owner, coalesce(uid_initiator, '') as uid_initiator, coalesce(share_with, '') as share_with, coalesce(file_source, '') as file_source, file_target, ts.id, stime, permissions, share_type, accepted FROM oc_share ts WHERE uid_owner=? AND file_source=? AND share_type=? AND share_with=? "
|
||||
if len(user.Groups) > 0 {
|
||||
query += "AND (share_with=? OR share_with in (?" + strings.Repeat(",?", len(user.Groups)-1) + "))"
|
||||
} else {
|
||||
query += "AND (share_with=?)"
|
||||
}
|
||||
|
||||
if err := m.db.QueryRowContext(ctx, query, params...).Scan(&s.UIDOwner, &s.UIDInitiator, &s.ShareWith, &s.FileSource, &s.FileTarget, &s.ID, &s.STime, &s.Permissions, &s.ShareType, &s.State); err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, errtypes.NotFound(key.String())
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return m.convertToCS3ReceivedShare(ctx, s, m.storageMountID)
|
||||
}
|
||||
|
||||
func granteeTypeToShareType(granteeType provider.GranteeType) int {
|
||||
switch granteeType {
|
||||
case provider.GranteeType_GRANTEE_TYPE_USER:
|
||||
return shareTypeUser
|
||||
case provider.GranteeType_GRANTEE_TYPE_GROUP:
|
||||
return shareTypeGroup
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// translateFilters translates the filters to sql queries
|
||||
func translateFilters(filters []*collaboration.Filter) (string, []interface{}, error) {
|
||||
var (
|
||||
filterQuery string
|
||||
params []interface{}
|
||||
)
|
||||
|
||||
groupedFilters := share.GroupFiltersByType(filters)
|
||||
// If multiple filters of the same type are passed to this function, they need to be combined with the `OR` operator.
|
||||
// That is why the filters got grouped by type.
|
||||
// For every given filter type, iterate over the filters and if there are more than one combine them.
|
||||
// Combine the different filter types using `AND`
|
||||
var filterCounter = 0
|
||||
for filterType, filters := range groupedFilters {
|
||||
switch filterType {
|
||||
case collaboration.Filter_TYPE_RESOURCE_ID:
|
||||
filterQuery += "("
|
||||
for i, f := range filters {
|
||||
filterQuery += "file_source=?"
|
||||
params = append(params, f.GetResourceId().OpaqueId)
|
||||
|
||||
if i != len(filters)-1 {
|
||||
filterQuery += " OR "
|
||||
}
|
||||
}
|
||||
filterQuery += ")"
|
||||
case collaboration.Filter_TYPE_GRANTEE_TYPE:
|
||||
filterQuery += "("
|
||||
for i, f := range filters {
|
||||
filterQuery += "r.share_type=?"
|
||||
params = append(params, granteeTypeToShareType(f.GetGranteeType()))
|
||||
|
||||
if i != len(filters)-1 {
|
||||
filterQuery += " OR "
|
||||
}
|
||||
}
|
||||
filterQuery += ")"
|
||||
case collaboration.Filter_TYPE_EXCLUDE_DENIALS:
|
||||
// TODO this may change once the mapping of permission to share types is completed (cf. pkg/cbox/utils/conversions.go)
|
||||
filterQuery += "r.permissions > 0"
|
||||
default:
|
||||
return "", nil, fmt.Errorf("filter type is not supported")
|
||||
}
|
||||
if filterCounter != len(groupedFilters)-1 {
|
||||
filterQuery += " AND "
|
||||
}
|
||||
filterCounter++
|
||||
}
|
||||
return filterQuery, params, nil
|
||||
}
|
||||
BIN
Binary file not shown.
-1
@@ -32,7 +32,6 @@ import (
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/localhome"
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/nextcloud"
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/ocis"
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/owncloudsql"
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/s3"
|
||||
_ "github.com/owncloud/reva/v2/pkg/storage/fs/s3ng"
|
||||
// Add your own here
|
||||
|
||||
Generated
Vendored
-761
@@ -1,761 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
package filecache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/conversions"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
// Provides mysql drivers
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
// Cache represents a oc10-style file cache
|
||||
type Cache struct {
|
||||
driver string
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// Storage represents a storage entry in the database
|
||||
type Storage struct {
|
||||
ID string
|
||||
NumericID int
|
||||
}
|
||||
|
||||
// File represents an entry of the file cache
|
||||
type File struct {
|
||||
ID int
|
||||
Storage int
|
||||
Parent int
|
||||
MimePart int
|
||||
MimeType int
|
||||
MimeTypeString string
|
||||
Size int
|
||||
MTime int
|
||||
StorageMTime int
|
||||
UnencryptedSize int
|
||||
Permissions int
|
||||
Encrypted bool
|
||||
Path string
|
||||
Name string
|
||||
Etag string
|
||||
Checksum string
|
||||
}
|
||||
|
||||
// TrashItem represents a trash item of the file cache
|
||||
type TrashItem struct {
|
||||
ID int
|
||||
Name string
|
||||
User string
|
||||
Path string
|
||||
Timestamp int
|
||||
}
|
||||
|
||||
// Scannable describes the interface providing a Scan method
|
||||
type Scannable interface {
|
||||
Scan(...interface{}) error
|
||||
}
|
||||
|
||||
// NewMysql returns a new Cache instance connecting to a MySQL database
|
||||
func NewMysql(dsn string) (*Cache, error) {
|
||||
sqldb, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error connecting to the database")
|
||||
}
|
||||
|
||||
// FIXME make configurable
|
||||
sqldb.SetConnMaxLifetime(time.Minute * 3)
|
||||
sqldb.SetConnMaxIdleTime(time.Second * 30)
|
||||
sqldb.SetMaxOpenConns(100)
|
||||
sqldb.SetMaxIdleConns(10)
|
||||
|
||||
err = sqldb.Ping()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error connecting to the database")
|
||||
}
|
||||
|
||||
return New("mysql", sqldb)
|
||||
}
|
||||
|
||||
// New returns a new Cache instance connecting to the given sql.DB
|
||||
func New(driver string, sqldb *sql.DB) (*Cache, error) {
|
||||
return &Cache{
|
||||
driver: driver,
|
||||
db: sqldb,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListStorages returns the list of numeric ids of all storages
|
||||
// Optionally only home storages are considered
|
||||
func (c *Cache) ListStorages(ctx context.Context, onlyHome bool) ([]*Storage, error) {
|
||||
query := ""
|
||||
if onlyHome {
|
||||
mountPointConcat := ""
|
||||
if c.driver == "mysql" {
|
||||
mountPointConcat = "m.mount_point = CONCAT('/', m.user_id, '/')"
|
||||
} else { // sqlite3
|
||||
mountPointConcat = "m.mount_point = '/' || m.user_id || '/'"
|
||||
}
|
||||
|
||||
query = "SELECT s.id, s.numeric_id FROM oc_storages s JOIN oc_mounts m ON s.numeric_id = m.storage_id WHERE " + mountPointConcat
|
||||
} else {
|
||||
query = "SELECT id, numeric_id FROM oc_storages"
|
||||
}
|
||||
rows, err := c.db.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
storages := []*Storage{}
|
||||
for rows.Next() {
|
||||
storage := &Storage{}
|
||||
err := rows.Scan(&storage.ID, &storage.NumericID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
storages = append(storages, storage)
|
||||
}
|
||||
return storages, nil
|
||||
}
|
||||
|
||||
// GetStorage returns the storage with the given numeric id
|
||||
func (c *Cache) GetStorage(ctx context.Context, numeridID interface{}) (*Storage, error) {
|
||||
numericID, err := toIntID(numeridID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row := c.db.QueryRowContext(ctx, "SELECT id, numeric_id FROM oc_storages WHERE numeric_id = ?", numericID)
|
||||
s := &Storage{}
|
||||
switch err := row.Scan(&s.ID, &s.NumericID); err {
|
||||
case nil:
|
||||
return s, nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// GetNumericStorageID returns the database id for the given storage
|
||||
func (c *Cache) GetNumericStorageID(ctx context.Context, id string) (int, error) {
|
||||
row := c.db.QueryRowContext(ctx, "SELECT numeric_id FROM oc_storages WHERE id = ?", id)
|
||||
var nid int
|
||||
switch err := row.Scan(&nid); err {
|
||||
case nil:
|
||||
return nid, nil
|
||||
default:
|
||||
return -1, err
|
||||
}
|
||||
}
|
||||
|
||||
// CreateStorage creates a new storage and returns its numeric id
|
||||
func (c *Cache) CreateStorage(ctx context.Context, id string) (int, error) {
|
||||
tx, err := c.db.Begin()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
stmt, err := tx.PrepareContext(ctx, "INSERT INTO oc_storages(id) VALUES(?)")
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
res, err := stmt.ExecContext(ctx, id)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
insertedID, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"path": "",
|
||||
"etag": "",
|
||||
"mimetype": "httpd/unix-directory",
|
||||
}
|
||||
_, err = c.doInsertOrUpdate(ctx, tx, int(insertedID), data, true)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return int(insertedID), err
|
||||
}
|
||||
|
||||
// GetStorageOwner returns the username of the owner of the given storage
|
||||
func (c *Cache) GetStorageOwner(ctx context.Context, numericID interface{}) (string, error) {
|
||||
numericID, err := toIntID(numericID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
row := c.db.QueryRowContext(ctx, "SELECT id FROM oc_storages WHERE numeric_id = ?", numericID)
|
||||
var id string
|
||||
switch err := row.Scan(&id); err {
|
||||
case nil:
|
||||
return strings.TrimPrefix(id, "home::"), nil
|
||||
default:
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
// GetStorageOwnerByFileID returns the username of the owner of the given entry
|
||||
func (c *Cache) GetStorageOwnerByFileID(ctx context.Context, numericID interface{}) (string, error) {
|
||||
numericID, err := toIntID(numericID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
row := c.db.QueryRowContext(ctx, "SELECT id FROM oc_storages storages, oc_filecache cache WHERE storages.numeric_id = cache.storage AND cache.fileid = ?", numericID)
|
||||
var id string
|
||||
switch err := row.Scan(&id); err {
|
||||
case nil:
|
||||
return strings.TrimPrefix(id, "home::"), nil
|
||||
default:
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) rowToFile(row Scannable) (*File, error) {
|
||||
var fileid, storage, parent, mimetype, mimepart, size, mtime, storageMtime, encrypted, unencryptedSize int
|
||||
var permissions sql.NullInt32
|
||||
var path, name, etag, checksum, mimetypestring sql.NullString
|
||||
err := row.Scan(&fileid, &storage, &path, &parent, &permissions, &mimetype, &mimepart, &mimetypestring, &size, &mtime, &storageMtime, &encrypted, &unencryptedSize, &name, &etag, &checksum)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &File{
|
||||
ID: fileid,
|
||||
Storage: storage,
|
||||
Path: path.String,
|
||||
Parent: parent,
|
||||
Permissions: int(permissions.Int32),
|
||||
MimeType: mimetype,
|
||||
MimeTypeString: mimetypestring.String,
|
||||
MimePart: mimepart,
|
||||
Size: size,
|
||||
MTime: mtime,
|
||||
StorageMTime: storageMtime,
|
||||
Encrypted: encrypted == 1,
|
||||
UnencryptedSize: unencryptedSize,
|
||||
Name: name.String,
|
||||
Etag: etag.String,
|
||||
Checksum: checksum.String,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Get returns the cache entry for the specified storage/path
|
||||
func (c *Cache) Get(ctx context.Context, s interface{}, p string) (*File, error) {
|
||||
storageID, err := toIntID(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
phashBytes := md5.Sum([]byte(p))
|
||||
phash := hex.EncodeToString(phashBytes[:])
|
||||
|
||||
row := c.db.QueryRowContext(ctx, `
|
||||
SELECT
|
||||
fc.fileid, fc.storage, fc.path, fc.parent, fc.permissions, fc.mimetype, fc.mimepart,
|
||||
mt.mimetype, fc.size, fc.mtime, fc.storage_mtime, fc.encrypted, fc.unencrypted_size,
|
||||
fc.name, fc.etag, fc.checksum
|
||||
FROM oc_filecache fc
|
||||
LEFT JOIN oc_mimetypes mt ON fc.mimetype = mt.id
|
||||
WHERE path_hash = ? AND storage = ?`, phash, storageID)
|
||||
return c.rowToFile(row)
|
||||
}
|
||||
|
||||
// Path returns the path for the specified entry
|
||||
func (c *Cache) Path(ctx context.Context, id interface{}) (string, error) {
|
||||
id, err := toIntID(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
row := c.db.QueryRowContext(ctx, "SELECT path FROM oc_filecache WHERE fileid = ?", id)
|
||||
var path string
|
||||
err = row.Scan(&path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// List returns the list of entries below the given path
|
||||
func (c *Cache) List(ctx context.Context, storage interface{}, p string) ([]*File, error) {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rows *sql.Rows
|
||||
phash := fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(p, "/"))))
|
||||
rows, err = c.db.QueryContext(ctx, `
|
||||
SELECT
|
||||
fc.fileid, fc.storage, fc.path, fc.parent, fc.permissions, fc.mimetype, fc.mimepart,
|
||||
mt.mimetype, fc.size, fc.mtime, fc.storage_mtime, fc.encrypted, fc.unencrypted_size,
|
||||
fc.name, fc.etag, fc.checksum
|
||||
FROM oc_filecache fc
|
||||
LEFT JOIN oc_mimetypes mt ON fc.mimetype = mt.id
|
||||
WHERE storage = ? AND parent = (SELECT fileid FROM oc_filecache WHERE storage = ? AND path_hash=?) AND name IS NOT NULL
|
||||
`, storageID, storageID, phash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
entries := []*File{}
|
||||
for rows.Next() {
|
||||
entry, err := c.rowToFile(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// Permissions returns the permissions for the specified storage/path
|
||||
func (c *Cache) Permissions(ctx context.Context, storage interface{}, p string) (*provider.ResourcePermissions, error) {
|
||||
entry, err := c.Get(ctx, storage, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
perms, err := conversions.NewPermissions(entry.Permissions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return conversions.RoleFromOCSPermissions(perms, nil).CS3ResourcePermissions(), nil
|
||||
}
|
||||
|
||||
// InsertOrUpdate creates or updates a cache entry
|
||||
func (c *Cache) InsertOrUpdate(ctx context.Context, storage interface{}, data map[string]interface{}, allowEmptyParent bool) (int, error) {
|
||||
tx, err := c.db.Begin()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
id, err := c.doInsertOrUpdate(ctx, tx, storage, data, allowEmptyParent)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (c *Cache) doInsertOrUpdate(ctx context.Context, tx *sql.Tx, storage interface{}, data map[string]interface{}, allowEmptyParent bool) (int, error) {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
columns := []string{"storage"}
|
||||
placeholders := []string{"?"}
|
||||
values := []interface{}{storage}
|
||||
|
||||
for _, key := range []string{"path", "mimetype", "etag"} {
|
||||
if _, exists := data[key]; !exists {
|
||||
return -1, fmt.Errorf("missing required data")
|
||||
}
|
||||
}
|
||||
|
||||
path := data["path"].(string)
|
||||
data["name"] = filepath.Base(path)
|
||||
if data["name"] == "." {
|
||||
data["name"] = ""
|
||||
}
|
||||
|
||||
parentPath := strings.TrimRight(filepath.Dir(path), "/")
|
||||
if parentPath == "." {
|
||||
parentPath = ""
|
||||
}
|
||||
if path == "" {
|
||||
data["parent"] = -1
|
||||
} else {
|
||||
parent, err := c.Get(ctx, storageID, parentPath)
|
||||
if err == nil {
|
||||
data["parent"] = parent.ID
|
||||
} else {
|
||||
if allowEmptyParent {
|
||||
data["parent"] = -1
|
||||
} else {
|
||||
return -1, fmt.Errorf("could not find parent %s, %s, %v, %w", parentPath, path, parent, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if _, exists := data["checksum"]; !exists {
|
||||
data["checksum"] = ""
|
||||
}
|
||||
|
||||
for k, v := range data {
|
||||
switch k {
|
||||
case "path":
|
||||
phashBytes := md5.Sum([]byte(v.(string)))
|
||||
phash := hex.EncodeToString(phashBytes[:])
|
||||
columns = append(columns, "path_hash")
|
||||
values = append(values, phash)
|
||||
placeholders = append(placeholders, "?")
|
||||
case "storage_mtime":
|
||||
if _, exists := data["mtime"]; !exists {
|
||||
columns = append(columns, "mtime")
|
||||
values = append(values, v)
|
||||
placeholders = append(placeholders, "?")
|
||||
}
|
||||
case "mimetype":
|
||||
parts := strings.Split(v.(string), "/")
|
||||
columns = append(columns, "mimetype")
|
||||
values = append(values, v)
|
||||
placeholders = append(placeholders, "(SELECT id FROM oc_mimetypes WHERE mimetype=?)")
|
||||
columns = append(columns, "mimepart")
|
||||
values = append(values, parts[0])
|
||||
placeholders = append(placeholders, "(SELECT id FROM oc_mimetypes WHERE mimetype=?)")
|
||||
continue
|
||||
}
|
||||
|
||||
columns = append(columns, k)
|
||||
values = append(values, v)
|
||||
placeholders = append(placeholders, "?")
|
||||
}
|
||||
|
||||
err = c.insertMimetype(ctx, tx, data["mimetype"].(string))
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
query := "INSERT INTO oc_filecache( " + strings.Join(columns, ", ") + ") VALUES(" + strings.Join(placeholders, ",") + ")"
|
||||
|
||||
updates := []string{}
|
||||
for i, column := range columns {
|
||||
if column != "path" && column != "path_hash" && column != "storage" {
|
||||
updates = append(updates, column+"="+placeholders[i])
|
||||
values = append(values, values[i])
|
||||
}
|
||||
}
|
||||
if c.driver == "mysql" { // mysql upsert
|
||||
query += " ON DUPLICATE KEY UPDATE "
|
||||
} else { // sqlite3 upsert
|
||||
query += " ON CONFLICT(storage,path_hash) DO UPDATE SET "
|
||||
}
|
||||
query += strings.Join(updates, ",")
|
||||
|
||||
stmt, err := tx.PrepareContext(ctx, query)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
|
||||
res, err := stmt.ExecContext(ctx, values...)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("could not store filecache item")
|
||||
return -1, err
|
||||
}
|
||||
id, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return int(id), nil
|
||||
}
|
||||
|
||||
// Copy creates a copy of the specified entry at the target path
|
||||
func (c *Cache) Copy(ctx context.Context, storage interface{}, sourcePath, targetPath string) (int, error) {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
source, err := c.Get(ctx, storageID, sourcePath)
|
||||
if err != nil {
|
||||
return -1, errors.Wrap(err, "could not find source")
|
||||
}
|
||||
|
||||
row := c.db.QueryRowContext(ctx, "SELECT mimetype FROM oc_mimetypes WHERE id=?", source.MimeType)
|
||||
var mimetype string
|
||||
err = row.Scan(&mimetype)
|
||||
if err != nil {
|
||||
return -1, errors.Wrap(err, "could not find source mimetype")
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"path": targetPath,
|
||||
"checksum": source.Checksum,
|
||||
"mimetype": mimetype,
|
||||
"permissions": source.Permissions,
|
||||
"etag": source.Etag,
|
||||
"size": source.Size,
|
||||
"mtime": source.MTime,
|
||||
"storage_mtime": source.StorageMTime,
|
||||
"encrypted": source.Encrypted,
|
||||
"unencrypted_size": source.UnencryptedSize,
|
||||
}
|
||||
return c.InsertOrUpdate(ctx, storage, data, false)
|
||||
}
|
||||
|
||||
// Move moves the specified entry to the target path
|
||||
func (c *Cache) Move(ctx context.Context, storage interface{}, sourcePath, targetPath string) error {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source, err := c.Get(ctx, storageID, sourcePath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not find source")
|
||||
}
|
||||
newParentPath := strings.TrimRight(filepath.Dir(targetPath), "/")
|
||||
newParent, err := c.Get(ctx, storageID, newParentPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not find new parent")
|
||||
}
|
||||
|
||||
tx, err := c.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
stmt, err := tx.Prepare("UPDATE oc_filecache SET parent=?, path=?, name=?, path_hash=? WHERE storage = ? AND fileid=?")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stmt.Close()
|
||||
phashBytes := md5.Sum([]byte(targetPath))
|
||||
_, err = stmt.ExecContext(ctx, newParent.ID, targetPath, filepath.Base(targetPath), hex.EncodeToString(phashBytes[:]), storageID, source.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
childRows, err := tx.QueryContext(ctx, "SELECT fileid, path FROM oc_filecache WHERE parent = ?", source.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer childRows.Close()
|
||||
children := map[int]string{}
|
||||
for childRows.Next() {
|
||||
var (
|
||||
id int
|
||||
path string
|
||||
)
|
||||
err = childRows.Scan(&id, &path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
children[id] = path
|
||||
}
|
||||
for id, path := range children {
|
||||
path = strings.ReplaceAll(path, sourcePath, targetPath)
|
||||
phashBytes = md5.Sum([]byte(path))
|
||||
_, err = stmt.ExecContext(ctx, source.ID, path, filepath.Base(path), hex.EncodeToString(phashBytes[:]), storageID, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Purge removes the specified storage/path from the cache without putting it into the trash
|
||||
func (c *Cache) Purge(ctx context.Context, storage interface{}, path string) error {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
phashBytes := md5.Sum([]byte(path))
|
||||
phash := hex.EncodeToString(phashBytes[:])
|
||||
_, err = c.db.ExecContext(ctx, "DELETE FROM oc_filecache WHERE storage = ? and path_hash = ?", storageID, phash)
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete removes the specified storage/path from the cache
|
||||
func (c *Cache) Delete(ctx context.Context, storage interface{}, user, path, trashPath string) error {
|
||||
err := c.Move(ctx, storage, path, trashPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
re := regexp.MustCompile(`(.*)\.d(\d+)$`)
|
||||
parts := re.FindStringSubmatch(filepath.Base(trashPath))
|
||||
|
||||
query := "INSERT INTO oc_files_trash(user,id,timestamp,location) VALUES(?,?,?,?)"
|
||||
stmt, err := c.db.PrepareContext(ctx, query)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
relativeLocation, err := filepath.Rel("files/", filepath.Dir(path))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = stmt.ExecContext(ctx, user, filepath.Base(parts[1]), parts[2], relativeLocation)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("could not store filecache item")
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRecycleItem returns the specified recycle item
|
||||
func (c *Cache) GetRecycleItem(ctx context.Context, user, path string, timestamp int) (*TrashItem, error) {
|
||||
row := c.db.QueryRowContext(ctx, "SELECT auto_id, id, location FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp)
|
||||
var autoID int
|
||||
var id, location string
|
||||
err := row.Scan(&autoID, &id, &location)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &TrashItem{
|
||||
ID: autoID,
|
||||
Name: id,
|
||||
User: user,
|
||||
Path: location,
|
||||
Timestamp: timestamp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EmptyRecycle clears the recycle bin for the given user
|
||||
func (c *Cache) EmptyRecycle(ctx context.Context, user string) error {
|
||||
_, err := c.db.ExecContext(ctx, "DELETE FROM oc_files_trash WHERE user = ?", user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
storage, err := c.GetNumericStorageID(ctx, "home::"+user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = c.db.ExecContext(ctx, "DELETE FROM oc_filecache WHERE storage = ? AND PATH LIKE ?", storage, "files_trashbin/%")
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteRecycleItem deletes the specified item from the trash
|
||||
func (c *Cache) DeleteRecycleItem(ctx context.Context, user, path string, timestamp int) error {
|
||||
_, err := c.db.ExecContext(ctx, "DELETE FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp)
|
||||
return err
|
||||
}
|
||||
|
||||
// PurgeRecycleItem deletes the specified item from the filecache and the trash
|
||||
func (c *Cache) PurgeRecycleItem(ctx context.Context, user, path string, timestamp int, isVersionFile bool) error {
|
||||
row := c.db.QueryRowContext(ctx, "SELECT auto_id, location FROM oc_files_trash WHERE id = ? AND user = ? AND timestamp = ?", path, user, timestamp)
|
||||
var autoID int
|
||||
var location string
|
||||
err := row.Scan(&autoID, &location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = c.db.ExecContext(ctx, "DELETE FROM oc_files_trash WHERE auto_id=?", autoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
storage, err := c.GetNumericStorageID(ctx, "home::"+user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
trashType := "files"
|
||||
if isVersionFile {
|
||||
trashType = "versions"
|
||||
}
|
||||
item, err := c.Get(ctx, storage, filepath.Join("files_trashbin", trashType, path+".d"+strconv.Itoa(timestamp)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = c.db.ExecContext(ctx, "DELETE FROM oc_filecache WHERE fileid=? OR parent=?", item.ID, item.ID)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// SetEtag set a new etag for the specified item
|
||||
func (c *Cache) SetEtag(ctx context.Context, storage interface{}, path, etag string) error {
|
||||
storageID, err := toIntID(storage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
source, err := c.Get(ctx, storageID, path)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not find source")
|
||||
}
|
||||
stmt, err := c.db.PrepareContext(ctx, "UPDATE oc_filecache SET etag=? WHERE storage = ? AND fileid=?")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = stmt.ExecContext(ctx, etag, storageID, source.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Cache) insertMimetype(ctx context.Context, tx *sql.Tx, mimetype string) error {
|
||||
insertPart := func(v string) error {
|
||||
stmt, err := tx.PrepareContext(ctx, "INSERT INTO oc_mimetypes(mimetype) VALUES(?)")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = stmt.ExecContext(ctx, v)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "UNIQUE") || strings.Contains(err.Error(), "Error 1062") {
|
||||
return nil // Already exists
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(mimetype, "/")
|
||||
err := insertPart(parts[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return insertPart(mimetype)
|
||||
}
|
||||
|
||||
func toIntID(rid interface{}) (int, error) {
|
||||
switch t := rid.(type) {
|
||||
case int:
|
||||
return t, nil
|
||||
case string:
|
||||
return strconv.Atoi(t)
|
||||
default:
|
||||
return -1, fmt.Errorf("invalid type")
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
-2149
File diff suppressed because it is too large.
Load diff
Generated
Vendored
-87
@@ -1,87 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
)
|
||||
|
||||
// TODO(jfd) get rid of the differences between unix and windows. the inode and dev should never be used for the etag because it interferes with backups
|
||||
|
||||
// calcEtag will create an etag based on the md5 of
|
||||
// - mtime,
|
||||
// - inode (if available),
|
||||
// - device (if available) and
|
||||
// - size.
|
||||
// errors are logged, but an etag will still be returned
|
||||
func calcEtag(ctx context.Context, fi os.FileInfo) string {
|
||||
log := appctx.GetLogger(ctx)
|
||||
h := md5.New()
|
||||
err := binary.Write(h, binary.BigEndian, fi.ModTime().UnixNano())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing mtime")
|
||||
}
|
||||
stat, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if ok {
|
||||
// take device and inode into account
|
||||
err = binary.Write(h, binary.BigEndian, stat.Ino)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing inode")
|
||||
}
|
||||
err = binary.Write(h, binary.BigEndian, stat.Dev)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing device")
|
||||
}
|
||||
}
|
||||
err = binary.Write(h, binary.BigEndian, fi.Size())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing size")
|
||||
}
|
||||
etag := fmt.Sprintf("%x", h.Sum(nil))
|
||||
return strings.Trim(etag, "\"")
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) GetQuota(ctx context.Context, ref *provider.Reference) (uint64, uint64, uint64, error) {
|
||||
// TODO quota of which storage space?
|
||||
// we could use the logged in user, but when a user has access to multiple storages this falls short
|
||||
// for now return quota of root
|
||||
stat := syscall.Statfs_t{}
|
||||
err := syscall.Statfs(fs.toInternalPath(ctx, "/"), &stat)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
// Total data blocks in filesystem
|
||||
total := stat.Blocks * uint64(stat.Bsize)
|
||||
// Free blocks available to unprivileged user
|
||||
used := (stat.Blocks - uint64(stat.Bavail)) * uint64(stat.Bsize) //nolint:unconvert
|
||||
remaining := total - used
|
||||
return total, used, remaining, nil
|
||||
}
|
||||
Generated
Vendored
-76
@@ -1,76 +0,0 @@
|
||||
// Copyright 2018-2021 CERN
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// In applying this license, CERN does not waive the privileges and immunities
|
||||
// granted to it by virtue of its status as an Intergovernmental Organization
|
||||
// or submit itself to any jurisdiction.
|
||||
|
||||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package owncloudsql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/appctx"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// calcEtag will create an etag based on the md5 of
|
||||
// - mtime,
|
||||
// - inode (if available),
|
||||
// - device (if available) and
|
||||
// - size.
|
||||
// errors are logged, but an etag will still be returned
|
||||
func calcEtag(ctx context.Context, fi os.FileInfo) string {
|
||||
log := appctx.GetLogger(ctx)
|
||||
h := md5.New()
|
||||
err := binary.Write(h, binary.BigEndian, fi.ModTime().UnixNano())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing mtime")
|
||||
}
|
||||
// device and inode have no meaning on windows
|
||||
err = binary.Write(h, binary.BigEndian, fi.Size())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("error writing size")
|
||||
}
|
||||
etag := fmt.Sprintf(`"%x"`, h.Sum(nil))
|
||||
return fmt.Sprintf("\"%s\"", strings.Trim(etag, "\""))
|
||||
}
|
||||
|
||||
func (fs *owncloudsqlfs) GetQuota(ctx context.Context, ref *provider.Reference) (uint64, uint64, uint64, error) {
|
||||
// TODO quota of which storage space?
|
||||
// we could use the logged in user, but when a user has access to multiple storages this falls short
|
||||
// for now return quota of root
|
||||
var free, total, avail uint64
|
||||
|
||||
pathPtr, err := windows.UTF16PtrFromString(fs.toInternalPath(ctx, "/"))
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
err = windows.GetDiskFreeSpaceEx(pathPtr, &avail, &total, &free)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
|
||||
used := total - free
|
||||
return total, used, free, nil
|
||||
}
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user