Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6ca549b0e |
No files matched your search
@@ -65,8 +65,6 @@ updates:
|
||||
day: sunday
|
||||
time: '22:00'
|
||||
timezone: Etc/UTC
|
||||
cooldown:
|
||||
default-days: 7
|
||||
open-pull-requests-limit: 5
|
||||
groups:
|
||||
minor-and-patch:
|
||||
|
||||
@@ -62,14 +62,14 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Enable pnpm
|
||||
run: corepack enable && corepack prepare pnpm@10.33.3 --activate
|
||||
|
||||
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -165,7 +165,7 @@ jobs:
|
||||
exit $FAILED
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
path: |
|
||||
@@ -231,7 +231,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -280,7 +280,7 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -294,7 +294,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: api-coverage-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -315,7 +315,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -328,7 +328,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -342,7 +342,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: api-coverage-cli-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -363,7 +363,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -376,7 +376,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -390,7 +390,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: api-coverage-ldap-pool-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -419,7 +419,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
- uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: "8.4"
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -468,7 +468,7 @@ jobs:
|
||||
'
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -485,7 +485,7 @@ jobs:
|
||||
|
||||
- name: Upload raw coverage data
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: api-coverage-core-${{ matrix.suite }}
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
@@ -534,7 +534,7 @@ jobs:
|
||||
vault_storage: true
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
|
||||
# https://github.com/microsoft/playwright/issues/40724
|
||||
@@ -551,7 +551,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -683,7 +683,7 @@ jobs:
|
||||
|
||||
- name: Upload tracing result
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-traces-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e
|
||||
@@ -691,7 +691,7 @@ jobs:
|
||||
|
||||
- name: Upload a11y result
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-a11y-result-${{ matrix.suite }}-${{ github.run_attempt }}
|
||||
path: web/reports/e2e/a11y-report.json
|
||||
@@ -712,7 +712,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -737,7 +737,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -762,7 +762,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -787,7 +787,7 @@ jobs:
|
||||
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
|
||||
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: ocis-build-artifacts
|
||||
|
||||
@@ -809,7 +809,7 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
@@ -842,7 +842,7 @@ jobs:
|
||||
go-version-file: go.mod
|
||||
cache: true
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
@@ -876,7 +876,7 @@ jobs:
|
||||
cache: true
|
||||
|
||||
- name: Download raw coverage data
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
pattern: api-coverage-*
|
||||
path: ${{ env.GOCOVERDIR }}
|
||||
|
||||
+20
-100
@@ -82,7 +82,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup PHP ${{ env.PHP_VERSION }}
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0
|
||||
uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2
|
||||
with:
|
||||
php-version: ${{ env.PHP_VERSION }}
|
||||
extensions: curl, xml, mbstring, zip, ldap, gd
|
||||
@@ -476,18 +476,18 @@ jobs:
|
||||
# - suite: mfa
|
||||
# args: "--type playwright --suites mfa"
|
||||
# mfa: true
|
||||
# - suite: oidc
|
||||
# args: "--type playwright specs/oidc/refreshToken.spec.ts"
|
||||
# oidc: true
|
||||
# - suite: oidc-iframe
|
||||
# args: "--type playwright specs/oidc/iframeTokenRenewal.spec.ts"
|
||||
# oidc_iframe: true
|
||||
- suite: app-provider
|
||||
args: "--type playwright --suites app-provider"
|
||||
collaboration: true
|
||||
- suite: ocm
|
||||
args: "--type playwright --suites ocm"
|
||||
federated: true
|
||||
- suite: oidc
|
||||
args: "--type playwright specs/oidc/refreshToken.spec.ts"
|
||||
oidc: true
|
||||
- suite: oidc-iframe
|
||||
args: "--type playwright specs/oidc/iframeTokenRenewal.spec.ts"
|
||||
oidc_iframe: true
|
||||
# - suite: app-provider
|
||||
# args: "--type playwright --suites app-provider"
|
||||
# collaboration: true
|
||||
# - suite: ocm
|
||||
# args: "--type playwright --suites ocm"
|
||||
# federated: true
|
||||
# - suite: vault-storage
|
||||
# args: "--type playwright --suites vault-storage"
|
||||
# vault_storage: true
|
||||
@@ -497,7 +497,7 @@ jobs:
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
# 24.16.0 breaks playwright install (yauzl zip extraction hangs); pin to last known good.
|
||||
# https://github.com/microsoft/playwright/issues/40724
|
||||
@@ -540,92 +540,13 @@ jobs:
|
||||
run: make -C tests/config/k8s create-cluster
|
||||
|
||||
- name: Prepare Helm Charts
|
||||
env:
|
||||
ENABLE_WOPI: ${{ matrix.suite == 'app-provider' }}
|
||||
ENABLE_OCM: ${{ matrix.suite == 'ocm' }}
|
||||
run: |
|
||||
cd tests/config/k8s
|
||||
make prepare-charts
|
||||
if [[ "${{ matrix.suite }}" == "ocm" ]]; then
|
||||
OCM=true make prepare-charts
|
||||
fi
|
||||
|
||||
- name: Deploy Suite-Specific External Backends
|
||||
run: |
|
||||
if [[ "${{ matrix.suite }}" == "app-provider" ]]; then
|
||||
# Start Collabora
|
||||
docker run -d \
|
||||
--name collabora \
|
||||
--network host \
|
||||
--entrypoint bash \
|
||||
-e DONT_GEN_SSL_CERT=set \
|
||||
-e "extra_params=--o:ssl.enable=true --o:ssl.termination=true --o:welcome.enable=false --o:net.frame_ancestors=https://127.0.0.1:9200" \
|
||||
collabora/code:25.04.7.3.1 \
|
||||
-c "coolconfig generate-proof-key && bash /start-collabora-online.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:9980/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "collabora ready."
|
||||
|
||||
# Start OnlyOffice
|
||||
docker run -d \
|
||||
--name onlyoffice \
|
||||
-p 7443:443 \
|
||||
--add-host "$TEST_SERVER_DOMAIN:host-gateway" \
|
||||
-e WOPI_ENABLED=true \
|
||||
-e USE_UNAUTHORIZED_STORAGE=true \
|
||||
-v "$(pwd)/tests/config/ci/only-office.json:/tmp/local.json:ro" \
|
||||
--entrypoint /bin/sh \
|
||||
onlyoffice/documentserver:9.2.1 \
|
||||
-c "set -e
|
||||
cp /tmp/local.json /etc/onlyoffice/documentserver/local.json
|
||||
openssl req -x509 -newkey rsa:4096 -keyout onlyoffice.key -out onlyoffice.crt -sha256 -days 365 -batch -nodes
|
||||
mkdir -p /var/www/onlyoffice/Data/certs
|
||||
cp onlyoffice.key /var/www/onlyoffice/Data/certs/
|
||||
cp onlyoffice.crt /var/www/onlyoffice/Data/certs/
|
||||
chmod 400 /var/www/onlyoffice/Data/certs/onlyoffice.key
|
||||
/app/ds/run-document-server.sh"
|
||||
timeout 150 bash -c 'until curl -kfsSL https://localhost:7443/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "onlyoffice ready."
|
||||
|
||||
#Start FakeOffice
|
||||
docker run -d --name fakeoffice --network host \
|
||||
-v "$(pwd):/ocis:ro" \
|
||||
python:3-alpine \
|
||||
python3 -c "
|
||||
import http.server, pathlib
|
||||
body = pathlib.Path('/ocis/tests/config/ci/hosting-discovery.xml').read_bytes()
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header('Content-Type', 'text/xml')
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
def log_message(self, *a): pass
|
||||
http.server.HTTPServer(('', 8080), H).serve_forever()
|
||||
"
|
||||
timeout 60 bash -c 'until curl -fsSL http://localhost:8080/hosting/discovery > /dev/null; do sleep 5; done'
|
||||
echo "fakeoffice ready."
|
||||
|
||||
bash tests/config/k8s/expose-external-svc.sh collabora:9980
|
||||
bash tests/config/k8s/expose-external-svc.sh onlyoffice:7443
|
||||
bash tests/config/k8s/expose-external-svc.sh fakeoffice:8080
|
||||
fi
|
||||
run: make -C tests/config/k8s prepare-charts
|
||||
|
||||
- name: Deploy oCIS
|
||||
run: |
|
||||
cd tests/config/k8s
|
||||
kubectl get pods -n "$TEST_SERVER_DOMAIN" -Aw &
|
||||
make deploy-ocis
|
||||
if [[ "${{ matrix.suite }}" == "ocm" ]]; then
|
||||
OCM=true make deploy-ocis
|
||||
fi
|
||||
|
||||
- name: Expose node ports
|
||||
if: ${{ matrix.suite == 'app-provider' }}
|
||||
run: |
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-collabora 9300 30300
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9300 30301
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-onlyoffice 9300 30302
|
||||
bash tests/config/k8s/expose-nodeports.sh collaboration-fakeoffice 9304 30304
|
||||
|
||||
- name: Wait for oCIS to be ready
|
||||
env:
|
||||
@@ -697,14 +618,13 @@ jobs:
|
||||
E2E_ARGS: "${{ matrix.args }}"
|
||||
K8S: ${{ env.K8S }}
|
||||
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
|
||||
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
|
||||
FED_SERVER_URL: ${{ env.FED_SERVER_URL }}
|
||||
FEDERATED_NEEDED: ${{ matrix.federated == true && 'true' || 'false' }}
|
||||
OIDC_NEEDED: ${{ matrix.oidc == true && 'true' || 'false' }}
|
||||
OIDC_IFRAME_NEEDED: ${{ matrix.oidc_iframe == true && 'true' || 'false' }}
|
||||
run: python3 tests/acceptance/run-e2e.py
|
||||
|
||||
- name: Upload Playwright traces
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-traces-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: web/reports/e2e
|
||||
@@ -712,7 +632,7 @@ jobs:
|
||||
|
||||
- name: Upload a11y result
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: playwright-a11y-result-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: web/reports/e2e/a11y-report.json
|
||||
@@ -720,7 +640,7 @@ jobs:
|
||||
|
||||
- name: Upload oCIS logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: ocis-logs-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
|
||||
path: tests/config/k8s/logs
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
+186
-15
@@ -14,6 +14,9 @@ on:
|
||||
default: ''
|
||||
|
||||
env:
|
||||
PRODUCTION_RELEASE_TAGS: '5.0,7,8'
|
||||
DOCKER_REPO_ROLLING: owncloud/ocis-rolling
|
||||
DOCKER_REPO_PRODUCTION: owncloud/ocis
|
||||
NODE_VERSION: '24'
|
||||
PNPM_VERSION: '10.28.1'
|
||||
GOLANG_BUILD_IMAGE: 'golang:1.26.8-alpine3.23@sha256:a8fa79c5bd40d880b52bd3b6d7669ecdcfd00e85facdd427d279efb5ddd79cb1'
|
||||
@@ -24,7 +27,9 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
version: ${{ steps.info.outputs.version }}
|
||||
is_production: ${{ steps.info.outputs.is_production }}
|
||||
is_prerelease: ${{ steps.info.outputs.is_prerelease }}
|
||||
docker_repos: ${{ steps.info.outputs.docker_repos }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
if: ${{ github.ref_type == 'branch' || (github.event_name == 'workflow_dispatch' && inputs.version_override == '') }}
|
||||
@@ -70,10 +75,23 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
IS_PRODUCTION=false
|
||||
for TAG in ${PRODUCTION_RELEASE_TAGS//,/ }; do
|
||||
[[ "$VERSION" == "$TAG"* ]] && IS_PRODUCTION=true && break
|
||||
done
|
||||
|
||||
[[ "$VERSION" == *"-"* ]] && IS_PRERELEASE=true || IS_PRERELEASE=false
|
||||
|
||||
if [[ "$IS_PRODUCTION" == "true" && "$IS_PRERELEASE" == "false" ]]; then
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\",\"$DOCKER_REPO_PRODUCTION\"]
|
||||
else
|
||||
REPOS=[\"$DOCKER_REPO_ROLLING\"]
|
||||
fi
|
||||
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "is_production=$IS_PRODUCTION" >> $GITHUB_OUTPUT
|
||||
echo "is_prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT
|
||||
echo "docker_repos=$REPOS" >> $GITHUB_OUTPUT
|
||||
|
||||
generate-code:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -84,7 +102,7 @@ jobs:
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- run: npm install --silent -g yarn npx --force
|
||||
@@ -101,7 +119,7 @@ jobs:
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
sed -i "s/LatestTag = \".*\"/LatestTag = \"$VERSION\"/" ocis-pkg/version/version.go
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: |
|
||||
@@ -110,6 +128,159 @@ jobs:
|
||||
!web
|
||||
retention-days: 1
|
||||
|
||||
docker-build:
|
||||
if: false
|
||||
name: docker-build (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ${{ matrix.arch == 'amd64' && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }}
|
||||
timeout-minutes: 120
|
||||
needs: [determine-release-type, generate-code, security-scan-trivy]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64, arm64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- id: goversion
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- run: |
|
||||
ALPINE_VERSION=$(grep '^FROM.*alpine:' ocis/docker/Dockerfile.linux.${{ matrix.arch }} | grep -o 'alpine:[0-9.]*' | cut -d: -f2 | cut -d. -f1,2)
|
||||
docker run --rm \
|
||||
-v "${{ github.workspace }}:/workspace" \
|
||||
-w /workspace \
|
||||
"golang:${{ steps.goversion.outputs.go-version }}-alpine${ALPINE_VERSION}" \
|
||||
sh -c "apk add --no-cache bash gcc musl-dev vips-dev make git && \
|
||||
git config --global --add safe.directory /workspace && \
|
||||
CGO_ENABLED=1 ENABLE_VIPS=true VERSION=${{ needs.determine-release-type.outputs.version }} \
|
||||
make -C ocis release-linux-docker-${{ matrix.arch }}"
|
||||
- id: tags
|
||||
run: |
|
||||
VERSION="${{ needs.determine-release-type.outputs.version }}"
|
||||
REPO="${{ matrix.repo }}"
|
||||
ARCH="${{ matrix.arch }}"
|
||||
printf "tags<<EOF\n%s\nEOF\n" \
|
||||
"${REPO}:${VERSION}-linux-${ARCH}" >> $GITHUB_OUTPUT
|
||||
- id: build
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: ocis
|
||||
file: ocis/docker/Dockerfile.linux.${{ matrix.arch }}
|
||||
platforms: linux/${{ matrix.arch }}
|
||||
load: true
|
||||
push: false
|
||||
provenance: false
|
||||
build-args: |
|
||||
REVISION=${{ github.sha }}
|
||||
VERSION=${{ needs.determine-release-type.outputs.version }}
|
||||
tags: ${{ steps.tags.outputs.tags }}
|
||||
- id: trivy
|
||||
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ steps.tags.outputs.tags }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ steps.tags.outputs.tags }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
- name: push
|
||||
if: steps.trivy.outcome == 'success'
|
||||
run: docker push ${{ steps.tags.outputs.tags }}
|
||||
|
||||
docker-scan:
|
||||
name: docker-scan (${{ matrix.arch }}, ${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: [determine-release-type, docker-build]
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [amd64]
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
|
||||
id: trivy
|
||||
continue-on-error: true
|
||||
with:
|
||||
image-ref: ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }}
|
||||
format: table
|
||||
exit-code: 1
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
skip-files: /usr/bin/gomplate,/usr/bin/wait-for
|
||||
hide-progress: true
|
||||
env:
|
||||
TRIVY_IGNOREFILE: .trivyignore
|
||||
|
||||
- name: Block on vulnerabilities
|
||||
if: steps.trivy.outcome == 'failure'
|
||||
run: |
|
||||
echo "::error title=Security scan blocked release::Image ${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-${{ matrix.arch }} has HIGH or CRITICAL vulnerabilities (see Trivy report above). Fix all findings before releasing."
|
||||
exit 1
|
||||
|
||||
docker-manifest:
|
||||
if: false
|
||||
name: docker-manifest (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [determine-release-type, docker-build, docker-scan]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- if: ${{ contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
- if: ${{ !contains(matrix.repo, 'rolling') }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-amd64" \
|
||||
"${{ matrix.repo }}:${{ needs.determine-release-type.outputs.version }}-linux-arm64"
|
||||
|
||||
docker-readme:
|
||||
if: false
|
||||
name: docker-readme (${{ matrix.repo }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [determine-release-type, docker-manifest]
|
||||
strategy:
|
||||
matrix:
|
||||
repo: ${{ fromJSON(needs.determine-release-type.outputs.docker_repos) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa # v5.0.0
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
repository: ${{ matrix.repo }}
|
||||
readme-filepath: ocis/README.md
|
||||
|
||||
build-binaries:
|
||||
name: build-binaries (${{ matrix.os }})
|
||||
runs-on: ubuntu-latest
|
||||
@@ -120,7 +291,7 @@ jobs:
|
||||
os: [linux, darwin]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
@@ -133,7 +304,7 @@ jobs:
|
||||
if [[ "${{ matrix.os }}" == "linux" ]]; then
|
||||
cp assets/End-User-License-Agreement-for-ownCloud-Infinite-Scale.pdf ocis/dist/release/
|
||||
fi
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: binaries-${{ matrix.os }}
|
||||
path: ocis/dist/release/*
|
||||
@@ -158,11 +329,11 @@ jobs:
|
||||
needs: [determine-release-type, generate-code]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: generated-code
|
||||
path: .
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
@@ -176,7 +347,7 @@ jobs:
|
||||
- run: make ci-node-check-licenses && make ci-node-save-licenses
|
||||
- run: make ci-go-check-licenses && make ci-go-save-licenses
|
||||
- run: tar -czf third-party-licenses.tar.gz -C third-party-licenses .
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: third-party-licenses.tar.gz
|
||||
@@ -200,7 +371,7 @@ jobs:
|
||||
if [[ $(wc -l < ocis/dist/CHANGELOG.md) -lt 5 ]]; then
|
||||
echo "Development release — no release notes yet. See [unreleased changes](https://github.com/owncloud/ocis/tree/master/changelog/unreleased/)." > ocis/dist/CHANGELOG.md
|
||||
fi
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: changelog
|
||||
path: ocis/dist/CHANGELOG.md
|
||||
@@ -211,19 +382,19 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: changelog
|
||||
path: .
|
||||
@@ -248,15 +419,15 @@ jobs:
|
||||
- create-github-release
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-linux
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: binaries-darwin
|
||||
path: release-assets
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: third-party-licenses
|
||||
path: release-assets
|
||||
|
||||
@@ -77,7 +77,7 @@ jobs:
|
||||
version: 10.33.3
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with:
|
||||
node-version: 24.15.0
|
||||
cache: pnpm
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
Bugfix: Show a clear error for deleted public links and files in app views
|
||||
|
||||
Opening a file via a public link in an app such as the preview, after the link
|
||||
or the file had been deleted, showed the message "Unknown error". The server
|
||||
answers with an empty 404, which the WebDAV client turns into a generic message,
|
||||
and app views that failed while loading the folder passed only that message on.
|
||||
These views now show "The resource could not be located, it may not exist
|
||||
anymore.", as the other loading paths already did.
|
||||
|
||||
https://github.com/owncloud/ocis/issues/13138
|
||||
https://github.com/owncloud/ocis/pull/13156
|
||||
@@ -1,9 +0,0 @@
|
||||
Bugfix: Show image preview for files with spaces in the name on public links
|
||||
|
||||
The preview in the details panel was not shown for files opened via a public
|
||||
link when the file name contained spaces. The preview URL was used unquoted in a
|
||||
CSS `url()`, so the browser dropped it and never requested the thumbnail. The
|
||||
URL is now quoted.
|
||||
|
||||
https://github.com/owncloud/ocis/issues/13137
|
||||
https://github.com/owncloud/ocis/pull/13150
|
||||
@@ -1,10 +0,0 @@
|
||||
Bugfix: Disable rubber-band overscroll of the page in file apps
|
||||
|
||||
Scrolling to the top or bottom of the content in a file app such as
|
||||
OnlyOffice, Collabora or the text editor could make the whole page bounce
|
||||
along with it, including the top bar and the app frame, briefly revealing the
|
||||
blank page background behind them. The vertical elastic overscroll of the page
|
||||
is now disabled while a file is open in one of these apps, so the surrounding
|
||||
layout stays in place.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13140
|
||||
@@ -1,11 +0,0 @@
|
||||
Bugfix: Files no longer stay in processing after upload or copy
|
||||
|
||||
After uploading or copying files, some of them sometimes stayed greyed out as
|
||||
"processing" until the page was reloaded. This happened when processing
|
||||
finished while the file list was still being loaded: the update from the
|
||||
server was ignored and the list then showed the file as still processing.
|
||||
|
||||
Files whose processing has finished are now refreshed automatically when they
|
||||
show up in the file list as processing.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13134
|
||||
@@ -1,13 +0,0 @@
|
||||
Bugfix: Remove the unmarshalable request body field from graph log messages
|
||||
|
||||
We've removed the `body` field from the log messages of the graph service's HTTP
|
||||
handlers. The field was set from `http.Request.Body`, an `io.ReadCloser`, which
|
||||
can never be serialized into a useful log value.
|
||||
|
||||
The tracing middleware replaces the request body with a wrapper that carries an
|
||||
exported function field, so serializing it failed outright and the log line was
|
||||
emitted with `"body": "marshaling error: json: unsupported type: func(int64)"`
|
||||
instead of the payload. Without the tracing middleware the field serialized to an
|
||||
empty object. In both cases the intended payload was never logged.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12915
|
||||
@@ -1,15 +0,0 @@
|
||||
Bugfix: Keep bind config in sync when resetting a service user password
|
||||
|
||||
Resetting an IDM service user password with `ocis idm resetpassword
|
||||
--user-type service` only changed the entry in the IDM directory. Services such
|
||||
as auth-basic, users and groups still bound to LDAP as the `reva` service user
|
||||
using the old `bind_password` from their configuration, so after a restart
|
||||
those binds failed and regular admin login started returning 401 Unauthorized.
|
||||
|
||||
The command now rewrites the matching `bind_password` and
|
||||
`service_user_passwords` keys in `ocis.yaml` when it is present, and always
|
||||
prints the environment variables that must carry the new password for env-var
|
||||
and distributed deployments it cannot rewrite.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13176
|
||||
https://github.com/owncloud/ocis/issues/12569
|
||||
@@ -1,10 +0,0 @@
|
||||
Bugfix: Mark all notifications as read
|
||||
|
||||
Clicking "Mark all read" in the notifications menu only cleared the list
|
||||
visually. The request sent to the server was malformed, so the notifications
|
||||
were not deleted and reappeared after a page reload. This affected the regular
|
||||
view as well as the Safe.
|
||||
|
||||
The request is now sent correctly and the notifications are removed for good.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13157
|
||||
@@ -1,9 +0,0 @@
|
||||
Bugfix: Remove federated connections
|
||||
|
||||
Removing a federated connection in the connections panel sent a malformed
|
||||
request to the server, so the connection was not actually removed and could
|
||||
reappear after a page reload.
|
||||
|
||||
The request is now sent correctly and the connection is removed for good.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13160
|
||||
@@ -1,10 +0,0 @@
|
||||
Bugfix: Clean up the trash view in the Safe
|
||||
|
||||
The trash offered a "Copy permanent link" action for deleted items, which
|
||||
cannot be linked to. The action is no longer shown for deleted items.
|
||||
|
||||
The personal space in the trash was labelled "Personal" in the Safe, while the
|
||||
rest of the interface calls it "Safe-Personal". The trash now uses the same
|
||||
name.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13136
|
||||
@@ -1,8 +0,0 @@
|
||||
Bugfix: Show correct message when Safe access is denied for lacking permission
|
||||
|
||||
A user without permission to use the Safe who opened the Safe URL directly was
|
||||
shown "Not logged in" with a "Log in again" button, even though they were
|
||||
still logged in. The page now shows "Access denied" with a "Continue" button
|
||||
that returns to the app for this case.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13111
|
||||
@@ -1,8 +0,0 @@
|
||||
Bugfix: Vault share search could show ineligible users
|
||||
|
||||
Searching for a share recipient by a cross-instance reference (e.g.
|
||||
`user@school`) could return a user without vault access, letting them be
|
||||
selected in the Safe share picker before failing with an error afterward.
|
||||
Vault eligibility is now always enforced for this kind of search too.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13154
|
||||
@@ -1,13 +0,0 @@
|
||||
Bugfix: Fix file and folder downloads in vault mode
|
||||
|
||||
Downloading a file in the vault failed with a 403 error. A download uses a
|
||||
signed link without a login token. Thus the proxy uses the stored MFA status of
|
||||
the user. The proxy did not store this status. Now the proxy stores it after it
|
||||
knows the user. A download is accepted if the user had a request with MFA within
|
||||
the MFA session duration.
|
||||
|
||||
Downloading a folder or several files in the vault failed with a 404 error. In
|
||||
vault mode, the web UI requested the signing key from a wrong address. Now the
|
||||
web UI uses the correct address.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13097
|
||||
@@ -1,14 +0,0 @@
|
||||
Bugfix: Retry WOPI rename and upload while the file is processing
|
||||
|
||||
Renaming a file or uploading its contents through the collaboration service
|
||||
failed with a 500 when the file was still being processed, for example right
|
||||
after it had been created by a PutRelativeFile request. The storage answers
|
||||
with a "too early" status in that case, which was only handled when deleting
|
||||
files.
|
||||
|
||||
The collaboration service now retries the rename and upload requests with an
|
||||
increasing waiting time until the file is ready. The delete request uses the
|
||||
same retry logic, which is now limited to 10 retries instead of waiting
|
||||
indefinitely.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13141
|
||||
@@ -1,14 +0,0 @@
|
||||
Bugfix: The global variable OCIS_CACHE_DATABASE was replaced
|
||||
|
||||
Some services accepted only the global variable OCIS_CACHE_DATABASE for their
|
||||
cache database name. The default values for each service is unique that is
|
||||
why this has not been noticed until now.
|
||||
|
||||
We added a local variable for each service. The GATEWAY service now accepts
|
||||
GATEWAY_PROVIDER_CACHE_DATABASE. The PROXY service now accepts
|
||||
PROXY_OIDC_USERINFO_CACHE_DATABASE. The SETTINGS service now accepts
|
||||
SETTINGS_CACHE_DATABASE. The STORAGE-SYSTEM service now accepts
|
||||
STORAGE_SYSTEM_CACHE_DATABASE. The do not use the global variable OCIS_CACHE_DATABASE
|
||||
to avoid the cache collisions.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/13158
|
||||
@@ -5,7 +5,7 @@ go 1.26.8
|
||||
require (
|
||||
dario.cat/mergo v1.0.2
|
||||
github.com/CiscoM31/godata v1.0.11
|
||||
github.com/KimMachineGun/automemlimit v1.0.0
|
||||
github.com/KimMachineGun/automemlimit v0.7.5
|
||||
github.com/Masterminds/semver v1.5.0
|
||||
github.com/MicahParks/keyfunc/v2 v2.1.0
|
||||
github.com/Nerzal/gocloak/v13 v13.9.0
|
||||
@@ -23,9 +23,9 @@ require (
|
||||
github.com/gabriel-vasile/mimetype v1.4.15
|
||||
github.com/ggwhite/go-masker v1.1.0
|
||||
github.com/go-chi/chi/v5 v5.3.2
|
||||
github.com/go-chi/httprate v0.16.1
|
||||
github.com/go-chi/httprate v0.16.0
|
||||
github.com/go-chi/render v1.0.3
|
||||
github.com/go-ldap/ldap/v3 v3.4.15
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3
|
||||
github.com/go-micro/plugins/v4/client/grpc v1.2.1
|
||||
github.com/go-micro/plugins/v4/logger/zerolog v1.2.0
|
||||
@@ -58,7 +58,7 @@ require (
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/mna/pigeon v1.3.0
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
|
||||
github.com/nats-io/nats-server/v2 v2.15.1
|
||||
github.com/nats-io/nats-server/v2 v2.15.0
|
||||
github.com/nats-io/nats.go v1.54.0
|
||||
github.com/olekukonko/tablewriter v1.1.5
|
||||
github.com/onsi/ginkgo v1.16.5
|
||||
@@ -67,10 +67,10 @@ 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-20261007144855-b8082819aa39
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
github.com/prometheus/client_golang v1.24.1
|
||||
github.com/r3labs/sse/v2 v2.10.0
|
||||
github.com/rogpeppe/go-internal v1.16.0
|
||||
github.com/rs/cors v1.11.1
|
||||
@@ -82,7 +82,7 @@ require (
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/test-go/testify v1.1.4
|
||||
github.com/thejerf/suture/v4 v4.0.6
|
||||
github.com/tidwall/gjson v1.20.0
|
||||
github.com/tidwall/gjson v1.19.1
|
||||
github.com/tus/tusd/v2 v2.10.1
|
||||
github.com/unrolled/secure v1.17.0
|
||||
github.com/urfave/cli/v2 v2.27.7
|
||||
@@ -90,7 +90,7 @@ require (
|
||||
go-micro.dev/v4 v4.11.0
|
||||
go.etcd.io/bbolt v1.5.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/jaeger v1.17.0
|
||||
@@ -100,16 +100,15 @@ require (
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.60.0
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sync v0.24.0
|
||||
golang.org/x/sync v0.23.0
|
||||
golang.org/x/term v0.46.0
|
||||
golang.org/x/text v0.42.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
|
||||
google.golang.org/grpc v1.86.0-dev
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gotest.tools/v3 v3.5.2
|
||||
stash.kopano.io/kgol/rndm v1.1.2
|
||||
)
|
||||
@@ -239,7 +238,7 @@ require (
|
||||
github.com/json-iterator/go v1.1.13-0.20220915233716-71ac16282d12 // indirect
|
||||
github.com/juliangruber/go-intersect v1.1.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||
github.com/klauspost/compress v1.20.1 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/kovidgoyal/go-parallel v1.1.1 // indirect
|
||||
@@ -293,8 +292,8 @@ require (
|
||||
github.com/pquerna/cachecontrol v0.2.0 // indirect
|
||||
github.com/prometheus/alertmanager v0.34.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.72.0 // indirect
|
||||
github.com/prometheus/procfs v0.22.0 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/prometheus/statsd_exporter v0.22.8 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
|
||||
@@ -51,8 +51,8 @@ github.com/CiscoM31/godata v1.0.11 h1:w7y8twuW02LdH6mak3/GJ5i0GrCv2IoZUJVqa/g5Ye
|
||||
github.com/CiscoM31/godata v1.0.11/go.mod h1:ZMiT6JuD3Rm83HEtiTx4JEChsd25YCrxchKGag/sdTc=
|
||||
github.com/DeepDiver1975/secure v0.0.0-20240611112133-abc838fb797c h1:ocsNvQ2tNHme4v/lTs17HROamc7mFzZfzWcg4m+UXN0=
|
||||
github.com/DeepDiver1975/secure v0.0.0-20240611112133-abc838fb797c/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
|
||||
github.com/KimMachineGun/automemlimit v1.0.0 h1:+MqlvDE/pkJNjk1rU+O14QsH8k10nJAD0frB0lsxyvw=
|
||||
github.com/KimMachineGun/automemlimit v1.0.0/go.mod h1:n+BSXxQWDFS1DKh67Rqo0lgTsowsg6x65ak5uyngML0=
|
||||
github.com/KimMachineGun/automemlimit v0.7.5 h1:RkbaC0MwhjL1ZuBKunGDjE/ggwAX43DwZrJqVwyveTk=
|
||||
github.com/KimMachineGun/automemlimit v0.7.5/go.mod h1:QZxpHaGOQoYvFhv/r4u3U0JTC2ZcOwbSr11UZF46UBM=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
|
||||
@@ -288,8 +288,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
|
||||
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/httprate v0.16.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
|
||||
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
|
||||
github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
|
||||
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=
|
||||
@@ -315,8 +315,8 @@ github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBj
|
||||
github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU=
|
||||
github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0=
|
||||
github.com/go-ldap/ldap/v3 v3.1.7/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q=
|
||||
github.com/go-ldap/ldap/v3 v3.4.15 h1:eRB4f4Ecn1POL1mO86+uUDlecmyWsdiJwh60bAUS4UY=
|
||||
github.com/go-ldap/ldap/v3 v3.4.15/go.mod h1:jeD0c98EdZQCKKKKe4kTWs5aCf6y+j8KuYsYLznZSQk=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3 h1:sfz1YppV05y4sYaW7kXZtrocU/+vimnIWt4cxAYh7+o=
|
||||
github.com/go-ldap/ldif v0.0.0-20200320164324-fd88d9b715b3/go.mod h1:ZXFhGda43Z2TVbfGZefXyMJzsDHhCh0go3bZUcwTx7o=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
@@ -573,8 +573,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4
|
||||
github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
|
||||
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
|
||||
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
@@ -696,8 +696,8 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.1 h1:fK3AeYFIji1Smng60jB0hVoAPZezA/UzsaI3BqXFNEI=
|
||||
github.com/nats-io/nats-server/v2 v2.15.1/go.mod h1:yeuYRtKVKIFtmMz2/YPk+6hvmNBnk+WwTUzErBdH6IE=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0/go.mod h1:5qLF4CDGzZVFt//3fUrY1ePpwbi05r7QHPNroSUtolk=
|
||||
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
|
||||
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
|
||||
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
|
||||
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899 h1:IMu076AtnFEdabpBbowcGDYOeFLtm9ycNY1Z43YPYZU=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261007144855-b8082819aa39 h1:lC5Y4C3/i0uDhMLA53+kfDJg919gNbjSe2+FiViP3XM=
|
||||
github.com/owncloud/reva/v2 v2.0.0-20261007144855-b8082819aa39/go.mod h1:cgqg+UTe4ekjMbJj8hgoXSTxQ9fQramKcOUdvsFUrzc=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
||||
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
|
||||
@@ -777,8 +777,8 @@ github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqr
|
||||
github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.12.2/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY=
|
||||
github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.0.0-20170216185247-6f3806018612/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
@@ -793,8 +793,8 @@ github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9
|
||||
github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls=
|
||||
github.com/prometheus/common v0.35.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA=
|
||||
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
|
||||
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.0.0-20170703101242-e645f4e5aaa8/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
@@ -802,8 +802,8 @@ github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4O
|
||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||
github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4=
|
||||
github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics=
|
||||
github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/prometheus/statsd_exporter v0.22.7/go.mod h1:N/TevpjkIh9ccs6nuzY3jQn9dFqnUakOjnEuMPJJJnI=
|
||||
github.com/prometheus/statsd_exporter v0.22.8 h1:Qo2D9ZzaQG+id9i5NYNGmbf1aa/KxKbB9aKfMS+Yib0=
|
||||
github.com/prometheus/statsd_exporter v0.22.8/go.mod h1:/DzwbTEaFTE0Ojz5PqcSk6+PFHOPWGxdXVr6yC8eFOM=
|
||||
@@ -891,8 +891,8 @@ github.com/thanhpk/randstr v1.0.6 h1:psAOktJFD4vV9NEVb3qkhRSMvYh4ORRaj1+w/hn4B+o
|
||||
github.com/thanhpk/randstr v1.0.6/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U=
|
||||
github.com/thejerf/suture/v4 v4.0.6 h1:QsuCEsCqb03xF9tPAsWAj8QOAJBgQI1c0VqJNaingg8=
|
||||
github.com/thejerf/suture/v4 v4.0.6/go.mod h1:gu9Y4dXNUWFrByqRt30Rm9/UZ0wzRSt9AJS6xu/ZGxU=
|
||||
github.com/tidwall/gjson v1.20.0 h1:+agJ3rEzKcCXKDKo0ml26UROcpcAlnZyjq+TjbY5Fto=
|
||||
github.com/tidwall/gjson v1.20.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/gjson v1.19.1 h1:uKxUTe/+mtjSY3Sf1EIND83MyH+jWf1SixZ7DHpjbJU=
|
||||
github.com/tidwall/gjson v1.19.1/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
@@ -968,8 +968,8 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0 h1:aXBUaFvbF7xy77q6vXBvaw7dcZK0zUqJSF5UhtbbuZ4=
|
||||
go.opentelemetry.io/contrib/zpages v0.72.0/go.mod h1:e/qIKK0RHtY2dvkJhp1jtjVvglq/IDzMI7gDN8mMMtY=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
@@ -1102,8 +1102,8 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
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=
|
||||
@@ -1127,8 +1127,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
|
||||
@@ -274,15 +274,12 @@ func (c *ContentConnector) PutFile(ctx context.Context, stream io.Reader, stream
|
||||
},
|
||||
}
|
||||
|
||||
// Initiate the upload request. The target file might still be processing,
|
||||
// so we retry if we get a "TOO_EARLY" code
|
||||
resp, err := retryWhileTooEarly(ctx, logger, "PutFile", func() (*gatewayv1beta1.InitiateFileUploadResponse, error) {
|
||||
gwc, err := c.gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gwc.InitiateFileUpload(ctx, req)
|
||||
})
|
||||
gwc, err = c.gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Initiate the upload request
|
||||
resp, err := gwc.InitiateFileUpload(ctx, req)
|
||||
if err := requestFailed(logger, resp.GetStatus(), false, err, "PutFile: InitiateFileUpload failed"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -410,34 +410,6 @@ var _ = Describe("ContentConnector", func() {
|
||||
Expect(response).To(BeNil())
|
||||
})
|
||||
|
||||
It("InitiateFileUpload retries while the file is processing", func() {
|
||||
reader := strings.NewReader("Content to upload is here!")
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
gatewayClient.On("Stat", mock.Anything, mock.Anything).Times(1).Return(&providerv1beta1.StatResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
Info: &providerv1beta1.ResourceInfo{
|
||||
Lock: &providerv1beta1.Lock{
|
||||
LockId: "goodAndValidLock",
|
||||
Type: providerv1beta1.LockType_LOCK_TYPE_WRITE,
|
||||
},
|
||||
Size: uint64(123456789),
|
||||
},
|
||||
}, nil)
|
||||
|
||||
gatewayClient.On("InitiateFileUpload", mock.Anything, mock.Anything).Return(&gateway.InitiateFileUploadResponse{
|
||||
Status: status.NewTooEarly(ctx, "resource is processing"),
|
||||
}, nil).Twice()
|
||||
gatewayClient.On("InitiateFileUpload", mock.Anything, mock.Anything).Return(&gateway.InitiateFileUploadResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil).Once()
|
||||
|
||||
// no upload protocols are returned, so the upload fails after InitiateFileUpload succeeds
|
||||
_, err := cc.PutFile(ctx, reader, reader.Size(), "goodAndValidLock")
|
||||
Expect(err).To(Equal(connector.NewConnectorError(500, "url is missing")))
|
||||
gatewayClient.AssertNumberOfCalls(GinkgoT(), "InitiateFileUpload", 3)
|
||||
})
|
||||
|
||||
It("upload request failed", func() {
|
||||
reader := strings.NewReader("Content to upload is here!")
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
@@ -939,22 +939,42 @@ func (f *FileConnector) DeleteFile(ctx context.Context, lockID string) (*Connect
|
||||
Str("RequestedLockID", lockID).
|
||||
Logger()
|
||||
|
||||
var deleteRes *providerv1beta1.DeleteResponse
|
||||
deleteReq := &providerv1beta1.DeleteRequest{
|
||||
Ref: wopiContext.FileReference,
|
||||
LockId: lockID,
|
||||
}
|
||||
|
||||
// the file might still be processing, so we retry if we get a "TOO_EARLY" code
|
||||
deleteRes, err := retryWhileTooEarly(ctx, logger, "DeleteFile", func() (*providerv1beta1.DeleteResponse, error) {
|
||||
// we'll retry the request after a while if we get a "TOO_EARLY" code
|
||||
for retries := 0; deleteRes == nil || deleteRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_TOO_EARLY; retries++ {
|
||||
gwc, err := f.gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gwc.Delete(ctx, deleteReq)
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("DeleteFile: delete failed")
|
||||
return nil, err
|
||||
deleteRes, err = gwc.Delete(ctx, deleteReq)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("DeleteFile: stat failed")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if deleteRes.GetStatus().GetCode() == rpcv1beta1.Code_CODE_TOO_EARLY {
|
||||
// starting from 20ms, double the waiting time for each retry
|
||||
// capping at 5 secs
|
||||
var waitingTime time.Duration
|
||||
waitingTime = (20 * time.Millisecond) << retries
|
||||
if waitingTime.Seconds() > 5 {
|
||||
waitingTime = 5 * time.Second
|
||||
}
|
||||
|
||||
logger.Warn().
|
||||
Str("StatusCode", deleteRes.GetStatus().GetCode().String()).
|
||||
Str("StatusMsg", deleteRes.GetStatus().GetMessage()).
|
||||
Dur("WaitingTime", waitingTime).
|
||||
Int("Retries", retries).
|
||||
Msg("DeleteFile: file isn't ready yet. Retrying")
|
||||
|
||||
time.Sleep(waitingTime)
|
||||
}
|
||||
}
|
||||
|
||||
if deleteRes.GetStatus().GetCode() != rpcv1beta1.Code_CODE_OK {
|
||||
@@ -1072,18 +1092,15 @@ func (f *FileConnector) RenameFile(ctx context.Context, lockID, target string) (
|
||||
// add the new file reference to the log context
|
||||
newLogger := logger.With().Str("NewFileReference", targetFileReference.String()).Logger()
|
||||
|
||||
// try to move the file. It mustn't return a 400 or 409
|
||||
// the file might still be processing, so we retry if we get a "TOO_EARLY" code
|
||||
moveRes, err := retryWhileTooEarly(ctx, newLogger, "RenameFile", func() (*providerv1beta1.MoveResponse, error) {
|
||||
gwc, err := f.gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gwc.Move(ctx, &providerv1beta1.MoveRequest{
|
||||
Source: wopiContext.FileReference,
|
||||
Destination: targetFileReference,
|
||||
LockId: lockID,
|
||||
})
|
||||
gwc, err = f.gws.Next()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// try to put the file. It mustn't return a 400 or 409
|
||||
moveRes, err := gwc.Move(ctx, &providerv1beta1.MoveRequest{
|
||||
Source: wopiContext.FileReference,
|
||||
Destination: targetFileReference,
|
||||
LockId: lockID,
|
||||
})
|
||||
if err != nil {
|
||||
newLogger.Error().Err(err).Msg("RenameFile: move failed")
|
||||
|
||||
@@ -1456,36 +1456,6 @@ var _ = Describe("FileConnector", func() {
|
||||
Expect(response.Headers).To(BeNil())
|
||||
})
|
||||
|
||||
It("Delete retries while the file is processing", func() {
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
gatewayClient.On("Delete", mock.Anything, mock.Anything).Return(&providerv1beta1.DeleteResponse{
|
||||
Status: status.NewTooEarly(ctx, "file is processing"),
|
||||
}, nil).Twice()
|
||||
gatewayClient.On("Delete", mock.Anything, mock.Anything).Return(&providerv1beta1.DeleteResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil).Once()
|
||||
|
||||
response, err := fc.DeleteFile(ctx, "newlock")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(response.Status).To(Equal(200))
|
||||
gatewayClient.AssertNumberOfCalls(GinkgoT(), "Delete", 3)
|
||||
})
|
||||
|
||||
It("Delete stops retrying when the context is cancelled", func() {
|
||||
cancelCtx, cancel := context.WithCancel(context.Background())
|
||||
ctx := middleware.WopiContextToCtx(cancelCtx, wopiCtx)
|
||||
|
||||
gatewayClient.On("Delete", mock.Anything, mock.Anything).Return(&providerv1beta1.DeleteResponse{
|
||||
Status: status.NewTooEarly(ctx, "file is processing"),
|
||||
}, nil).Run(func(mock.Arguments) { cancel() }).Once()
|
||||
|
||||
response, err := fc.DeleteFile(ctx, "newlock")
|
||||
Expect(err).To(MatchError(context.Canceled))
|
||||
Expect(response).To(BeNil())
|
||||
gatewayClient.AssertNumberOfCalls(GinkgoT(), "Delete", 1)
|
||||
})
|
||||
|
||||
It("Delete success", func() {
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
@@ -1653,32 +1623,6 @@ var _ = Describe("FileConnector", func() {
|
||||
Expect(rBody["Name"]).To(MatchRegexp(`^[a-zA-Z0-9_-]+ newFile$`))
|
||||
})
|
||||
|
||||
It("Rename retries while the file is processing", func() {
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
gatewayClient.On("Stat", mock.Anything, mock.Anything).Times(1).Return(&providerv1beta1.StatResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
Info: &providerv1beta1.ResourceInfo{
|
||||
Lock: &providerv1beta1.Lock{
|
||||
LockId: "zzz999",
|
||||
Type: providerv1beta1.LockType_LOCK_TYPE_WRITE,
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
gatewayClient.On("Move", mock.Anything, mock.Anything).Return(&providerv1beta1.MoveResponse{
|
||||
Status: status.NewTooEarly(ctx, "resource is processing"),
|
||||
}, nil).Twice()
|
||||
gatewayClient.On("Move", mock.Anything, mock.Anything).Return(&providerv1beta1.MoveResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil).Once()
|
||||
|
||||
response, err := fc.RenameFile(ctx, "zzz999", "newFile.doc")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(response.Status).To(Equal(200))
|
||||
gatewayClient.AssertNumberOfCalls(GinkgoT(), "Move", 3)
|
||||
})
|
||||
|
||||
It("Success", func() {
|
||||
ctx := middleware.WopiContextToCtx(context.Background(), wopiCtx)
|
||||
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
const (
|
||||
// tooEarlyInitialWait is the waiting time before the first retry
|
||||
tooEarlyInitialWait = 20 * time.Millisecond
|
||||
// tooEarlyMaxWait caps the waiting time between retries
|
||||
tooEarlyMaxWait = 5 * time.Second
|
||||
// tooEarlyMaxRetries limits the retries, so the request can't hang forever
|
||||
tooEarlyMaxRetries = 10
|
||||
)
|
||||
|
||||
// statusResponse is implemented by every CS3 response carrying a status
|
||||
type statusResponse interface {
|
||||
GetStatus() *rpcv1beta1.Status
|
||||
}
|
||||
|
||||
// retryWhileTooEarly calls the request until the response status isn't
|
||||
// "TOO_EARLY", which is returned while the target resource is still being
|
||||
// processed (e.g. right after an upload). The waiting time starts at 20ms and
|
||||
// doubles on each retry, capped at 5 seconds.
|
||||
//
|
||||
// The last response is returned if the resource is still processing after all
|
||||
// the retries, so the caller must handle the "TOO_EARLY" code too. Errors abort
|
||||
// the retries immediately, and so does a cancelled context, in which case the
|
||||
// context error is returned.
|
||||
func retryWhileTooEarly[T statusResponse](ctx context.Context, logger zerolog.Logger, msg string, request func() (T, error)) (T, error) {
|
||||
for retries := 0; ; retries++ {
|
||||
res, err := request()
|
||||
if err != nil || res.GetStatus().GetCode() != rpcv1beta1.Code_CODE_TOO_EARLY || retries >= tooEarlyMaxRetries {
|
||||
return res, err
|
||||
}
|
||||
|
||||
waitingTime := min(tooEarlyInitialWait<<retries, tooEarlyMaxWait)
|
||||
logger.Warn().
|
||||
Str("StatusCode", res.GetStatus().GetCode().String()).
|
||||
Str("StatusMsg", res.GetStatus().GetMessage()).
|
||||
Dur("WaitingTime", waitingTime).
|
||||
Int("Retries", retries).
|
||||
Msg(msg + ": file isn't ready yet. Retrying")
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return res, ctx.Err()
|
||||
case <-time.After(waitingTime):
|
||||
// nothing to do, the waiting time elapsed so we just retry the request
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,14 +88,14 @@ type StorageRegistry struct {
|
||||
|
||||
// Cache holds cache config
|
||||
type Cache struct {
|
||||
ProviderCacheStore string `yaml:"provider_cache_store" env:"OCIS_CACHE_STORE;GATEWAY_PROVIDER_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheNodes []string `yaml:"provider_cache_nodes" env:"OCIS_CACHE_STORE_NODES;GATEWAY_PROVIDER_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheDatabase string `yaml:"provider_cache_database" env:"OCIS_CACHE_DATABASE;GATEWAY_PROVIDER_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable GATEWAY_PROVIDER_CACHE_DATABASE instead."`
|
||||
ProviderCacheTTL time.Duration `yaml:"provider_cache_ttl" env:"OCIS_CACHE_TTL;GATEWAY_PROVIDER_CACHE_TTL" desc:"Default time to live for user info in the cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheDisablePersistence bool `yaml:"provider_cache_disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;GATEWAY_PROVIDER_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the provider cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
ProviderCacheAuthUsername string `yaml:"provider_cache_auth_username" env:"OCIS_CACHE_AUTH_USERNAME;GATEWAY_PROVIDER_CACHE_AUTH_USERNAME" desc:"The username to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
ProviderCacheAuthPassword string `yaml:"provider_cache_auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;GATEWAY_PROVIDER_CACHE_AUTH_PASSWORD" desc:"The password to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
ProviderCacheEnableTLS bool `yaml:"provider_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GATEWAY_PROVIDER_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
ProviderCacheTLSInsecure bool `yaml:"provider_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GATEWAY_PROVIDER_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
ProviderCacheTLSRootCACertificate string `yaml:"provider_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GATEWAY_PROVIDER_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
ProviderCacheStore string `yaml:"provider_cache_store" env:"OCIS_CACHE_STORE;GATEWAY_PROVIDER_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheNodes []string `yaml:"provider_cache_nodes" env:"OCIS_CACHE_STORE_NODES;GATEWAY_PROVIDER_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheDatabase string `yaml:"provider_cache_database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
ProviderCacheTTL time.Duration `yaml:"provider_cache_ttl" env:"OCIS_CACHE_TTL;GATEWAY_PROVIDER_CACHE_TTL" desc:"Default time to live for user info in the cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
ProviderCacheDisablePersistence bool `yaml:"provider_cache_disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;GATEWAY_PROVIDER_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the provider cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
ProviderCacheAuthUsername string `yaml:"provider_cache_auth_username" env:"OCIS_CACHE_AUTH_USERNAME;GATEWAY_PROVIDER_CACHE_AUTH_USERNAME" desc:"The username to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
ProviderCacheAuthPassword string `yaml:"provider_cache_auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;GATEWAY_PROVIDER_CACHE_AUTH_PASSWORD" desc:"The password to use for authentication. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
ProviderCacheEnableTLS bool `yaml:"provider_cache_enable_tls" env:"OCIS_CACHE_ENABLE_TLS;GATEWAY_PROVIDER_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
ProviderCacheTLSInsecure bool `yaml:"provider_cache_tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;GATEWAY_PROVIDER_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
ProviderCacheTLSRootCACertificate string `yaml:"provider_cache_tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;GATEWAY_PROVIDER_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
}
|
||||
@@ -173,7 +173,7 @@ func (api DriveItemPermissionsApi) CreateLink(w http.ResponseWriter, r *http.Req
|
||||
|
||||
var createLink libregraph.DriveItemCreateLink
|
||||
if err = StrictJSONUnmarshal(r.Body, &createLink); err != nil {
|
||||
logger.Error().Err(err).Msg("could not create link: invalid body schema definition")
|
||||
logger.Error().Err(err).Interface("body", r.Body).Msg("could not create link: invalid body schema definition")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition")
|
||||
return
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func (api DriveItemPermissionsApi) CreateSpaceRootLink(w http.ResponseWriter, r
|
||||
|
||||
var createLink libregraph.DriveItemCreateLink
|
||||
if err = StrictJSONUnmarshal(r.Body, &createLink); err != nil {
|
||||
logger.Error().Err(err).Msg("could not create link: invalid body schema definition")
|
||||
logger.Error().Err(err).Interface("body", r.Body).Msg("could not create link: invalid body schema definition")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@ func (g Graph) CreateAppRoleAssignment(w http.ResponseWriter, r *http.Request) {
|
||||
// DeleteAppRoleAssignment implements the Service interface.
|
||||
func (g Graph) DeleteAppRoleAssignment(w http.ResponseWriter, r *http.Request) {
|
||||
logger := g.logger.SubloggerWithRequestID(r.Context())
|
||||
logger.Info().Msg("calling delete appRoleAssignment")
|
||||
logger.Info().Interface("body", r.Body).Msg("calling delete appRoleAssignment")
|
||||
|
||||
userID := chi.URLParam(r, "userID")
|
||||
|
||||
|
||||
@@ -444,7 +444,7 @@ func (g Graph) createDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
|
||||
|
||||
drive := libregraph.Drive{}
|
||||
if err := StrictJSONUnmarshal(r.Body, &drive); err != nil {
|
||||
logger.Debug().Err(err).Msg("could not create drive: invalid body schema definition")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not create drive: invalid body schema definition")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition")
|
||||
return
|
||||
}
|
||||
@@ -582,7 +582,7 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
|
||||
|
||||
drive := libregraph.DriveUpdate{}
|
||||
if err = StrictJSONUnmarshal(r.Body, &drive); err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update drive, invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not update drive, invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: error: %v", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (g Graph) PostEducationClass(w http.ResponseWriter, r *http.Request) {
|
||||
class := libregraph.NewEducationClassWithDefaults()
|
||||
err := StrictJSONUnmarshal(r.Body, class)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not create education class: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not create education class: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func (g Graph) PatchEducationClass(w http.ResponseWriter, r *http.Request) {
|
||||
changes := libregraph.NewEducationClassWithDefaults()
|
||||
err = StrictJSONUnmarshal(r.Body, changes)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not change class: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not change class: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -315,7 +315,10 @@ func (g Graph) PostEducationClassMember(w http.ResponseWriter, r *http.Request)
|
||||
memberRef := libregraph.NewMemberReference()
|
||||
err = StrictJSONUnmarshal(r.Body, memberRef)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not add class member: invalid request body")
|
||||
logger.Debug().
|
||||
Err(err).
|
||||
Interface("body", r.Body).
|
||||
Msg("could not add class member: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -458,7 +461,10 @@ func (g Graph) PostEducationClassTeacher(w http.ResponseWriter, r *http.Request)
|
||||
memberRef := libregraph.NewMemberReference()
|
||||
err = StrictJSONUnmarshal(r.Body, memberRef)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not add class teacher: invalid request body")
|
||||
logger.Debug().
|
||||
Err(err).
|
||||
Interface("body", r.Body).
|
||||
Msg("could not add class teacher: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (g Graph) PostEducationSchool(w http.ResponseWriter, r *http.Request) {
|
||||
school := libregraph.NewEducationSchool()
|
||||
err := StrictJSONUnmarshal(r.Body, school)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not create school: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not create school: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -131,7 +131,7 @@ func (g Graph) PatchEducationSchool(w http.ResponseWriter, r *http.Request) {
|
||||
school := libregraph.NewEducationSchool()
|
||||
err = StrictJSONUnmarshal(r.Body, school)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update school: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not update school: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -330,7 +330,10 @@ func (g Graph) PostEducationSchoolUser(w http.ResponseWriter, r *http.Request) {
|
||||
memberRef := libregraph.NewMemberReference()
|
||||
err = StrictJSONUnmarshal(r.Body, memberRef)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not add school user: invalid request body")
|
||||
logger.Debug().
|
||||
Err(err).
|
||||
Interface("body", r.Body).
|
||||
Msg("could not add school user: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -482,7 +485,10 @@ func (g Graph) PostEducationSchoolClass(w http.ResponseWriter, r *http.Request)
|
||||
memberRef := libregraph.NewMemberReference()
|
||||
err = StrictJSONUnmarshal(r.Body, memberRef)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not add school class: invalid request body")
|
||||
logger.Debug().
|
||||
Err(err).
|
||||
Interface("body", r.Body).
|
||||
Msg("could not add school class: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,11 +52,11 @@ func (g Graph) GetEducationUsers(w http.ResponseWriter, r *http.Request) {
|
||||
// PostEducationUser implements the Service interface.
|
||||
func (g Graph) PostEducationUser(w http.ResponseWriter, r *http.Request) {
|
||||
logger := g.logger.SubloggerWithRequestID(r.Context())
|
||||
logger.Info().Msg("calling create education user")
|
||||
logger.Info().Interface("body", r.Body).Msg("calling create education user")
|
||||
u := libregraph.NewEducationUser()
|
||||
err := StrictJSONUnmarshal(r.Body, u)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not create education user: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not create education user: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %v", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -321,7 +321,7 @@ func (g Graph) PatchEducationUser(w http.ResponseWriter, r *http.Request) {
|
||||
changes := libregraph.NewEducationUser()
|
||||
err = StrictJSONUnmarshal(r.Body, changes)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update education user: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not update education user: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest,
|
||||
fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
|
||||
@@ -99,7 +99,7 @@ func (g Graph) PostGroup(w http.ResponseWriter, r *http.Request) {
|
||||
grp := libregraph.NewGroup()
|
||||
err := StrictJSONUnmarshal(r.Body, grp)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not create group: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not create group: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -164,13 +164,13 @@ func (g Graph) PatchGroup(w http.ResponseWriter, r *http.Request) {
|
||||
changes := libregraph.NewGroup()
|
||||
err = StrictJSONUnmarshal(r.Body, changes)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not change group: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not change group: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if reflect.ValueOf(*changes).IsZero() {
|
||||
logger.Debug().Msg("ignoring empyt request body")
|
||||
logger.Debug().Interface("body", r.Body).Msg("ignoring empyt request body")
|
||||
render.Status(r, http.StatusNoContent)
|
||||
render.NoContent(w, r)
|
||||
return
|
||||
@@ -370,7 +370,10 @@ func (g Graph) PostGroupMember(w http.ResponseWriter, r *http.Request) {
|
||||
memberRef := libregraph.NewMemberReference()
|
||||
err = StrictJSONUnmarshal(r.Body, memberRef)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not add group member: invalid request body")
|
||||
logger.Debug().
|
||||
Err(err).
|
||||
Interface("body", r.Body).
|
||||
Msg("could not add group member: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ func (g Graph) AssignTags(w http.ResponseWriter, r *http.Request) {
|
||||
)
|
||||
|
||||
if err := StrictJSONUnmarshal(r.Body, &assignment); err != nil {
|
||||
g.logger.Debug().Err(err).Msg("could not decode tag assignment request")
|
||||
g.logger.Debug().Err(err).Interface("body", r.Body).Msg("could not decode tag assignment request")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition")
|
||||
return
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func (g Graph) UnassignTags(w http.ResponseWriter, r *http.Request) {
|
||||
)
|
||||
|
||||
if err := StrictJSONUnmarshal(r.Body, &unassignment); err != nil {
|
||||
g.logger.Debug().Err(err).Msg("could not decode tag assignment request")
|
||||
g.logger.Debug().Err(err).Interface("body", r.Body).Msg("could not decode tag assignment request")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "invalid body schema definition")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -386,11 +386,11 @@ func (g Graph) GetUsers(w http.ResponseWriter, r *http.Request) {
|
||||
username, instancename := g.parseExternalSearch(odataReq)
|
||||
|
||||
switch {
|
||||
case odataReq.Query.Filter != nil:
|
||||
users, err = g.applyUserFilter(r.Context(), odataReq, nil)
|
||||
case username != "" && instancename != "" && g.contextUserHasExternalSharePermission(r.Context()):
|
||||
users = make([]*libregraph.User, 1)
|
||||
users[0], err = g.identityBackend.GetPreciseUser(r.Context(), username, instancename, odataReq)
|
||||
case odataReq.Query.Filter != nil:
|
||||
users, err = g.applyUserFilter(r.Context(), odataReq, nil)
|
||||
default:
|
||||
users, err = g.identityBackend.GetUsers(r.Context(), odataReq)
|
||||
}
|
||||
@@ -857,7 +857,7 @@ func (g Graph) PatchMe(w http.ResponseWriter, r *http.Request) {
|
||||
changes := libregraph.NewUserUpdate()
|
||||
err := StrictJSONUnmarshal(r.Body, changes)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update user: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not update user: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest,
|
||||
fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
@@ -904,7 +904,7 @@ func (g Graph) PatchUser(w http.ResponseWriter, r *http.Request) {
|
||||
changes := libregraph.NewUserUpdate()
|
||||
err = StrictJSONUnmarshal(r.Body, changes)
|
||||
if err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update user: invalid request body")
|
||||
logger.Debug().Err(err).Interface("body", r.Body).Msg("could not update user: invalid request body")
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest,
|
||||
fmt.Sprintf("invalid request body: %s", err.Error()))
|
||||
return
|
||||
@@ -945,7 +945,7 @@ func (g Graph) patchUser(w http.ResponseWriter, r *http.Request, nameOrID string
|
||||
}
|
||||
|
||||
if reflect.ValueOf(*changes).IsZero() {
|
||||
logger.Debug().Msg("ignoring empty request body")
|
||||
logger.Debug().Interface("body", r.Body).Msg("ignoring empty request body")
|
||||
render.Status(r, http.StatusNoContent)
|
||||
render.NoContent(w, r)
|
||||
return
|
||||
|
||||
@@ -610,165 +610,6 @@ var _ = Describe("Users", func() {
|
||||
})
|
||||
})
|
||||
|
||||
// vaultRole is a role bundle that grants vault mode, vaultLessRole is one that does not.
|
||||
const (
|
||||
vaultRole = "vault-granting-role-ID"
|
||||
vaultLessRole = "ordinary-role-ID"
|
||||
eligibleUser = "25cb7bc0-3168-4a0c-adbe-396f478ad494"
|
||||
otherUser = "2713f1d5-6822-42bd-ad56-9f6c55a3a8fa"
|
||||
)
|
||||
|
||||
// expectRoles makes the settings service report both roles, only one of which
|
||||
// carries the vault mode permission.
|
||||
expectRoles := func() {
|
||||
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListBundlesResponse{
|
||||
Bundles: []*settingsmsg.Bundle{
|
||||
{
|
||||
Id: vaultRole,
|
||||
Type: settingsmsg.Bundle_TYPE_ROLE,
|
||||
Settings: []*settingsmsg.Setting{
|
||||
{
|
||||
Name: permission.VaultMode,
|
||||
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: vaultLessRole,
|
||||
Type: settingsmsg.Bundle_TYPE_ROLE,
|
||||
Settings: []*settingsmsg.Setting{
|
||||
{
|
||||
Name: "Some.OtherPermission",
|
||||
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
// expectAssignments stubs ListRoleAssignments (the per-account assignment lookup)
|
||||
// for a single account.
|
||||
expectAssignments := func(accountUUID string, assignments []*settingsmsg.UserRoleAssignment, err error) {
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.MatchedBy(
|
||||
func(in *settings.ListRoleAssignmentsRequest) bool {
|
||||
return in.GetAccountUuid() == accountUUID
|
||||
}), mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, err)
|
||||
}
|
||||
|
||||
Describe("GetUsers with a cross-instance search string", func() {
|
||||
BeforeEach(func() {
|
||||
cfg.MultiInstance.Enabled = true
|
||||
cfg.MultiInstance.QueryRegexp = `^([^@]+)@([^.]+)\.example\.test$`
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Operation: settingsmsg.Permission_OPERATION_UNKNOWN,
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, 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.
|
||||
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)
|
||||
student := &libregraph.User{}
|
||||
student.SetId("precise-student")
|
||||
identityBackend.On("GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(student, nil)
|
||||
|
||||
if !permissionGranted {
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Unset()
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{}, nil)
|
||||
}
|
||||
|
||||
path := "/graph/v1.0/users"
|
||||
if search != "" {
|
||||
path += "?$search=" + url.QueryEscape(search)
|
||||
}
|
||||
if filter != "" {
|
||||
sep := "?"
|
||||
if search != "" {
|
||||
sep = "&"
|
||||
}
|
||||
path += sep + "$filter=" + url.QueryEscape(filter)
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if needsMFA {
|
||||
r = r.WithContext(revactx.SetMFA(r.Context()))
|
||||
}
|
||||
svc.GetUsers(rr, r)
|
||||
|
||||
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("search string doesn't match the cross-instance pattern",
|
||||
`"not-a-cross-instance-string"`, "", true, false),
|
||||
Entry("no $search present at all",
|
||||
"", "", true, true),
|
||||
Entry("caller lacks external-share permission",
|
||||
`"student@school4.example.test"`, "", false, false),
|
||||
)
|
||||
|
||||
It("resolves a legitimate cross-instance share when no $filter is present", func() {
|
||||
student := &libregraph.User{}
|
||||
student.SetId("precise-student")
|
||||
identityBackend.On("GetPreciseUser", mock.Anything, "student", "school2", mock.Anything).
|
||||
Return(student, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet,
|
||||
"/graph/v1.0/users?$search="+url.QueryEscape(`"student@school2.example.test"`), 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("precise-student"))
|
||||
identityBackend.AssertNotCalled(GinkgoT(), "GetUsers", mock.Anything, mock.Anything)
|
||||
})
|
||||
|
||||
It("still runs the filter end-to-end — keeping the eligible user and dropping the ineligible one — when the search string also matches the cross-instance pattern", func() {
|
||||
eligible := &libregraph.User{}
|
||||
eligible.SetId(eligibleUser)
|
||||
ineligible := &libregraph.User{}
|
||||
ineligible.SetId(otherUser)
|
||||
identityBackend.On("GetUsers", mock.Anything, mock.Anything).
|
||||
Return([]*libregraph.User{eligible, ineligible}, nil)
|
||||
|
||||
expectRoles()
|
||||
expectAssignments(eligibleUser, []*settingsmsg.UserRoleAssignment{
|
||||
{Id: "assignment-ID", AccountUuid: eligibleUser, RoleId: vaultRole},
|
||||
}, nil)
|
||||
expectAssignments(otherUser, []*settingsmsg.UserRoleAssignment{
|
||||
{Id: "other-assignment-ID", AccountUuid: otherUser, RoleId: vaultLessRole},
|
||||
}, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet,
|
||||
"/graph/v1.0/users?$search="+url.QueryEscape(`"student@school3.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())
|
||||
|
||||
ids := make([]string, 0, len(res.Value))
|
||||
for _, u := range res.Value {
|
||||
ids = append(ids, u.GetId())
|
||||
}
|
||||
Expect(ids).To(ConsistOf(eligibleUser))
|
||||
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("GetUsers handles unsupported or invalid filters",
|
||||
func(filter string, status int) {
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
@@ -860,7 +701,52 @@ var _ = Describe("Users", func() {
|
||||
)
|
||||
|
||||
Describe("the vaultEligible filter", func() {
|
||||
const thirdUser = "3a6e6e0e-3f8b-4e3e-9f8b-1a2b3c4d5e6f"
|
||||
// vaultRole is a role bundle that grants vault mode, vaultLessRole is one that does not.
|
||||
const (
|
||||
vaultRole = "vault-granting-role-ID"
|
||||
vaultLessRole = "ordinary-role-ID"
|
||||
eligibleUser = "25cb7bc0-3168-4a0c-adbe-396f478ad494"
|
||||
otherUser = "2713f1d5-6822-42bd-ad56-9f6c55a3a8fa"
|
||||
thirdUser = "3a6e6e0e-3f8b-4e3e-9f8b-1a2b3c4d5e6f"
|
||||
)
|
||||
|
||||
// expectRoles makes the settings service report both roles, only one of which
|
||||
// carries the vault mode permission.
|
||||
expectRoles := func() {
|
||||
roleService.On("ListRoles", mock.Anything, mock.Anything, mock.Anything).Return(&settings.ListBundlesResponse{
|
||||
Bundles: []*settingsmsg.Bundle{
|
||||
{
|
||||
Id: vaultRole,
|
||||
Type: settingsmsg.Bundle_TYPE_ROLE,
|
||||
Settings: []*settingsmsg.Setting{
|
||||
{
|
||||
Name: permission.VaultMode,
|
||||
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Id: vaultLessRole,
|
||||
Type: settingsmsg.Bundle_TYPE_ROLE,
|
||||
Settings: []*settingsmsg.Setting{
|
||||
{
|
||||
Name: "Some.OtherPermission",
|
||||
Value: &settingsmsg.Setting_PermissionValue{PermissionValue: &settingsmsg.Permission{}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
// expectAssignments stubs ListRoleAssignments (the per-account assignment lookup)
|
||||
// for a single account.
|
||||
expectAssignments := func(accountUUID string, assignments []*settingsmsg.UserRoleAssignment, err error) {
|
||||
roleService.On("ListRoleAssignments", mock.Anything, mock.MatchedBy(
|
||||
func(in *settings.ListRoleAssignmentsRequest) bool {
|
||||
return in.GetAccountUuid() == accountUUID
|
||||
}), mock.Anything).Return(&settings.ListRoleAssignmentsResponse{Assignments: assignments}, err)
|
||||
}
|
||||
|
||||
// requestVaultEligibleUsers builds a GetUsers request for filter, executes it against
|
||||
// svc, and unmarshals a successful response body into a userList. It fails the test
|
||||
@@ -1834,44 +1720,6 @@ var _ = Describe("Users", func() {
|
||||
Expect(res.Value[0].GetId()).To(Equal("federated"))
|
||||
Expect(res.Value[0].GetUserType()).To(Equal("Federated"))
|
||||
})
|
||||
It("runs the Federated filter, not GetPreciseUser, when the search string also matches the cross-instance pattern", func() {
|
||||
cfg.MultiInstance.Enabled = true
|
||||
cfg.MultiInstance.QueryRegexp = `^([^@]+)@([^.]+)\.example\.test$`
|
||||
svc, _ = service.NewService(
|
||||
service.Config(cfg),
|
||||
service.WithGatewaySelector(gatewaySelector),
|
||||
service.EventsPublisher(&eventsPublisher),
|
||||
service.WithIdentityBackend(identityBackend),
|
||||
service.WithRoleService(roleService),
|
||||
service.WithValueService(valueService),
|
||||
service.PermissionService(permissionService),
|
||||
)
|
||||
|
||||
gatewayClient.On("FindAcceptedUsers", mock.Anything, mock.Anything).Return(&invitepb.FindAcceptedUsersResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
AcceptedUsers: []*userv1beta1.User{},
|
||||
}, nil)
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Operation: settingsmsg.Permission_OPERATION_UNKNOWN,
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
r := httptest.NewRequest(http.MethodGet,
|
||||
"/graph/v1.0/users?$search="+url.QueryEscape(`"student@school2.example.test"`)+
|
||||
"&$filter="+url.QueryEscape("userType eq 'Federated'"), 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())
|
||||
identityBackend.AssertNotCalled(GinkgoT(), "GetPreciseUser", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
})
|
||||
It("does not list federated users when filtering for 'Member' users", func() {
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{}, nil)
|
||||
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// configFilePerm is the permission mask used when rewriting ocis.yaml, matching
|
||||
// the mask `ocis init` uses to create it.
|
||||
const configFilePerm = 0o600
|
||||
|
||||
// serviceUserConfigKeys maps an IDM service user (the ou=sysusers entries plus
|
||||
// the bootstrap password keys) to the ocis.yaml key paths that must hold the
|
||||
// same secret so services can still bind to LDAP after a password reset.
|
||||
//
|
||||
// reva, libregraph and idp share OCIS_LDAP_BIND_PASSWORD across several
|
||||
// services but bind as distinct DNs, so their bind_password lives under
|
||||
// different service sections. The idm.service_user_passwords.* keys are what
|
||||
// `ocis init` writes and what re-bootstrapping a fresh database would read.
|
||||
var serviceUserConfigKeys = map[string][][]string{
|
||||
"reva": {
|
||||
{"auth_basic", "auth_providers", "ldap", "bind_password"},
|
||||
{"users", "drivers", "ldap", "bind_password"},
|
||||
{"groups", "drivers", "ldap", "bind_password"},
|
||||
{"idm", "service_user_passwords", "reva_password"},
|
||||
},
|
||||
"libregraph": {
|
||||
{"graph", "identity", "ldap", "bind_password"},
|
||||
{"idm", "service_user_passwords", "idm_password"},
|
||||
},
|
||||
"idp": {
|
||||
{"idp", "ldap", "bind_password"},
|
||||
{"idm", "service_user_passwords", "idp_password"},
|
||||
},
|
||||
}
|
||||
|
||||
// syncServiceUserPasswordInConfig rewrites the bind_password / service user
|
||||
// password keys associated with the given service user to newPassword,
|
||||
// preserving the rest of the document (including comments and unrelated keys).
|
||||
// It returns the updated document, the dotted paths that were actually changed,
|
||||
// and any error. Paths that are not present in the document are skipped.
|
||||
func syncServiceUserPasswordInConfig(data []byte, userName, newPassword string) ([]byte, []string, error) {
|
||||
paths, ok := serviceUserConfigKeys[userName]
|
||||
if !ok {
|
||||
// Not a known service user with bind config to sync.
|
||||
return data, nil, nil
|
||||
}
|
||||
|
||||
var root yaml.Node
|
||||
if err := yaml.Unmarshal(data, &root); err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to parse config: %w", err)
|
||||
}
|
||||
if len(root.Content) == 0 {
|
||||
return data, nil, nil
|
||||
}
|
||||
doc := root.Content[0]
|
||||
|
||||
updated := make([]string, 0, len(paths))
|
||||
for _, path := range paths {
|
||||
if node := lookupYAMLNode(doc, path); node != nil {
|
||||
node.SetString(newPassword)
|
||||
updated = append(updated, strings.Join(path, "."))
|
||||
}
|
||||
}
|
||||
|
||||
if len(updated) == 0 {
|
||||
return data, nil, nil
|
||||
}
|
||||
|
||||
out, err := yaml.Marshal(&root)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to serialize config: %w", err)
|
||||
}
|
||||
return out, updated, nil
|
||||
}
|
||||
|
||||
// lookupYAMLNode walks a mapping node along path and returns the scalar value
|
||||
// node at the end, or nil if any segment is missing.
|
||||
func lookupYAMLNode(node *yaml.Node, path []string) *yaml.Node {
|
||||
for _, key := range path {
|
||||
if node.Kind != yaml.MappingNode {
|
||||
return nil
|
||||
}
|
||||
var next *yaml.Node
|
||||
for i := 0; i+1 < len(node.Content); i += 2 {
|
||||
if node.Content[i].Value == key {
|
||||
next = node.Content[i+1]
|
||||
break
|
||||
}
|
||||
}
|
||||
if next == nil {
|
||||
return nil
|
||||
}
|
||||
node = next
|
||||
}
|
||||
return node
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// sampleOcisConfig mirrors the relevant subset of an `ocis init` generated
|
||||
// ocis.yaml, carrying the bind_password keys the reva/libregraph/idp service
|
||||
// users are wired into.
|
||||
const sampleOcisConfig = `token_manager:
|
||||
jwt_secret: keepme
|
||||
idm:
|
||||
service_user_passwords:
|
||||
admin_password: adminpw
|
||||
idm_password: OLDIDM
|
||||
reva_password: OLDREVA
|
||||
idp_password: OLDIDP
|
||||
idp:
|
||||
ldap:
|
||||
bind_password: OLDIDP
|
||||
auth_basic:
|
||||
auth_providers:
|
||||
ldap:
|
||||
bind_password: OLDREVA
|
||||
users:
|
||||
drivers:
|
||||
ldap:
|
||||
bind_password: OLDREVA
|
||||
groups:
|
||||
drivers:
|
||||
ldap:
|
||||
bind_password: OLDREVA
|
||||
graph:
|
||||
identity:
|
||||
ldap:
|
||||
bind_password: OLDIDM
|
||||
`
|
||||
|
||||
func getYAMLPath(t *testing.T, data []byte, path ...string) string {
|
||||
t.Helper()
|
||||
var root yaml.Node
|
||||
require.NoError(t, yaml.Unmarshal(data, &root))
|
||||
node := root.Content[0]
|
||||
for _, key := range path {
|
||||
var next *yaml.Node
|
||||
for i := 0; i+1 < len(node.Content); i += 2 {
|
||||
if node.Content[i].Value == key {
|
||||
next = node.Content[i+1]
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotNilf(t, next, "path %v: key %q not found", path, key)
|
||||
node = next
|
||||
}
|
||||
return node.Value
|
||||
}
|
||||
|
||||
func TestSyncServiceUserPasswordReva(t *testing.T) {
|
||||
out, updated, err := syncServiceUserPasswordInConfig([]byte(sampleOcisConfig), "reva", "NEWPW")
|
||||
require.NoError(t, err)
|
||||
|
||||
// reva binds via auth_basic, users and groups, and is bootstrapped via
|
||||
// idm.service_user_passwords.reva_password — all must move to NEWPW.
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "auth_basic", "auth_providers", "ldap", "bind_password"))
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "users", "drivers", "ldap", "bind_password"))
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "groups", "drivers", "ldap", "bind_password"))
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "idm", "service_user_passwords", "reva_password"))
|
||||
|
||||
// Unrelated service users must stay untouched.
|
||||
assert.Equal(t, "OLDIDM", getYAMLPath(t, out, "graph", "identity", "ldap", "bind_password"))
|
||||
assert.Equal(t, "OLDIDP", getYAMLPath(t, out, "idp", "ldap", "bind_password"))
|
||||
assert.Equal(t, "OLDIDM", getYAMLPath(t, out, "idm", "service_user_passwords", "idm_password"))
|
||||
|
||||
// Unrelated keys and comments-free structure must survive the round-trip.
|
||||
assert.Equal(t, "keepme", getYAMLPath(t, out, "token_manager", "jwt_secret"))
|
||||
|
||||
assert.ElementsMatch(t, []string{
|
||||
"auth_basic.auth_providers.ldap.bind_password",
|
||||
"users.drivers.ldap.bind_password",
|
||||
"groups.drivers.ldap.bind_password",
|
||||
"idm.service_user_passwords.reva_password",
|
||||
}, updated)
|
||||
}
|
||||
|
||||
func TestSyncServiceUserPasswordLibregraph(t *testing.T) {
|
||||
out, updated, err := syncServiceUserPasswordInConfig([]byte(sampleOcisConfig), "libregraph", "NEWPW")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "graph", "identity", "ldap", "bind_password"))
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "idm", "service_user_passwords", "idm_password"))
|
||||
// reva keys stay put
|
||||
assert.Equal(t, "OLDREVA", getYAMLPath(t, out, "users", "drivers", "ldap", "bind_password"))
|
||||
|
||||
assert.ElementsMatch(t, []string{
|
||||
"graph.identity.ldap.bind_password",
|
||||
"idm.service_user_passwords.idm_password",
|
||||
}, updated)
|
||||
}
|
||||
|
||||
func TestSyncServiceUserPasswordIdp(t *testing.T) {
|
||||
out, updated, err := syncServiceUserPasswordInConfig([]byte(sampleOcisConfig), "idp", "NEWPW")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "idp", "ldap", "bind_password"))
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "idm", "service_user_passwords", "idp_password"))
|
||||
|
||||
assert.ElementsMatch(t, []string{
|
||||
"idp.ldap.bind_password",
|
||||
"idm.service_user_passwords.idp_password",
|
||||
}, updated)
|
||||
}
|
||||
|
||||
func TestSyncServiceUserPasswordUnknownUser(t *testing.T) {
|
||||
// An arbitrary (non service) user has no bind config to sync; the config
|
||||
// must be returned unchanged with no reported updates.
|
||||
out, updated, err := syncServiceUserPasswordInConfig([]byte(sampleOcisConfig), "einstein", "NEWPW")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, updated)
|
||||
assert.Equal(t, strings.TrimSpace(sampleOcisConfig), strings.TrimSpace(string(out)))
|
||||
}
|
||||
|
||||
func TestSyncServiceUserPasswordMissingKeys(t *testing.T) {
|
||||
// A slim config that omits some bind_password keys: only the present ones
|
||||
// are updated and reported, absent ones are silently skipped.
|
||||
const slim = `idm:
|
||||
service_user_passwords:
|
||||
reva_password: OLDREVA
|
||||
`
|
||||
out, updated, err := syncServiceUserPasswordInConfig([]byte(slim), "reva", "NEWPW")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "NEWPW", getYAMLPath(t, out, "idm", "service_user_passwords", "reva_password"))
|
||||
assert.ElementsMatch(t, []string{"idm.service_user_passwords.reva_password"}, updated)
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -13,7 +12,6 @@ import (
|
||||
"github.com/libregraph/idm/pkg/ldbbolt"
|
||||
"github.com/libregraph/idm/server"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
ocisdefaults "github.com/owncloud/ocis/v2/ocis-pkg/config/defaults"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/idm/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/idm/pkg/config/parser"
|
||||
@@ -23,12 +21,6 @@ import (
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// User account types accepted by the --user-type flag.
|
||||
const (
|
||||
userTypeUser = "user"
|
||||
userTypeService = "service"
|
||||
)
|
||||
|
||||
// ResetPassword is the entrypoint for the resetpassword command
|
||||
func ResetPassword(cfg *config.Config) *cli.Command {
|
||||
return &cli.Command{
|
||||
@@ -45,7 +37,7 @@ func ResetPassword(cfg *config.Config) *cli.Command {
|
||||
&cli.StringFlag{
|
||||
Name: "user-type",
|
||||
Usage: "Type of user account: 'user' (ou=users) or 'service' (ou=sysusers)",
|
||||
Value: userTypeUser,
|
||||
Value: "user",
|
||||
},
|
||||
},
|
||||
Before: func(_ *cli.Context) error {
|
||||
@@ -58,8 +50,8 @@ func ResetPassword(cfg *config.Config) *cli.Command {
|
||||
defer cancel()
|
||||
|
||||
userType := c.String("user-type")
|
||||
if userType != userTypeUser && userType != userTypeService {
|
||||
return fmt.Errorf("invalid --user-type %q: must be %q or %q", userType, userTypeUser, userTypeService)
|
||||
if userType != "user" && userType != "service" {
|
||||
return fmt.Errorf("invalid --user-type %q: must be 'user' or 'service'", userType)
|
||||
}
|
||||
|
||||
return resetPassword(ctx, logger, cfg, c.String("user-name"), userType)
|
||||
@@ -77,7 +69,7 @@ func resetPassword(_ context.Context, logger log.Logger, cfg *config.Config, use
|
||||
}
|
||||
|
||||
ou := "users"
|
||||
if userType == userTypeService {
|
||||
if userType == "service" {
|
||||
ou = "sysusers"
|
||||
}
|
||||
userDN := fmt.Sprintf("uid=%s,ou=%s,%s", userName, ou, servercfg.LDAPBaseDN)
|
||||
@@ -113,66 +105,9 @@ func resetPassword(_ context.Context, logger log.Logger, cfg *config.Config, use
|
||||
fmt.Fprintf(os.Stderr, "Failed to update user password: %v\n", err)
|
||||
}
|
||||
fmt.Printf("Password for user '%s' updated.\n", userDN)
|
||||
|
||||
if userType == userTypeService {
|
||||
syncServiceUserBindConfig(userName, newPw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// syncServiceUserBindConfig keeps ocis.yaml in sync after a service user's
|
||||
// password was changed in the IDM database. Services bind to LDAP as the
|
||||
// service users (e.g. uid=reva,ou=sysusers) using the bind_password from their
|
||||
// config; if only the directory entry is changed those binds start failing on
|
||||
// the next restart, which manifests as admin login returning 401. It rewrites
|
||||
// the matching keys in ocis.yaml when present and always prints the env vars
|
||||
// the operator must ensure carry the new value (covering env-var and
|
||||
// distributed deployments this tool cannot rewrite).
|
||||
func syncServiceUserBindConfig(userName, newPassword string) {
|
||||
if _, known := serviceUserConfigKeys[userName]; !known {
|
||||
return
|
||||
}
|
||||
|
||||
configFile := path.Join(ocisdefaults.BaseConfigPath(), "ocis.yaml")
|
||||
if data, err := os.ReadFile(configFile); err == nil {
|
||||
out, updated, err := syncServiceUserPasswordInConfig(data, userName, newPassword)
|
||||
switch {
|
||||
case err != nil:
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not update bind passwords in %q: %v\n", configFile, err)
|
||||
case len(updated) > 0:
|
||||
if err := os.WriteFile(configFile, out, configFilePerm); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not write updated config %q: %v\n", configFile, err)
|
||||
} else {
|
||||
fmt.Printf("Updated bind passwords in %q:\n", configFile)
|
||||
for _, key := range updated {
|
||||
fmt.Printf(" - %s\n", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not read config %q: %v\n", configFile, err)
|
||||
}
|
||||
|
||||
fmt.Printf("\nIMPORTANT: the '%s' service user is used by oCIS services to bind to LDAP.\n", userName)
|
||||
fmt.Printf("Make sure the following environment variable(s) are set to the new password\n")
|
||||
fmt.Printf("wherever they are configured (env, secrets, per-service yaml), then restart oCIS:\n")
|
||||
fmt.Printf(" - OCIS_LDAP_BIND_PASSWORD (shared) or the per-service variables below\n")
|
||||
for _, env := range serviceUserBindEnvVars[userName] {
|
||||
fmt.Printf(" - %s\n", env)
|
||||
}
|
||||
}
|
||||
|
||||
// serviceUserBindEnvVars lists the per-service bind_password environment
|
||||
// variables that carry the given service user's password, for the operator
|
||||
// guidance message. OCIS_LDAP_BIND_PASSWORD is a single shared variable used by
|
||||
// all of these services, so it is noted separately by the caller rather than
|
||||
// per user.
|
||||
var serviceUserBindEnvVars = map[string][]string{
|
||||
"reva": {"AUTH_BASIC_LDAP_BIND_PASSWORD", "USERS_LDAP_BIND_PASSWORD", "GROUPS_LDAP_BIND_PASSWORD", "IDM_REVASVC_PASSWORD"},
|
||||
"libregraph": {"GRAPH_LDAP_BIND_PASSWORD", "IDM_SVC_PASSWORD"},
|
||||
"idp": {"IDP_LDAP_BIND_PASSWORD", "IDM_IDPSVC_PASSWORD"},
|
||||
}
|
||||
|
||||
func getPassword() (string, error) {
|
||||
fmt.Print("Enter new password: ")
|
||||
bytePassword, err := term.ReadPassword(syscall.Stdin)
|
||||
|
||||
@@ -33,7 +33,6 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/notifications/pkg/channels"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/owncloud/reva/v2/pkg/storagespace"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
cs3mocks "github.com/owncloud/reva/v2/tests/cs3mocks/mocks"
|
||||
"github.com/stretchr/testify/mock"
|
||||
@@ -81,11 +80,6 @@ var _ = Describe("Notifications", func() {
|
||||
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&user.GetUserResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, User: sharer}, nil).Once()
|
||||
gatewayClient.On("GetUser", mock.Anything, mock.Anything).Return(&user.GetUserResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, User: sharee}, nil).Once()
|
||||
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, User: sharer}, nil)
|
||||
// Registered before the catch-all below: testify/mock matches expectations in
|
||||
// registration order, so the more specific vault matcher must come first.
|
||||
gatewayClient.On("Stat", mock.Anything, mock.MatchedBy(func(r *provider.StatRequest) bool {
|
||||
return r.GetRef().GetResourceId().GetStorageId() == utils.VaultStorageProviderID
|
||||
})).Return(&provider.StatResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, Info: &provider.ResourceInfo{Name: "report.pdf", Space: &provider.StorageSpace{Name: "vault space"}}}, nil)
|
||||
gatewayClient.On("Stat", mock.Anything, mock.Anything).Return(&provider.StatResponse{Status: &rpc.Status{Code: rpc.Code_CODE_OK}, Info: &provider.ResourceInfo{Name: "secrets of the board", Space: &provider.StorageSpace{Name: "secret space"}}}, nil)
|
||||
vs = &settingssvc.MockValueService{}
|
||||
vs.GetValueByUniqueIdentifiersFunc = func(ctx context.Context, req *settingssvc.GetValueByUniqueIdentifiersRequest, opts ...client.CallOption) (*settingssvc.GetValueResponse, error) {
|
||||
@@ -276,95 +270,6 @@ https://owncloud.com
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
vaultResourceID := &provider.ResourceId{
|
||||
StorageId: utils.VaultStorageProviderID,
|
||||
SpaceId: "spaceid",
|
||||
OpaqueId: "itemid",
|
||||
}
|
||||
vaultSpaceID := &provider.StorageSpaceId{
|
||||
OpaqueId: storagespace.FormatResourceID(&provider.ResourceId{
|
||||
StorageId: utils.VaultStorageProviderID,
|
||||
SpaceId: "vaultspaceid",
|
||||
OpaqueId: "vaultspaceid",
|
||||
}),
|
||||
}
|
||||
|
||||
DescribeTable("Vault resources are redacted in notifications",
|
||||
func(ev events.Event, mustNotContain string) {
|
||||
received := make(chan *channels.Message, 1)
|
||||
ch := make(chan events.Event)
|
||||
evts := NewEventsNotifier(trace.NewNoopTracerProvider(), ch, capturingChannel{out: received}, log.NewLogger(), gatewaySelector, vs, "",
|
||||
"", "", "", "", "", "",
|
||||
store.Create(), nil, nil)
|
||||
go evts.Run()
|
||||
|
||||
ch <- ev
|
||||
|
||||
var msg *channels.Message
|
||||
select {
|
||||
case msg = <-received:
|
||||
case <-time.Tick(3 * time.Second):
|
||||
Fail("timeout waiting for notification")
|
||||
}
|
||||
|
||||
Expect(msg.Subject).NotTo(ContainSubstring(mustNotContain))
|
||||
Expect(msg.TextBody).NotTo(ContainSubstring(mustNotContain))
|
||||
},
|
||||
|
||||
Entry("Share Created", events.Event{
|
||||
Event: events.ShareCreated{
|
||||
Sharer: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
CTime: utils.TimeToTS(time.Date(2023, 4, 17, 16, 42, 0, 0, time.UTC)),
|
||||
ItemID: vaultResourceID,
|
||||
},
|
||||
}, "report.pdf"),
|
||||
|
||||
Entry("Share Expired", events.Event{
|
||||
Event: events.ShareExpired{
|
||||
ShareOwner: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
ExpiredAt: time.Date(2023, 4, 17, 16, 42, 0, 0, time.UTC),
|
||||
ItemID: vaultResourceID,
|
||||
},
|
||||
}, "report.pdf"),
|
||||
|
||||
Entry("Share Removed", events.Event{
|
||||
Event: events.ShareRemoved{
|
||||
Executant: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
ItemID: vaultResourceID,
|
||||
},
|
||||
}, "report.pdf"),
|
||||
|
||||
Entry("Added to Space", events.Event{
|
||||
Event: events.SpaceShared{
|
||||
Executant: sharer.GetId(),
|
||||
Creator: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
ID: vaultSpaceID,
|
||||
},
|
||||
}, "vault space"),
|
||||
|
||||
Entry("Removed from Space", events.Event{
|
||||
Event: events.SpaceUnshared{
|
||||
Executant: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
ID: vaultSpaceID,
|
||||
},
|
||||
}, "vault space"),
|
||||
|
||||
Entry("Space Expired", events.Event{
|
||||
Event: events.SpaceMembershipExpired{
|
||||
SpaceOwner: sharer.GetId(),
|
||||
GranteeUserID: sharee.GetId(),
|
||||
SpaceID: vaultSpaceID,
|
||||
SpaceName: "vault space",
|
||||
ExpiredAt: time.Date(2023, 4, 17, 16, 42, 0, 0, time.UTC),
|
||||
},
|
||||
}, "vault space"),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("Notifications X-Site Scripting", func() {
|
||||
@@ -1373,17 +1278,6 @@ type testChannel struct {
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// capturingChannel hands the sent message to the caller instead of asserting on it itself,
|
||||
// for tests that need to inspect the message rather than match it exactly.
|
||||
type capturingChannel struct {
|
||||
out chan *channels.Message
|
||||
}
|
||||
|
||||
func (c capturingChannel) SendMessage(_ context.Context, m *channels.Message) error {
|
||||
c.out <- m
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tc testChannel) SendMessage(_ context.Context, m *channels.Message) error {
|
||||
defer GinkgoRecover()
|
||||
|
||||
|
||||
@@ -12,15 +12,6 @@ import (
|
||||
"google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
)
|
||||
|
||||
// vaultRedactedName replaces a file/space name with a generic placeholder when it belongs to
|
||||
// the vault storage provider, so personal data never leaves the vault in a notification email.
|
||||
func vaultRedactedName(storageID, name string) string {
|
||||
if storageID == utils.VaultStorageProviderID {
|
||||
return "a shared item"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func (s eventsNotifier) handleShareCreated(baseCtx context.Context, e events.ShareCreated, eventId string) {
|
||||
logger := s.logger.With().
|
||||
Str("event", "ShareCreated").
|
||||
@@ -78,7 +69,7 @@ func (s eventsNotifier) prepareShareCreated(baseCtx context.Context, logger zero
|
||||
Msg("could not stat resource")
|
||||
return owner, shareFolder, shareLink, ctx, err
|
||||
}
|
||||
shareFolder = vaultRedactedName(e.ItemID.GetStorageId(), resourceInfo.Name)
|
||||
shareFolder = resourceInfo.Name
|
||||
|
||||
shareLink, err = urlJoinPath(s.ocisURL, "files/shares/with-me")
|
||||
if err != nil {
|
||||
@@ -166,7 +157,7 @@ func (s eventsNotifier) prepareShareExpired(baseCtx context.Context, logger zero
|
||||
Msg("could not stat resource")
|
||||
return shareFolder, ctx, err
|
||||
}
|
||||
shareFolder = vaultRedactedName(e.ItemID.GetStorageId(), resourceInfo.GetName())
|
||||
shareFolder = resourceInfo.GetName()
|
||||
|
||||
return shareFolder, ctx, err
|
||||
}
|
||||
@@ -228,7 +219,7 @@ func (s eventsNotifier) prepareShareRemoved(baseCtx context.Context, logger zero
|
||||
Msg("could not stat resource")
|
||||
return executant, shareFolder, ctx, err
|
||||
}
|
||||
shareFolder = vaultRedactedName(e.ItemID.GetStorageId(), resourceInfo.Name)
|
||||
shareFolder = resourceInfo.Name
|
||||
|
||||
executant, err = utils.GetUserWithContext(ctx, e.Executant, gatewayClient)
|
||||
if err != nil {
|
||||
|
||||
@@ -84,7 +84,7 @@ func (s eventsNotifier) prepareSpaceShared(baseCtx context.Context, logger zerol
|
||||
Msg("could not get space info")
|
||||
return executant, spaceName, shareLink, ctx, err
|
||||
}
|
||||
spaceName = vaultRedactedName(resourceID.GetStorageId(), resourceInfo.GetSpace().GetName())
|
||||
spaceName = resourceInfo.GetSpace().GetName()
|
||||
|
||||
shareLink, err = urlJoinPath(s.ocisURL, "f", e.ID.OpaqueId)
|
||||
if err != nil {
|
||||
@@ -169,7 +169,7 @@ func (s eventsNotifier) prepareSpaceUnshared(baseCtx context.Context, logger zer
|
||||
Msg("could not get space info")
|
||||
return executant, spaceName, shareLink, ctx, err
|
||||
}
|
||||
spaceName = vaultRedactedName(resourceID.GetStorageId(), resourceInfo.GetSpace().GetName())
|
||||
spaceName = resourceInfo.GetSpace().GetName()
|
||||
|
||||
shareLink, err = urlJoinPath(s.ocisURL, "f", e.ID.OpaqueId)
|
||||
if err != nil {
|
||||
@@ -220,17 +220,10 @@ func (s eventsNotifier) handleSpaceMembershipExpired(baseCtx context.Context, e
|
||||
return
|
||||
}
|
||||
|
||||
spaceName := e.SpaceName
|
||||
if resourceID, err := storagespace.ParseID(e.SpaceID.GetOpaqueId()); err == nil {
|
||||
spaceName = vaultRedactedName(resourceID.GetStorageId(), spaceName)
|
||||
} else {
|
||||
logger.Error().Err(err).Msg("could not parse resourceid from SpaceID, skipping vault redaction check")
|
||||
}
|
||||
|
||||
emails, err := s.render(ctx, email.MembershipExpired,
|
||||
"SpaceGrantee",
|
||||
map[string]string{
|
||||
"SpaceName": spaceName,
|
||||
"SpaceName": e.SpaceName,
|
||||
"ExpiredAt": e.ExpiredAt.Format("2006-01-02 15:04:05"),
|
||||
}, recipientsInstant, owner.GetDisplayName())
|
||||
if err != nil {
|
||||
|
||||
@@ -357,6 +357,7 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
middleware.AllowAppAuth(cfg.AuthMiddleware.AllowAppAuth),
|
||||
middleware.TraceProvider(traceProvider),
|
||||
),
|
||||
middleware.MultiFactor(cfg.MultiFactorAuthentication, middleware.Logger(logger), middleware.MFAStore(signingKeyStore)),
|
||||
middleware.AccountResolver(
|
||||
middleware.Logger(logger),
|
||||
middleware.UserProvider(userProvider),
|
||||
@@ -368,8 +369,6 @@ func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
middleware.EventsPublisher(publisher),
|
||||
middleware.MultiInstance(cfg.MultiInstance.Enabled, cfg.MultiInstance.InstanceID, cfg.MultiInstance.MasterID, cfg.MultiInstance.MemberClaim, cfg.MultiInstance.GuestClaim, cfg.MultiInstance.GuestRole),
|
||||
),
|
||||
// needs the user resolved by the AccountResolver
|
||||
middleware.MultiFactor(cfg.MultiFactorAuthentication, middleware.Logger(logger), middleware.MFAStore(signingKeyStore)),
|
||||
middleware.SelectorCookie(
|
||||
middleware.Logger(logger),
|
||||
middleware.PolicySelectorConfig(*cfg.PolicySelector),
|
||||
|
||||
@@ -141,7 +141,7 @@ type MFAConfig struct {
|
||||
type Cache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;PROXY_OIDC_USERINFO_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"addresses" env:"OCIS_CACHE_STORE_NODES;PROXY_OIDC_USERINFO_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE;PROXY_OIDC_USERINFO_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable PROXY_OIDC_USERINFO_CACHE_DATABASE instead."`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
Table string `yaml:"table" env:"PROXY_OIDC_USERINFO_CACHE_TABLE" desc:"The database table the store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;PROXY_OIDC_USERINFO_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;PROXY_OIDC_USERINFO_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"pre5.0"`
|
||||
|
||||
@@ -274,14 +274,6 @@ func DefaultPolicies() []config.Policy {
|
||||
Endpoint: "/graph/",
|
||||
Service: "com.owncloud.web.graph",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
Service: "com.owncloud.web.activitylog",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/v1.0/invitations",
|
||||
Service: "com.owncloud.web.invitations",
|
||||
},
|
||||
{
|
||||
Endpoint: "/vault/graph/",
|
||||
Service: "com.owncloud.web.graph",
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -18,22 +16,16 @@ import (
|
||||
|
||||
const defaultMFASessionDuration = 3600
|
||||
|
||||
// mfaSessionDuration returns the configured MFA session duration or the default.
|
||||
func mfaSessionDuration(cfg config.MFAConfig) time.Duration {
|
||||
if cfg.SessionDuration <= 0 {
|
||||
return defaultMFASessionDuration * time.Second
|
||||
}
|
||||
return time.Duration(cfg.SessionDuration) * time.Second
|
||||
}
|
||||
|
||||
// MultiFactor returns a middleware that checks requests for mfa.
|
||||
//
|
||||
// It must run after the AccountResolver, which adds the user to the context.
|
||||
// The user is needed to store and to read the MFA status.
|
||||
// MultiFactor returns a middleware that checks requests for mfa
|
||||
func MultiFactor(cfg config.MFAConfig, opts ...Option) func(next http.Handler) http.Handler {
|
||||
options := newOptions(opts...)
|
||||
logger := options.Logger
|
||||
|
||||
sessionDuration := cfg.SessionDuration
|
||||
if sessionDuration <= 0 {
|
||||
sessionDuration = defaultMFASessionDuration
|
||||
}
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return &MultiFactorAuthentication{
|
||||
next: next,
|
||||
@@ -41,7 +33,7 @@ func MultiFactor(cfg config.MFAConfig, opts ...Option) func(next http.Handler) h
|
||||
enabled: cfg.Enabled,
|
||||
authLevelNames: cfg.AuthLevelNames,
|
||||
store: options.MFAStore,
|
||||
sessionDuration: mfaSessionDuration(cfg),
|
||||
sessionDuration: time.Duration(sessionDuration) * time.Second,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,9 +45,9 @@ type MultiFactorAuthentication struct {
|
||||
enabled bool
|
||||
authLevelNames []string
|
||||
sessionDuration time.Duration
|
||||
// store holds the time of the last request with MFA of a user, so that requests
|
||||
// without claims (e.g. signed-URL downloads) can inherit the MFA status. Nil when
|
||||
// no store is configured.
|
||||
// store persists verified MFA status so that non-OIDC requests (e.g.
|
||||
// signed-URL archiver downloads) can inherit it from the user's most
|
||||
// recent OIDC session. Nil when no store is configured.
|
||||
store microstore.Store
|
||||
}
|
||||
|
||||
@@ -83,14 +75,20 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re
|
||||
claims := oidc.FromContext(ctx)
|
||||
|
||||
if claims == nil {
|
||||
// No OIDC claims, e.g. the request has a signed URL. MFA cannot be determined
|
||||
// No OIDC claims — request was authenticated via a non-OIDC method
|
||||
// (e.g. signed URL, basic auth, app token). MFA cannot be determined
|
||||
// from claims directly.
|
||||
//
|
||||
// Fall back to the stored MFA status from the most recent request with MFA
|
||||
// of the user. This allows, for example, a signed-URL archiver download to
|
||||
// succeed when the user has recently proven MFA in their browser session.
|
||||
if m.readMFAFromStore(ctx) {
|
||||
ctx = revactx.SetMFA(ctx)
|
||||
// Fall back to the persisted MFA status from the user's most recent
|
||||
// OIDC-authenticated session. This allows, for example, a signed-URL
|
||||
// archiver download to succeed when the user has recently proven MFA
|
||||
// in their browser session.
|
||||
if m.store != nil {
|
||||
if u, ok := revactx.ContextGetUser(ctx); ok && u.GetId().GetOpaqueId() != "" {
|
||||
if m.readMFAFromStore(u.GetId().GetOpaqueId()) {
|
||||
ctx = revactx.SetMFA(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m.logger.Debug().Str("path", req.URL.Path).Bool("mfaStatus", revactx.HasMFA(ctx)).Msg("no OIDC claims in context")
|
||||
@@ -107,7 +105,15 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re
|
||||
} else {
|
||||
m.logger.Debug().Str("acr", value).Str("url", req.URL.Path).Msg("mfa authenticated")
|
||||
ctx = revactx.SetMFA(ctx)
|
||||
m.writeMFAToStore(ctx)
|
||||
// Persist the verified MFA status so that subsequent non-OIDC requests
|
||||
// (e.g. signed-URL archiver downloads) can inherit it. The entry is
|
||||
// refreshed on every successful OIDC MFA verification and expires after
|
||||
// the configured session duration if no further OIDC requests are made.
|
||||
if m.store != nil {
|
||||
if u, ok := revactx.ContextGetUser(ctx); ok && u.GetId().GetOpaqueId() != "" {
|
||||
m.writeMFAToStore(u.GetId().GetOpaqueId())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MFA status will only be true if the acr claim contains the proper value,
|
||||
@@ -115,35 +121,18 @@ func (m MultiFactorAuthentication) ServeHTTP(w http.ResponseWriter, req *http.Re
|
||||
m.next.ServeHTTP(w, req.WithContext(ctx))
|
||||
}
|
||||
|
||||
// readMFAFromStore checks if the user had MFA in an OIDC request within the session duration.
|
||||
// The age is checked here because stores like nats-js-kv ignore the expiry of a record.
|
||||
func (m MultiFactorAuthentication) readMFAFromStore(ctx context.Context) bool {
|
||||
userID := mfaUserID(ctx)
|
||||
if m.store == nil || userID == "" {
|
||||
return false
|
||||
}
|
||||
func (m MultiFactorAuthentication) readMFAFromStore(userID string) bool {
|
||||
records, err := m.store.Read(key(userID))
|
||||
if err != nil || len(records) == 0 {
|
||||
return false
|
||||
}
|
||||
verifiedAt, err := strconv.ParseInt(string(records[0].Value), 10, 64)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return time.Since(time.Unix(verifiedAt, 0)) < m.sessionDuration
|
||||
return string(records[0].Value) == "true"
|
||||
}
|
||||
|
||||
// writeMFAToStore stores the time of the last request with MFA of the user, so that requests
|
||||
// without claims (e.g. signed-URL downloads) can inherit the MFA status, see readMFAFromStore.
|
||||
func (m MultiFactorAuthentication) writeMFAToStore(ctx context.Context) {
|
||||
userID := mfaUserID(ctx)
|
||||
if m.store == nil || userID == "" {
|
||||
return
|
||||
}
|
||||
func (m MultiFactorAuthentication) writeMFAToStore(userID string) {
|
||||
if err := m.store.Write(µstore.Record{
|
||||
Key: key(userID),
|
||||
Value: []byte(strconv.FormatInt(time.Now().Unix(), 10)),
|
||||
// redis honors the expiry, nats-js-kv uses the TTL of the bucket instead
|
||||
Key: key(userID),
|
||||
Value: []byte("true"),
|
||||
Expiry: m.sessionDuration,
|
||||
}); err != nil {
|
||||
m.logger.Error().Err(err).Str("userID", userID).Msg("failed to write MFA status to store")
|
||||
@@ -160,12 +149,6 @@ func (m MultiFactorAuthentication) containsMFA(value string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// mfaUserID returns the id of the user in the context, or "" if there is no user.
|
||||
func mfaUserID(ctx context.Context) string {
|
||||
u, _ := revactx.ContextGetUser(ctx)
|
||||
return u.GetId().GetOpaqueId()
|
||||
}
|
||||
|
||||
func key(userID string) string {
|
||||
return "mfa:" + userID
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/oidc"
|
||||
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"go-micro.dev/v4/store"
|
||||
)
|
||||
|
||||
var mfaTestUser = &userpb.User{Id: &userpb.UserId{OpaqueId: "user-1"}}
|
||||
|
||||
// mfaChain mirrors the proxy order: MultiFactor runs after the user is resolved.
|
||||
func mfaChain(cfg config.MFAConfig, s store.Store, hasMFA *bool) http.Handler {
|
||||
resolveUser := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r.WithContext(revactx.ContextSetUser(r.Context(), mfaTestUser)))
|
||||
})
|
||||
}
|
||||
final := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
*hasMFA = revactx.HasMFA(r.Context())
|
||||
})
|
||||
|
||||
return resolveUser(MultiFactor(cfg, Logger(log.NopLogger()), MFAStore(s))(final))
|
||||
}
|
||||
|
||||
func oidcRequest(acr string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, "https://example.com/dav/spaces/vault", nil)
|
||||
return req.WithContext(oidc.NewContext(req.Context(), map[string]any{"acr": acr}))
|
||||
}
|
||||
|
||||
// signedURLRequest has no OIDC claims.
|
||||
func signedURLRequest() *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, "https://example.com/dav/spaces/vault?OC-Signature=abc", nil)
|
||||
return req.WithContext(revactx.ContextSetUser(req.Context(), mfaTestUser))
|
||||
}
|
||||
|
||||
func TestMultiFactor_signedURLInheritsMFAFromOIDCRequest(t *testing.T) {
|
||||
cfg := config.MFAConfig{Enabled: true, AuthLevelNames: []string{"advanced"}, SessionDuration: 60}
|
||||
s := store.NewMemoryStore()
|
||||
var hasMFA bool
|
||||
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), oidcRequest("advanced"))
|
||||
assert.True(t, hasMFA)
|
||||
|
||||
records, err := s.Read(key(mfaTestUser.GetId().GetOpaqueId()))
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, records, 1)
|
||||
assert.Greater(t, records[0].Expiry, time.Duration(0))
|
||||
assert.LessOrEqual(t, records[0].Expiry, 60*time.Second)
|
||||
|
||||
hasMFA = false
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), signedURLRequest())
|
||||
assert.True(t, hasMFA)
|
||||
}
|
||||
|
||||
func TestMultiFactor_noMFAPersistedWithoutRequiredAcr(t *testing.T) {
|
||||
cfg := config.MFAConfig{Enabled: true, AuthLevelNames: []string{"advanced"}, SessionDuration: 60}
|
||||
s := store.NewMemoryStore()
|
||||
var hasMFA bool
|
||||
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), oidcRequest("regular"))
|
||||
assert.False(t, hasMFA)
|
||||
|
||||
_, err := s.Read(key(mfaTestUser.GetId().GetOpaqueId()))
|
||||
assert.ErrorIs(t, err, store.ErrNotFound)
|
||||
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), signedURLRequest())
|
||||
assert.False(t, hasMFA)
|
||||
}
|
||||
|
||||
func TestMultiFactor_signedURLWithoutPriorOIDCRequestHasNoMFA(t *testing.T) {
|
||||
cfg := config.MFAConfig{Enabled: true, AuthLevelNames: []string{"advanced"}, SessionDuration: 60}
|
||||
var hasMFA bool
|
||||
|
||||
mfaChain(cfg, store.NewMemoryStore(), &hasMFA).ServeHTTP(httptest.NewRecorder(), signedURLRequest())
|
||||
assert.False(t, hasMFA)
|
||||
}
|
||||
|
||||
func TestMultiFactor_expiredStoreEntryHasNoMFA(t *testing.T) {
|
||||
cfg := config.MFAConfig{Enabled: true, AuthLevelNames: []string{"advanced"}, SessionDuration: 60}
|
||||
s := store.NewMemoryStore()
|
||||
var hasMFA bool
|
||||
|
||||
verifiedAt := time.Now().Add(-61 * time.Second).Unix()
|
||||
assert.NoError(t, s.Write(&store.Record{
|
||||
Key: key(mfaTestUser.GetId().GetOpaqueId()),
|
||||
Value: []byte(strconv.FormatInt(verifiedAt, 10)),
|
||||
}))
|
||||
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), signedURLRequest())
|
||||
assert.False(t, hasMFA)
|
||||
}
|
||||
|
||||
func TestMultiFactor_disabledDoesNotPersist(t *testing.T) {
|
||||
cfg := config.MFAConfig{Enabled: false, AuthLevelNames: []string{"advanced"}}
|
||||
s := store.NewMemoryStore()
|
||||
var hasMFA bool
|
||||
|
||||
mfaChain(cfg, s, &hasMFA).ServeHTTP(httptest.NewRecorder(), oidcRequest("advanced"))
|
||||
// MultiFactor always sets MFA when disabled, but nothing needs to be persisted
|
||||
assert.True(t, hasMFA)
|
||||
|
||||
_, err := s.Read(key(mfaTestUser.GetId().GetOpaqueId()))
|
||||
assert.ErrorIs(t, err, store.ErrNotFound)
|
||||
}
|
||||
@@ -165,34 +165,3 @@ func TestRouter(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vault /graph/ sub-routes must reach the same service as their non-vault counterpart.
|
||||
func TestRouterVaultGraphSubRoutes(t *testing.T) {
|
||||
cfg := defaults.DefaultConfig()
|
||||
cfg.Policies = defaults.DefaultPolicies()
|
||||
|
||||
reg := registry.GetRegistry()
|
||||
sel := selector.NewSelector(selector.Registry(reg))
|
||||
router := New(sel, cfg.PolicySelector, cfg.Policies, log.NewLogger())
|
||||
|
||||
// Each path must match its own route, not a catch-all.
|
||||
paths := []string{
|
||||
"/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
"/vault/graph/v1beta1/extensions/org.libregraph/activities",
|
||||
"/graph/v1.0/invitations",
|
||||
"/vault/graph/v1.0/invitations",
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
ri, ok := router.Route(r)
|
||||
if !ok {
|
||||
t.Errorf("router.Route failed to route %s", path)
|
||||
continue
|
||||
}
|
||||
|
||||
if ri.endpoint != path {
|
||||
t.Errorf("%s matched endpoint %q, want %q — got routed to the generic graph catch-all instead", path, ri.endpoint, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ type Metadata struct {
|
||||
type Cache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;SETTINGS_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"addresses" env:"OCIS_CACHE_STORE_NODES;SETTINGS_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE;SETTINGS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable SETTINGS_CACHE_DATABASE instead."`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
FileTable string `yaml:"files_table" env:"SETTINGS_FILE_CACHE_TABLE" desc:"The database table the store should use for the file cache." introductionVersion:"pre5.0"`
|
||||
DirectoryTable string `yaml:"directories_table" env:"SETTINGS_DIRECTORY_CACHE_TABLE" desc:"The database table the store should use for the directory cache." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;SETTINGS_CACHE_TTL" desc:"Default time to live for entries in the cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
|
||||
@@ -86,14 +86,14 @@ type OCISDriver struct {
|
||||
|
||||
// Cache holds cache config
|
||||
type Cache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_SYSTEM_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_SYSTEM_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE;STORAGE_SYSTEM_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable STORAGE_SYSTEM_CACHE_DATABASE instead."`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_SYSTEM_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_SYSTEM_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"auth_username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_SYSTEM_CACHE_AUTH_USERNAME" desc:"Username for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_SYSTEM_CACHE_AUTH_PASSWORD" desc:"Password for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_SYSTEM_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_SYSTEM_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_SYSTEM_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_SYSTEM_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_SYSTEM_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_SYSTEM_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_SYSTEM_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"auth_username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_SYSTEM_CACHE_AUTH_USERNAME" desc:"Username for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"auth_password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_SYSTEM_CACHE_AUTH_PASSWORD" desc:"Password for the configured store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_SYSTEM_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_SYSTEM_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_SYSTEM_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
}
|
||||
@@ -224,30 +224,30 @@ type Events struct {
|
||||
|
||||
// FilemetadataCache holds cache config
|
||||
type FilemetadataCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE;STORAGE_USERS_FILEMETADATA_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable STORAGE_USERS_FILEMETADATA_CACHE_DATABASE instead."`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
}
|
||||
|
||||
// IDCache holds cache config
|
||||
type IDCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE;STORAGE_USERS_ID_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"9.0" deprecationInfo:"The global variable OCIS_CACHE_DATABASE is deprecated and will be removed in a future release. Please use local variable STORAGE_USERS_ID_CACHE_DATABASE instead."`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"9.0.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"9.0.0"`
|
||||
}
|
||||
|
||||
// S3Driver is the storage driver configuration when using 's3' storage driver
|
||||
|
||||
@@ -1338,47 +1338,48 @@ class CliContext implements Context {
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the most recently committed blob under the users storage root.
|
||||
*
|
||||
* Reva stages in-flight uploads as "reva-blobstore-upload-*" temp files in the
|
||||
* final blobs directory, so the newest file is not always a valid blob yet -
|
||||
* skip temps and poll until a committed blob shows up.
|
||||
* Finds the most recently written blob in the storage-users blobstore.
|
||||
* Scoped to the users storage root to avoid picking blobs from metadata storage.
|
||||
*
|
||||
* @return string absolute path to a real blob file
|
||||
*/
|
||||
private function findNewestBlobPath(): string {
|
||||
$storageRoot = $this->featureContext->getStorageUsersRoot();
|
||||
$newestPath = null;
|
||||
// Async postprocessing may not have moved the blob to its final
|
||||
// location yet — poll until the directory appears or we give up.
|
||||
$blobDirs = [];
|
||||
$retried = 0;
|
||||
do {
|
||||
$newestMtime = 0;
|
||||
$newestPath = null;
|
||||
foreach (\glob($storageRoot . '/spaces/*/*/blobs', GLOB_ONLYDIR) ?: [] as $blobsDir) {
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($blobsDir, \RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
);
|
||||
foreach ($iterator as $file) {
|
||||
if (!$file->isFile()
|
||||
|| \str_starts_with($file->getFilename(), 'reva-blobstore-upload-')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
$mtime = $file->getMTime();
|
||||
if ($mtime > $newestMtime) {
|
||||
$newestMtime = $mtime;
|
||||
$newestPath = $file->getPathname();
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($newestPath !== null) {
|
||||
$blobDirs = \glob($storageRoot . '/spaces/*/*/blobs', GLOB_ONLYDIR) ?: [];
|
||||
if (!empty($blobDirs)) {
|
||||
break;
|
||||
}
|
||||
$retried++;
|
||||
echo "Committed blob not found under $storageRoot, retrying ($retried)...\n";
|
||||
\usleep(STANDARD_SLEEP_TIME_MICROSEC * 50);
|
||||
echo "Blobstore directories not found under $storageRoot, retrying ($retried)...\n";
|
||||
\usleep(500 * 1000);
|
||||
} while ($retried < STANDARD_RETRY_COUNT);
|
||||
|
||||
Assert::assertNotNull($newestPath, "No committed blob file found under $storageRoot");
|
||||
Assert::assertNotEmpty($blobDirs, "No blobstore directory found under $storageRoot");
|
||||
|
||||
$newestPath = null;
|
||||
$newestMtime = 0;
|
||||
foreach ($blobDirs as $blobsDir) {
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($blobsDir, \RecursiveDirectoryIterator::SKIP_DOTS),
|
||||
);
|
||||
foreach ($iterator as $file) {
|
||||
if (!$file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
$mtime = $file->getMTime();
|
||||
if ($mtime > $newestMtime) {
|
||||
$newestMtime = $mtime;
|
||||
$newestPath = $file->getPathname();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert::assertNotNull($newestPath, "No blob file found under $storageRoot");
|
||||
return $newestPath;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ Feature: backup consistency
|
||||
And user "Alice" uploads a file "filesForUpload/textfile.txt" to "/today.txt" with mtime "today" via TUS inside of the space "Personal" using the WebDAV API
|
||||
# Wait for postprocessing to complete before stopping server to avoid race condition where
|
||||
# backup consistency check finds metadata referencing blobs that haven't been finalized yet
|
||||
And the administrator has waited until the file "today.txt" has finished processing
|
||||
And the administrator waits for "2" seconds
|
||||
And the administrator has stopped the server
|
||||
When the administrator checks the backup consistency using the CLI
|
||||
Then the command should be successful
|
||||
@@ -49,7 +49,6 @@ Feature: backup consistency
|
||||
Given user "Alice" has uploaded file with content "hello world" to "/textfile0.txt"
|
||||
And user "Alice" has uploaded file with content "hello world" to "/textfile0.txt"
|
||||
And user "Alice" has uploaded file with content "hello world" to "/textfile0.txt"
|
||||
And the administrator has waited until the file "textfile0.txt" has finished processing
|
||||
And the administrator has stopped the server
|
||||
When the administrator checks the backup consistency using the CLI
|
||||
Then the command should be successful
|
||||
|
||||
@@ -152,11 +152,6 @@ def main() -> int:
|
||||
"REPORT_TRACING": "false",
|
||||
"BROWSER": "chromium",
|
||||
}
|
||||
if os.environ.get("FEDERATED_NEEDED", "").lower() == "true":
|
||||
federated_url = os.environ["FED_SERVER_URL"]
|
||||
wait_for(lambda: ocis_healthy(federated_url), 120, "ocis-federated")
|
||||
print("ocis-federated ready.")
|
||||
playwright_env["FEDERATED_BASE_URL_OCIS"] = federated_url
|
||||
print(f"Running e2e: {e2e_args}")
|
||||
result = subprocess.run(
|
||||
["bash", "run-e2e.sh"] + shlex.split(e2e_args),
|
||||
|
||||
@@ -74,33 +74,6 @@ if [[ "$ENABLE_WOPI" == "true" ]]; then
|
||||
-e 's/{{- include "ocis.extraVolMounts" \. | nindent 12 }}/{{- include "ocis.extraVolMounts" $ | nindent 12 }}/' \
|
||||
-e 's/{{- include "ocis.extraVolumes" \. | nindent 8 }}/{{- include "ocis.extraVolumes" $ | nindent 8 }}/' \
|
||||
$TPL_DIR/collaboration/deployment.yaml
|
||||
sed -i "s|availableUnifiedRoles: \[\]|availableUnifiedRoles: ['b1e2218d-eef8-4d4c-b82d-0f1a1b48f3b5','a8d5fe5e-96e3-418d-825b-534dbdf22b99','fb6c3e19-e378-47e5-b277-9732f9de6e21','58c63c02-1d89-4572-916a-870abc5a1b7d','2d00ce52-1fc2-4dbc-8b95-a73b73395f5a','1c996275-f1c9-4e71-abdf-a42f6495e960','312c0871-5ef7-4b3a-85b6-0e4074c64049','aa97fe03-7980-45ac-9e50-b325749fd7e6']|" $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
if [[ "$ENABLE_OCM" == "true" ]]; then
|
||||
sed -i '/ocm:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
# enabling the ocm backend service does NOT make the web UI show the
|
||||
# "open-cloud-mesh" app -- that's gated by services.web.config.apps, which
|
||||
# the chart leaves unset by default so it falls back to the ocis binary's
|
||||
# own default list (services/web/pkg/config/defaults/defaultconfig.go),
|
||||
# and that list doesn't include "ocm". Since Helm's `with` fully replaces
|
||||
# the array rather than merging, we must repeat the full default list here
|
||||
# (see run-e2e.py's equivalent gha_web_cfg["apps"].append("ocm") for the
|
||||
# non-k8s path).
|
||||
sed -i '/^ web:/a\
|
||||
config:\
|
||||
apps:\
|
||||
- files\
|
||||
- search\
|
||||
- text-editor\
|
||||
- mermaid-editor\
|
||||
- pdf-viewer\
|
||||
- external\
|
||||
- admin-settings\
|
||||
- epub-reader\
|
||||
- preview\
|
||||
- app-store\
|
||||
- ocm' $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
if [[ "$ENABLE_OCM" == "true" ]]; then
|
||||
@@ -113,12 +86,19 @@ fi
|
||||
|
||||
if [[ "$ENABLE_VAULT" == "true" ]]; then
|
||||
sed -i '/vault:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
sed -i '/mfa:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
# baking keycloak url into the base CSP would affect every other suite that
|
||||
# shares this same values.yaml, breaking their fixed CSP header assertions.
|
||||
sed -i "/defaultSrc:/i\\ - 'https://keycloak:8443/'" $CFG_DIR/values.yaml
|
||||
sed -i "/imgSrc:/i\\ - 'https://keycloak:8443/'" $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
if [[ "$ENABLE_SHORT_ACCESS_TOKEN" == "true" ]]; then
|
||||
sed -i '/shortAccessTokenTest:/{n;s|false|true|}' $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
if [[ "$ENABLE_OIDC_OFFLINE_ACCESS" == "true" ]]; then
|
||||
sed -i "s|webClientScope: 'openid profile email'|webClientScope: 'openid profile email offline_access'|" $CFG_DIR/values.yaml
|
||||
fi
|
||||
|
||||
# copy custom values file
|
||||
cp $CFG_DIR/values.yaml "$CHT_DIR/ci/deployment-values.yaml"
|
||||
@@ -137,10 +137,13 @@
|
||||
- name: IDM_CREATE_DEMO_USERS
|
||||
value: "false"
|
||||
{{- end -}}
|
||||
{{- if eq .appName "storageusersvault" }}
|
||||
{{/* ocis-charts added native support for this service upstream (appName "storageusersvault").
|
||||
The native deployment.yaml already sets STORAGE_USERS_ENABLE_VAULT_MODE,
|
||||
STORAGE_USERS_SERVICE_NAME and STORAGE_USERS_EVENTS_CONSUMER_GROUP itself. */}}
|
||||
{{- if eq .appName "storageusers-vault" }}
|
||||
- name: STORAGE_USERS_ENABLE_VAULT_MODE
|
||||
value: "true"
|
||||
- name: STORAGE_USERS_SERVICE_NAME
|
||||
value: storage-users-vault
|
||||
- name: STORAGE_USERS_EVENTS_CONSUMER_GROUP
|
||||
value: vault-dcfs
|
||||
{{/* Without these overrides this instance falls back to the shared OCIS_CACHE_STORE=nats-js-kv
|
||||
used by the regular storage-users service. Since personal-space IDs are just the user's
|
||||
opaque ID (identical in both instances), the vault instance's existence check on
|
||||
@@ -165,4 +168,10 @@
|
||||
value: "1a01c2c4-4309-4483-a845-842fd56d8622"
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- if and (eq .appName "idp") .Values.shortAccessTokenTest.enabled }}
|
||||
{{/* Shortens the access token lifetime so the oidc/oidc-iframe e2e tests can actually
|
||||
observe a token renewal within their wait window - see values.yaml. */}}
|
||||
- name: IDP_ACCESS_TOKEN_EXPIRATION
|
||||
value: "30"
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,161 @@
|
||||
{{- if .Values.features.vault.enabled }}
|
||||
{{- include "ocis.basicServiceTemplates" (dict "scope" . "appName" "appNameStorageUsers" "appNameSuffix" "vault") -}}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
{{ include "ocis.metadata" . }}
|
||||
spec:
|
||||
{{- include "ocis.selector" . | nindent 2 }}
|
||||
{{- if and (not .Values.autoscaling.enabled) (.Values.replicas) }}
|
||||
replicas: {{ .Values.replicas }}
|
||||
{{- end }}
|
||||
{{- include "ocis.deploymentStrategy" . | nindent 2 }}
|
||||
template:
|
||||
{{- include "ocis.templateMetadata" (dict "scope" $ "configCheck" false) | nindent 4 }}
|
||||
spec:
|
||||
{{- include "ocis.affinity" $ | nindent 6 }}
|
||||
{{- include "ocis.securityContextAndtopologySpreadConstraints" . | nindent 6 }}
|
||||
{{- include "ocis.priorityClassName" $.priorityClassName | nindent 6 }}
|
||||
{{- include "ocis.hostAliases" $ | nindent 6 }}
|
||||
nodeSelector: {{ toYaml $.nodeSelector | nindent 8 }}
|
||||
containers:
|
||||
- name: {{ .appName }}
|
||||
{{- include "ocis.image" $ | nindent 10 }}
|
||||
command: ["ocis"]
|
||||
args: ["storage-users", "server"]
|
||||
{{- include "ocis.containerSecurityContext" . | nindent 10 }}
|
||||
env:
|
||||
{{- include "ocis.serviceRegistry" . | nindent 12 }}
|
||||
{{- include "ocis.events" . | nindent 12 }}
|
||||
{{- include "ocis.cacheStore" . | nindent 12 }}
|
||||
{{- include "ocis.cors" . | nindent 12 }}
|
||||
|
||||
# this is a secondary storage-users instance, dedicated to vault storage
|
||||
# see tests/config/k8s/templates/extra.tpl for STORAGE_USERS_ENABLE_VAULT_MODE
|
||||
# and STORAGE_USERS_SERVICE_NAME
|
||||
|
||||
- name: STORAGE_USERS_GATEWAY_GRPC_ADDR
|
||||
value: {{ .appNameGateway }}:9142
|
||||
|
||||
- name: STORAGE_USERS_LOG_COLOR
|
||||
value: {{ .Values.logging.color | quote }}
|
||||
- name: STORAGE_USERS_LOG_LEVEL
|
||||
value: {{ .Values.logging.level | quote }}
|
||||
- name: STORAGE_USERS_LOG_PRETTY
|
||||
value: {{ .Values.logging.pretty | quote }}
|
||||
|
||||
- name: STORAGE_USERS_TRACING_ENABLED
|
||||
value: "{{ .Values.tracing.enabled }}"
|
||||
- name: STORAGE_USERS_TRACING_TYPE
|
||||
value: {{ .Values.tracing.type | quote }}
|
||||
- name: STORAGE_USERS_TRACING_ENDPOINT
|
||||
value: {{ .Values.tracing.endpoint | quote }}
|
||||
- name: STORAGE_USERS_TRACING_COLLECTOR
|
||||
value: {{ .Values.tracing.collector | quote }}
|
||||
|
||||
- name: STORAGE_USERS_DEBUG_PPROF
|
||||
value: {{ .Values.debug.profiling | quote }}
|
||||
|
||||
- name: STORAGE_USERS_GRPC_ADDR
|
||||
value: 0.0.0.0:9157
|
||||
- name: STORAGE_USERS_DEBUG_ADDR
|
||||
value: 0.0.0.0:9159
|
||||
|
||||
- name: STORAGE_USERS_HTTP_ADDR
|
||||
value: 0.0.0.0:9158
|
||||
- name: STORAGE_USERS_DATA_SERVER_URL
|
||||
value: "http://{{ .appName }}:9158/data"
|
||||
|
||||
- name: STORAGE_USERS_DRIVER
|
||||
value: ocis
|
||||
- name: STORAGE_USERS_OCIS_MAX_CONCURRENCY
|
||||
value: {{ .Values.services.storageusers.storageBackend.driverConfig.ocis.maxConcurrency | quote }}
|
||||
|
||||
- name: STORAGE_USERS_UPLOAD_EXPIRATION
|
||||
value: {{ .Values.services.storageusers.maintenance.cleanUpExpiredUploads.uploadExpiration | quote }}
|
||||
|
||||
- name: STORAGE_USERS_PURGE_TRASH_BIN_PERSONAL_DELETE_BEFORE
|
||||
value: {{ .Values.services.storageusers.maintenance.purgeExpiredTrashBinItems.personalDeleteBefore | quote}}
|
||||
- name: STORAGE_USERS_PURGE_TRASH_BIN_PROJECT_DELETE_BEFORE
|
||||
value: {{ .Values.services.storageusers.maintenance.purgeExpiredTrashBinItems.projectDeleteBefore | quote }}
|
||||
|
||||
- name: STORAGE_USERS_SERVICE_ACCOUNT_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "config.authService" . }}
|
||||
key: service-account-id
|
||||
- name: STORAGE_USERS_SERVICE_ACCOUNT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.serviceAccountSecret" . }}
|
||||
key: service-account-secret
|
||||
|
||||
- name: STORAGE_USERS_STAT_CACHE_STORE
|
||||
value: noop
|
||||
|
||||
- name: STORAGE_USERS_MOUNT_ID
|
||||
valueFrom:
|
||||
configMapKeyRef:
|
||||
name: {{ include "config.storageUsers" . }}
|
||||
key: storage-uuid
|
||||
|
||||
- name: STORAGE_USERS_JWT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.jwtSecret" . }}
|
||||
key: jwt-secret
|
||||
|
||||
- name: OCIS_TRANSFER_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ include "secrets.transferSecret" . }}
|
||||
key: transfer-secret
|
||||
|
||||
- name: OCIS_ASYNC_UPLOADS
|
||||
value: "true"
|
||||
- name: STORAGE_USERS_EVENTS_NUM_CONSUMERS
|
||||
value: {{ .Values.services.storageusers.events.consumer.concurrency | quote }}
|
||||
|
||||
- name: STORAGE_USERS_DATA_GATEWAY_URL
|
||||
value: "http://{{ .appNameFrontend }}:9140/data/"
|
||||
|
||||
{{- include "ocis.caEnv" $ | nindent 12}}
|
||||
{{- include "ocis.extraEnvs" . | nindent 12}}
|
||||
|
||||
{{- include "ocis.livenessProbe" . | nindent 10 }}
|
||||
|
||||
resources: {{ toYaml .resources | nindent 12 }}
|
||||
|
||||
ports:
|
||||
- name: grpc
|
||||
containerPort: 9157
|
||||
- name: http
|
||||
containerPort: 9158
|
||||
- name: metrics-debug
|
||||
containerPort: 9159
|
||||
|
||||
volumeMounts:
|
||||
- name: tmp-volume
|
||||
mountPath: /tmp
|
||||
- name: messaging-system-ca
|
||||
mountPath: /etc/ocis/messaging-system-ca
|
||||
readOnly: true
|
||||
- name: {{ include "ocis.persistence.dataVolumeName" . }}
|
||||
mountPath: /var/lib/ocis
|
||||
{{- include "ocis.caPath" $ | nindent 12}}
|
||||
{{- include "ocis.extraVolMounts" . | nindent 12}}
|
||||
|
||||
{{- include "ocis.imagePullSecrets" $ | nindent 6 }}
|
||||
volumes:
|
||||
- name: tmp-volume
|
||||
emptyDir: {}
|
||||
- name: messaging-system-ca
|
||||
{{ if and (.Values.messagingSystem.external.enabled) (not .Values.messagingSystem.external.tls.certTrusted) }}
|
||||
secret:
|
||||
secretName: {{ include "secrets.messagingSystemCASecret" . }}
|
||||
{{ else }}
|
||||
emptyDir: {}
|
||||
{{ end }}
|
||||
{{- include "ocis.caVolume" $ | nindent 8}}
|
||||
{{- include "ocis.persistence.dataVolume" . | nindent 8 }}
|
||||
{{- include "ocis.extraVolumes" . | nindent 8}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,28 @@
|
||||
{{- if .Values.features.vault.enabled }}
|
||||
{{- include "ocis.basicServiceTemplates" (dict "scope" . "appName" "appNameStorageUsers" "appNameSuffix" "vault") -}}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .appName }}
|
||||
namespace: {{ template "ocis.namespace" . }}
|
||||
labels:
|
||||
app: {{ .appName }}
|
||||
ocis-metrics: enabled
|
||||
{{- include "ocis.labels" . | nindent 4 }}
|
||||
spec:
|
||||
selector:
|
||||
app: {{ .appName }}
|
||||
ports:
|
||||
- name: grpc
|
||||
port: 9157
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.grpc | quote}}
|
||||
- name: http
|
||||
port: 9158
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.http | quote}}
|
||||
- name: metrics-debug
|
||||
port: 9159
|
||||
protocol: TCP
|
||||
appProtocol: {{ .Values.service.appProtocol.http | quote}}
|
||||
{{- end -}}
|
||||
@@ -13,13 +13,13 @@ insecure:
|
||||
oidcIdpInsecure: true
|
||||
ocisHttpApiInsecure: true
|
||||
ocmInsecure: true
|
||||
shortAccessTokenTest:
|
||||
enabled: true
|
||||
features:
|
||||
authapp:
|
||||
enabled: false
|
||||
vault:
|
||||
enabled: false
|
||||
mfa:
|
||||
enabled: false
|
||||
emailNotifications:
|
||||
enabled: false
|
||||
smtp:
|
||||
@@ -51,45 +51,21 @@ features:
|
||||
max: '0'
|
||||
appsIntegration:
|
||||
enabled: false
|
||||
mimetypes:
|
||||
- mime_type: application/vnd.oasis.opendocument.text
|
||||
extension: odt
|
||||
name: OpenDocument
|
||||
description: OpenDocument text document
|
||||
icon: ""
|
||||
default_app: Collabora
|
||||
allow_creation: true
|
||||
- mime_type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
||||
extension: docx
|
||||
name: Microsoft Word
|
||||
description: Microsoft Word document
|
||||
icon: ""
|
||||
default_app: OnlyOffice
|
||||
allow_creation: true
|
||||
- mime_type: text/plain
|
||||
extension: txt
|
||||
name: Plain text
|
||||
description: Plain text file
|
||||
icon: ""
|
||||
default_app: FakeOffice
|
||||
allow_creation: true
|
||||
wopiIntegration:
|
||||
officeSuites:
|
||||
- name: 'Collabora'
|
||||
uri: 'https://collabora:9980'
|
||||
iconURI: 'https://collabora:9980/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9300'
|
||||
product: 'Collabora'
|
||||
enabled: true
|
||||
insecure: true
|
||||
disableProof: true
|
||||
secureViewEnabled: true
|
||||
secureViewEnabled: false
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
- name: 'FakeOffice'
|
||||
uri: 'http://fakeoffice:8080'
|
||||
iconURI: 'http://fakeoffice:8080/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9301'
|
||||
product: 'FakeOffice'
|
||||
enabled: true
|
||||
@@ -101,7 +77,6 @@ features:
|
||||
enabled: false
|
||||
- name: 'OnlyOffice'
|
||||
uri: 'https://onlyoffice:7443'
|
||||
iconURI: 'https://onlyoffice:7443/web-apps/apps/documenteditor/main/resources/img/favicon.ico'
|
||||
wopiSrc: 'http://ocis-server:9302'
|
||||
product: 'OnlyOffice'
|
||||
enabled: true
|
||||
@@ -111,8 +86,6 @@ features:
|
||||
disableChat: true
|
||||
ingress:
|
||||
enabled: false
|
||||
roles:
|
||||
availableUnifiedRoles: []
|
||||
|
||||
http:
|
||||
cors:
|
||||
@@ -178,7 +151,7 @@ services:
|
||||
enabled: true
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
storageusersvault:
|
||||
storageusers-vault:
|
||||
persistence:
|
||||
enabled: false
|
||||
ocm:
|
||||
@@ -196,6 +169,8 @@ services:
|
||||
enabled: true
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
config:
|
||||
webClientScope: 'openid profile email'
|
||||
antivirus:
|
||||
events:
|
||||
consumer:
|
||||
|
||||
+161
-370
@@ -13,22 +13,19 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
procSelfMountInfoPath = "/proc/self/mountinfo"
|
||||
procSelfCgroupPath = "/proc/self/cgroup"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoCgroup is returned when the process is not assigned to a cgroup.
|
||||
// ErrNoCgroup is returned when the process is not in cgroup.
|
||||
ErrNoCgroup = errors.New("process is not in cgroup")
|
||||
// ErrCgroupsNotSupported is returned when the system does not support cgroups.
|
||||
ErrCgroupsNotSupported = errors.New("cgroups is not supported on this system")
|
||||
)
|
||||
|
||||
func fromCgroup(mountInfoPath, cgroupPath string) (uint64, error) {
|
||||
mf, err := os.Open(mountInfoPath)
|
||||
// fromCgroup retrieves the memory limit from the cgroup.
|
||||
// The versionDetector function is used to detect the cgroup version from the mountinfo.
|
||||
func fromCgroup(versionDetector func(mis []mountInfo) (bool, bool)) (uint64, error) {
|
||||
mf, err := os.Open("/proc/self/mountinfo")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to open %s: %w", mountInfoPath, err)
|
||||
return 0, fmt.Errorf("failed to open /proc/self/mountinfo: %w", err)
|
||||
}
|
||||
defer mf.Close()
|
||||
|
||||
@@ -37,9 +34,14 @@ func fromCgroup(mountInfoPath, cgroupPath string) (uint64, error) {
|
||||
return 0, fmt.Errorf("failed to parse mountinfo: %w", err)
|
||||
}
|
||||
|
||||
cf, err := os.Open(cgroupPath)
|
||||
v1, v2 := versionDetector(mis)
|
||||
if !(v1 || v2) {
|
||||
return 0, ErrNoCgroup
|
||||
}
|
||||
|
||||
cf, err := os.Open("/proc/self/cgroup")
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to open %s: %w", cgroupPath, err)
|
||||
return 0, fmt.Errorf("failed to open /proc/self/cgroup: %w", err)
|
||||
}
|
||||
defer cf.Close()
|
||||
|
||||
@@ -48,75 +50,70 @@ func fromCgroup(mountInfoPath, cgroupPath string) (uint64, error) {
|
||||
return 0, fmt.Errorf("failed to parse cgroup file: %w", err)
|
||||
}
|
||||
|
||||
controller, err := selectMemoryController(chs, mis)
|
||||
if v2 {
|
||||
limit, err := getMemoryLimitV2(chs, mis)
|
||||
if err == nil {
|
||||
return limit, nil
|
||||
} else if !v1 {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return getMemoryLimitV1(chs, mis)
|
||||
}
|
||||
|
||||
// detectCgroupVersion detects the cgroup version from the mountinfo.
|
||||
func detectCgroupVersion(mis []mountInfo) (bool, bool) {
|
||||
var v1, v2 bool
|
||||
for _, mi := range mis {
|
||||
switch mi.FilesystemType {
|
||||
case "cgroup":
|
||||
v1 = true
|
||||
case "cgroup2":
|
||||
v2 = true
|
||||
}
|
||||
}
|
||||
return v1, v2
|
||||
}
|
||||
|
||||
// getMemoryLimitV2 retrieves the memory limit from the cgroup v2 controller.
|
||||
func getMemoryLimitV2(chs []cgroupHierarchy, mis []mountInfo) (uint64, error) {
|
||||
// find the cgroup v2 path for the memory controller.
|
||||
// in cgroup v2, the paths are unified and the controller list is empty.
|
||||
idx := slices.IndexFunc(chs, func(ch cgroupHierarchy) bool {
|
||||
return ch.HierarchyID == "0" && ch.ControllerList == ""
|
||||
})
|
||||
if idx == -1 {
|
||||
return 0, errors.New("cgroup v2 path not found")
|
||||
}
|
||||
relPath := chs[idx].CgroupPath
|
||||
|
||||
// find the mountpoint for the cgroup v2 controller.
|
||||
idx = slices.IndexFunc(mis, func(mi mountInfo) bool {
|
||||
return mi.FilesystemType == "cgroup2"
|
||||
})
|
||||
if idx == -1 {
|
||||
return 0, errors.New("cgroup v2 mountpoint not found")
|
||||
}
|
||||
root, mountPoint := mis[idx].Root, mis[idx].MountPoint
|
||||
|
||||
// resolve the actual cgroup path
|
||||
cgroupPath, err := resolveCgroupPath(mountPoint, root, relPath)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if controller.isV2 {
|
||||
return getMemoryLimitV2FromControllerPath(controller.path, mis)
|
||||
}
|
||||
|
||||
return getMemoryLimitV1FromControllerPath(controller.path, mis)
|
||||
// retrieve the memory limit from the memory.max recursively.
|
||||
return walkCgroupV2Hierarchy(cgroupPath, mountPoint)
|
||||
}
|
||||
|
||||
type memoryController struct {
|
||||
path string
|
||||
isV2 bool
|
||||
}
|
||||
|
||||
// selectMemoryController selects v1 when both v1 and v2 are available.
|
||||
func selectMemoryController(chs []cgroupHierarchy, mis []mountInfo) (memoryController, error) {
|
||||
var (
|
||||
v1Path string
|
||||
v2Path string
|
||||
hasV1Entry bool
|
||||
hasV2Entry bool
|
||||
hasV1Mount bool
|
||||
hasV2Mount bool
|
||||
)
|
||||
|
||||
for _, ch := range chs {
|
||||
if !hasV1Entry && ch.HierarchyID != "0" && slices.Contains(strings.Split(ch.ControllerList, ","), "memory") {
|
||||
v1Path = ch.CgroupPath
|
||||
hasV1Entry = true
|
||||
} else if !hasV2Entry && ch.HierarchyID == "0" && ch.ControllerList == "" {
|
||||
v2Path = ch.CgroupPath
|
||||
hasV2Entry = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, mi := range mis {
|
||||
if !hasV1Mount && mi.FilesystemType == "cgroup" && slices.Contains(strings.Split(mi.SuperOptions, ","), "memory") {
|
||||
hasV1Mount = true
|
||||
} else if !hasV2Mount && mi.FilesystemType == "cgroup2" {
|
||||
// cgroup v2 uses a unified hierarchy, so the filesystem type is sufficient
|
||||
hasV2Mount = true
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case hasV1Entry:
|
||||
if !hasV1Mount {
|
||||
return memoryController{}, errors.New("memory controller found in /proc/self/cgroup but no cgroup v1 memory mount found")
|
||||
}
|
||||
return memoryController{path: v1Path}, nil
|
||||
case hasV2Entry:
|
||||
if !hasV2Mount {
|
||||
return memoryController{}, errors.New("cgroup v2 hierarchy found in /proc/self/cgroup but no cgroup2 mount found")
|
||||
}
|
||||
return memoryController{path: v2Path, isV2: true}, nil
|
||||
default:
|
||||
return memoryController{}, ErrNoCgroup
|
||||
}
|
||||
}
|
||||
|
||||
// readMemoryLimitV2FromPath reads a memory limit from a cgroup v2 memory.max file.
|
||||
// It returns [ErrNoLimit] for "max" and preserves [os.ErrNotExist] for a missing file.
|
||||
// readMemoryLimitV2FromPath reads the memory limit for cgroup v2 from the given path.
|
||||
// this function expects the path to be memory.max file.
|
||||
func readMemoryLimitV2FromPath(path string) (uint64, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return 0, err
|
||||
return 0, ErrNoLimit
|
||||
}
|
||||
return 0, fmt.Errorf("failed to read memory.max: %w", err)
|
||||
}
|
||||
@@ -134,21 +131,22 @@ func readMemoryLimitV2FromPath(path string) (uint64, error) {
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
// walkCgroupV2Hierarchy returns the smallest limit between cgroupPath and mountPoint.
|
||||
// It skips missing and unlimited values, returning [ErrNoLimit] if no concrete limit remains.
|
||||
// walkCgroupV2Hierarchy walks up the cgroup v2 hierarchy to find the most restrictive memory limit.
|
||||
func walkCgroupV2Hierarchy(cgroupPath, mountPoint string) (uint64, error) {
|
||||
var (
|
||||
found = false
|
||||
minLimit uint64 = math.MaxUint64
|
||||
found = false
|
||||
minLimit uint64 = math.MaxUint64
|
||||
currentPath = cgroupPath
|
||||
)
|
||||
for currentPath := cgroupPath; ; {
|
||||
for {
|
||||
limit, err := readMemoryLimitV2FromPath(filepath.Join(currentPath, "memory.max"))
|
||||
if err == nil {
|
||||
if err != nil && !errors.Is(err, ErrNoLimit) {
|
||||
return 0, err
|
||||
} else if err == nil {
|
||||
found = true
|
||||
minLimit = min(minLimit, limit)
|
||||
} else if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, ErrNoLimit) {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if currentPath == mountPoint {
|
||||
break
|
||||
}
|
||||
@@ -166,236 +164,83 @@ func walkCgroupV2Hierarchy(cgroupPath, mountPoint string) (uint64, error) {
|
||||
return minLimit, nil
|
||||
}
|
||||
|
||||
// getMemoryLimitV2FromControllerPath prefers mounts rooted closest to the cgroup hierarchy root.
|
||||
func getMemoryLimitV2FromControllerPath(relPath string, mis []mountInfo) (uint64, error) {
|
||||
rootClosestMounts, err := getRootClosestMountCandidates(
|
||||
relPath,
|
||||
mis,
|
||||
func(mi mountInfo) bool {
|
||||
return mi.FilesystemType == "cgroup2"
|
||||
},
|
||||
)
|
||||
// getMemoryLimitV1 retrieves the memory limit from the cgroup v1 controller.
|
||||
func getMemoryLimitV1(chs []cgroupHierarchy, mis []mountInfo) (uint64, error) {
|
||||
// find the cgroup v1 path for the memory controller.
|
||||
idx := slices.IndexFunc(chs, func(ch cgroupHierarchy) bool {
|
||||
return slices.Contains(strings.Split(ch.ControllerList, ","), "memory")
|
||||
})
|
||||
if idx == -1 {
|
||||
return 0, errors.New("cgroup v1 path for memory controller not found")
|
||||
}
|
||||
relPath := chs[idx].CgroupPath
|
||||
|
||||
// find the mountpoint for the cgroup v1 controller.
|
||||
idx = slices.IndexFunc(mis, func(mi mountInfo) bool {
|
||||
return mi.FilesystemType == "cgroup" && slices.Contains(strings.Split(mi.SuperOptions, ","), "memory")
|
||||
})
|
||||
if idx == -1 {
|
||||
return 0, errors.New("cgroup v1 mountpoint for memory controller not found")
|
||||
}
|
||||
root, mountPoint := mis[idx].Root, mis[idx].MountPoint
|
||||
|
||||
// resolve the actual cgroup path
|
||||
cgroupPath, err := resolveCgroupPath(mountPoint, root, relPath)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
limit, found, err := getMemoryLimitFromMountCandidates(
|
||||
rootClosestMounts,
|
||||
func(mi mountInfo) (uint64, bool, error) {
|
||||
cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
stat, err := os.Stat(cgroupPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return 0, false, nil
|
||||
}
|
||||
return 0, false, err
|
||||
}
|
||||
if !stat.IsDir() {
|
||||
return 0, false, fmt.Errorf("cgroup v2 path %s is not a directory", cgroupPath)
|
||||
}
|
||||
|
||||
limit, err := walkCgroupV2Hierarchy(cgroupPath, mi.MountPoint)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
return limit, true, nil
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
} else if found {
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
return 0, errors.New("no usable cgroup v2 memory mount found")
|
||||
// retrieve the memory limit from the memory.stat and memory.limit_in_bytes files.
|
||||
return readMemoryLimitV1FromPath(cgroupPath)
|
||||
}
|
||||
|
||||
// getMemoryLimitV1FromControllerPath prefers mounts rooted closest to the cgroup hierarchy root.
|
||||
func getMemoryLimitV1FromControllerPath(relPath string, mis []mountInfo) (uint64, error) {
|
||||
rootClosestMounts, err := getRootClosestMountCandidates(
|
||||
relPath,
|
||||
mis,
|
||||
func(mi mountInfo) bool {
|
||||
return mi.FilesystemType == "cgroup" && slices.Contains(strings.Split(mi.SuperOptions, ","), "memory")
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
limit, found, err := getMemoryLimitFromMountCandidates(
|
||||
rootClosestMounts,
|
||||
func(mi mountInfo) (uint64, bool, error) {
|
||||
cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
return readMemoryLimitV1FromPath(cgroupPath)
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
} else if found {
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
return 0, errors.New("no usable cgroup v1 memory mount found")
|
||||
// getCgroupV1NoLimit returns the maximum value that is used to represent no limit in cgroup v1.
|
||||
// the max memory limit is max int64, but it should be multiple of the page size.
|
||||
func getCgroupV1NoLimit() uint64 {
|
||||
ps := uint64(os.Getpagesize())
|
||||
return math.MaxInt64 / ps * ps
|
||||
}
|
||||
|
||||
func getRootClosestMountCandidates(
|
||||
relPath string,
|
||||
mis []mountInfo,
|
||||
isCandidate func(mi mountInfo) bool,
|
||||
) ([]mountInfo, error) {
|
||||
var (
|
||||
rootClosestMounts []mountInfo
|
||||
maxDepth = -1
|
||||
)
|
||||
for _, mi := range mis {
|
||||
if !isCandidate(mi) {
|
||||
continue
|
||||
}
|
||||
|
||||
cgroupPath, err := resolveCgroupPath(mi.MountPoint, mi.Root, relPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if cgroupPath == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(cgroupPath); errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(mi.MountPoint, cgroupPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
depth := 0
|
||||
if rel != "." {
|
||||
depth = strings.Count(rel, string(filepath.Separator)) + 1
|
||||
}
|
||||
|
||||
switch {
|
||||
case depth > maxDepth:
|
||||
rootClosestMounts = []mountInfo{mi}
|
||||
maxDepth = depth
|
||||
case depth == maxDepth:
|
||||
rootClosestMounts = append(rootClosestMounts, mi)
|
||||
}
|
||||
}
|
||||
|
||||
return rootClosestMounts, nil
|
||||
}
|
||||
|
||||
// getLimit may return found=false to skip a candidate or [ErrNoLimit] for no usable limit.
|
||||
// Other errors and conflicting concrete limits are returned.
|
||||
func getMemoryLimitFromMountCandidates(
|
||||
mis []mountInfo,
|
||||
getLimit func(mi mountInfo) (uint64, bool, error),
|
||||
) (uint64, bool, error) {
|
||||
var (
|
||||
firstErr, conflictErr error
|
||||
sawNoLimit, limitFound bool
|
||||
firstLimit uint64
|
||||
)
|
||||
for _, mi := range mis {
|
||||
limit, found, err := getLimit(mi)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoLimit) {
|
||||
sawNoLimit = true
|
||||
} else if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
} else if !found {
|
||||
continue
|
||||
}
|
||||
|
||||
if !limitFound {
|
||||
limitFound = true
|
||||
firstLimit = limit
|
||||
} else if limit != firstLimit && conflictErr == nil {
|
||||
conflictErr = fmt.Errorf("conflicting memory limits from cgroup mount candidates: %d and %d", firstLimit, limit)
|
||||
}
|
||||
}
|
||||
if firstErr != nil {
|
||||
return 0, false, firstErr
|
||||
}
|
||||
if conflictErr != nil {
|
||||
return 0, false, conflictErr
|
||||
}
|
||||
|
||||
if limitFound {
|
||||
return firstLimit, true, nil
|
||||
}
|
||||
if sawNoLimit {
|
||||
return 0, false, ErrNoLimit
|
||||
}
|
||||
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
// cgroup v1 uses the kernel's maximum page counter value to represent no limit
|
||||
func isCgroupV1NoLimit(limit uint64) bool {
|
||||
pageSize := uint64(os.Getpagesize())
|
||||
if limit >= math.MaxInt64/pageSize*pageSize {
|
||||
return true
|
||||
}
|
||||
|
||||
// strconv.IntSize reflects the Go binary width, not the kernel bitness
|
||||
if strconv.IntSize == 32 {
|
||||
return limit == math.MaxInt32*pageSize
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// readMemoryLimitV1FromPath reads the effective memory limit from a cgroup v1 directory.
|
||||
// It returns [ErrNoLimit] for a no-limit sentinel.
|
||||
// The bool reports whether a limit value was found.
|
||||
func readMemoryLimitV1FromPath(cgroupPath string) (uint64, bool, error) {
|
||||
// use math.MaxUint64 as a neutral fallback so memory.limit_in_bytes determines the result
|
||||
hml, hmlFound, err := readHierarchicalMemoryLimit(filepath.Join(cgroupPath, "memory.stat"))
|
||||
// readMemoryLimitV1FromPath reads the memory limit for cgroup v1 from the given path.
|
||||
// this function expects the path to be the cgroup directory.
|
||||
func readMemoryLimitV1FromPath(cgroupPath string) (uint64, error) {
|
||||
// read hierarchical_memory_limit and memory.limit_in_bytes files.
|
||||
// but if hierarchical_memory_limit is not available, then use the max value as a fallback.
|
||||
hml, err := readHierarchicalMemoryLimit(filepath.Join(cgroupPath, "memory.stat"))
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return 0, false, fmt.Errorf("failed to read hierarchical_memory_limit: %w", err)
|
||||
} else if !hmlFound {
|
||||
return 0, fmt.Errorf("failed to read hierarchical_memory_limit: %w", err)
|
||||
} else if hml == 0 {
|
||||
hml = math.MaxUint64
|
||||
}
|
||||
|
||||
var libFound bool
|
||||
lib, err := readMemoryLimitInBytes(filepath.Join(cgroupPath, "memory.limit_in_bytes"))
|
||||
// read memory.limit_in_bytes file.
|
||||
b, err := os.ReadFile(filepath.Join(cgroupPath, "memory.limit_in_bytes"))
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return 0, false, err
|
||||
} else if errors.Is(err, os.ErrNotExist) {
|
||||
lib = math.MaxUint64
|
||||
} else {
|
||||
libFound = true
|
||||
}
|
||||
|
||||
if !hmlFound && !libFound {
|
||||
return 0, false, nil
|
||||
return 0, fmt.Errorf("failed to read memory.limit_in_bytes: %w", err)
|
||||
}
|
||||
lib, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse memory.limit_in_bytes value: %w", err)
|
||||
} else if lib == 0 {
|
||||
hml = math.MaxUint64
|
||||
}
|
||||
|
||||
// use the minimum value between hierarchical_memory_limit and memory.limit_in_bytes.
|
||||
// if the limit is the maximum value, then it is considered as no limit.
|
||||
limit := min(hml, lib)
|
||||
if isCgroupV1NoLimit(limit) {
|
||||
return 0, true, ErrNoLimit
|
||||
if limit >= getCgroupV1NoLimit() {
|
||||
return 0, ErrNoLimit
|
||||
}
|
||||
|
||||
return limit, true, nil
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
// readHierarchicalMemoryLimit returns false if memory.stat has no hierarchical_memory_limit field.
|
||||
func readHierarchicalMemoryLimit(path string) (uint64, bool, error) {
|
||||
// readHierarchicalMemoryLimit extracts hierarchical_memory_limit from memory.stat.
|
||||
// this function expects the path to be memory.stat file.
|
||||
func readHierarchicalMemoryLimit(path string) (uint64, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
return 0, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
@@ -403,42 +248,23 @@ func readHierarchicalMemoryLimit(path string) (uint64, bool, error) {
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 0 || fields[0] != "hierarchical_memory_limit" {
|
||||
continue
|
||||
}
|
||||
fields := strings.Split(line, " ")
|
||||
if len(fields) < 2 {
|
||||
return 0, false, fmt.Errorf("failed to parse memory.stat %q: not enough fields", line)
|
||||
} else if len(fields) > 2 {
|
||||
return 0, false, fmt.Errorf("failed to parse memory.stat %q: too many fields for hierarchical_memory_limit", line)
|
||||
return 0, fmt.Errorf("failed to parse memory.stat %q: not enough fields", line)
|
||||
}
|
||||
|
||||
limit, err := strconv.ParseUint(fields[1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, false, fmt.Errorf("failed to parse hierarchical_memory_limit value: %w", err)
|
||||
if fields[0] == "hierarchical_memory_limit" {
|
||||
if len(fields) > 2 {
|
||||
return 0, fmt.Errorf("failed to parse memory.stat %q: too many fields for hierarchical_memory_limit", line)
|
||||
}
|
||||
return strconv.ParseUint(fields[1], 10, 64)
|
||||
}
|
||||
|
||||
return limit, true, nil
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return 0, false, err
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
func readMemoryLimitInBytes(path string) (uint64, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to read memory.limit_in_bytes: %w", err)
|
||||
}
|
||||
|
||||
limit, err := strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse memory.limit_in_bytes value: %w", err)
|
||||
}
|
||||
|
||||
return limit, nil
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// https://www.man7.org/linux/man-pages/man5/proc_pid_mountinfo.5.html
|
||||
@@ -465,6 +291,7 @@ type mountInfo struct {
|
||||
SuperOptions string
|
||||
}
|
||||
|
||||
// parseMountInfoLine parses a line from the mountinfo file.
|
||||
func parseMountInfoLine(line string) (mountInfo, error) {
|
||||
if line == "" {
|
||||
return mountInfo{}, errors.New("empty line")
|
||||
@@ -488,50 +315,14 @@ func parseMountInfoLine(line string) (mountInfo, error) {
|
||||
}
|
||||
|
||||
return mountInfo{
|
||||
Root: unescapeMountInfoPath(fields1[3]),
|
||||
MountPoint: unescapeMountInfoPath(fields1[4]),
|
||||
Root: fields1[3],
|
||||
MountPoint: fields1[4],
|
||||
FilesystemType: fields2[0],
|
||||
SuperOptions: fields2[2],
|
||||
}, nil
|
||||
}
|
||||
|
||||
// unescapeMountInfoPath decodes path escapes written to /proc/<pid>/mountinfo.
|
||||
// https://github.com/torvalds/linux/blob/master/fs/proc_namespace.c
|
||||
func unescapeMountInfoPath(path string) string {
|
||||
if strings.IndexByte(path, '\\') == -1 {
|
||||
return path
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.Grow(len(path))
|
||||
for i := 0; i < len(path); i++ {
|
||||
if path[i] == '\\' && i+3 < len(path) {
|
||||
switch path[i : i+4] {
|
||||
case `\040`:
|
||||
b.WriteByte(' ')
|
||||
i += 3
|
||||
continue
|
||||
case `\011`:
|
||||
b.WriteByte('\t')
|
||||
i += 3
|
||||
continue
|
||||
case `\012`:
|
||||
b.WriteByte('\n')
|
||||
i += 3
|
||||
continue
|
||||
case `\134`:
|
||||
b.WriteByte('\\')
|
||||
i += 3
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
b.WriteByte(path[i])
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// parseMountInfo parses the mountinfo file.
|
||||
func parseMountInfo(r io.Reader) ([]mountInfo, error) {
|
||||
var (
|
||||
s = bufio.NewScanner(r)
|
||||
@@ -586,14 +377,17 @@ type cgroupHierarchy struct {
|
||||
CgroupPath string
|
||||
}
|
||||
|
||||
// parseCgroupHierarchyLine parses a line from the cgroup file.
|
||||
func parseCgroupHierarchyLine(line string) (cgroupHierarchy, error) {
|
||||
if line == "" {
|
||||
return cgroupHierarchy{}, errors.New("empty line")
|
||||
}
|
||||
|
||||
fields := strings.SplitN(line, ":", 3)
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) < 3 {
|
||||
return cgroupHierarchy{}, fmt.Errorf("not enough fields: %v", fields)
|
||||
} else if len(fields) > 3 {
|
||||
return cgroupHierarchy{}, fmt.Errorf("too many fields: %v", fields)
|
||||
}
|
||||
|
||||
return cgroupHierarchy{
|
||||
@@ -603,6 +397,7 @@ func parseCgroupHierarchyLine(line string) (cgroupHierarchy, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseCgroupFile parses the cgroup file.
|
||||
func parseCgroupFile(r io.Reader) ([]cgroupHierarchy, error) {
|
||||
var (
|
||||
s = bufio.NewScanner(r)
|
||||
@@ -625,26 +420,22 @@ func parseCgroupFile(r io.Reader) ([]cgroupHierarchy, error) {
|
||||
return chs, nil
|
||||
}
|
||||
|
||||
// resolveCgroupPath maps cgroupRelPath from root into mountPoint.
|
||||
// It returns an empty path when cgroupRelPath lies outside root.
|
||||
func resolveCgroupPath(mountPoint, root, cgroupRelPath string) (string, error) {
|
||||
if !strings.HasPrefix(root, "/") || !strings.HasPrefix(cgroupRelPath, "/") {
|
||||
return "", errors.New("cgroup root and path must be absolute")
|
||||
// resolveCgroupPath resolves the actual cgroup path from the mountpoint, root, and cgroupRelPath.
|
||||
func resolveCgroupPath(mountpoint, root, cgroupRelPath string) (string, error) {
|
||||
rel, err := filepath.Rel(root, cgroupRelPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if root == cgroupRelPath {
|
||||
return mountPoint, nil
|
||||
// if the relative path is ".", then the cgroupRelPath is the root itself.
|
||||
if rel == "." {
|
||||
return mountpoint, nil
|
||||
}
|
||||
|
||||
prefix := root
|
||||
if root != "/" {
|
||||
prefix += "/"
|
||||
// if the relative path starts with "..", then it is outside the root.
|
||||
if strings.HasPrefix(rel, "..") {
|
||||
return "", fmt.Errorf("invalid cgroup path: %s is not under root %s", cgroupRelPath, root)
|
||||
}
|
||||
|
||||
rel, ok := strings.CutPrefix(cgroupRelPath, prefix)
|
||||
if !ok || !filepath.IsLocal(rel) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return filepath.Join(mountPoint, rel), nil
|
||||
return filepath.Join(mountpoint, rel), nil
|
||||
}
|
||||
+26
-2
@@ -1,8 +1,32 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
package memlimit
|
||||
|
||||
// FromCgroup returns the memory limit for the current process's cgroup.
|
||||
// FromCgroup retrieves the memory limit from the cgroup.
|
||||
func FromCgroup() (uint64, error) {
|
||||
return fromCgroup(procSelfMountInfoPath, procSelfCgroupPath)
|
||||
return fromCgroup(detectCgroupVersion)
|
||||
}
|
||||
|
||||
// FromCgroupV1 retrieves the memory limit from the cgroup v1 controller.
|
||||
// After v1.0.0, this function could be removed and FromCgroup should be used instead.
|
||||
func FromCgroupV1() (uint64, error) {
|
||||
return fromCgroup(func(_ []mountInfo) (bool, bool) {
|
||||
return true, false
|
||||
})
|
||||
}
|
||||
|
||||
// FromCgroupHybrid retrieves the memory limit from the cgroup v2 and v1 controller sequentially,
|
||||
// basically, it is equivalent to FromCgroup.
|
||||
// After v1.0.0, this function could be removed and FromCgroup should be used instead.
|
||||
func FromCgroupHybrid() (uint64, error) {
|
||||
return FromCgroup()
|
||||
}
|
||||
|
||||
// FromCgroupV2 retrieves the memory limit from the cgroup v2 controller.
|
||||
// After v1.0.0, this function could be removed and FromCgroup should be used instead.
|
||||
func FromCgroupV2() (uint64, error) {
|
||||
return fromCgroup(func(_ []mountInfo) (bool, bool) {
|
||||
return false, true
|
||||
})
|
||||
}
|
||||
+13
-2
@@ -1,9 +1,20 @@
|
||||
//go:build !linux
|
||||
// +build !linux
|
||||
|
||||
package memlimit
|
||||
|
||||
// FromCgroup returns the memory limit for the current process's cgroup.
|
||||
// On non-Linux platforms, it always returns [ErrCgroupsNotSupported].
|
||||
func FromCgroup() (uint64, error) {
|
||||
return 0, ErrCgroupsNotSupported
|
||||
}
|
||||
|
||||
func FromCgroupV1() (uint64, error) {
|
||||
return 0, ErrCgroupsNotSupported
|
||||
}
|
||||
|
||||
func FromCgroupHybrid() (uint64, error) {
|
||||
return 0, ErrCgroupsNotSupported
|
||||
}
|
||||
|
||||
func FromCgroupV2() (uint64, error) {
|
||||
return 0, ErrCgroupsNotSupported
|
||||
}
|
||||
Generated
Vendored
+1
-1
@@ -4,7 +4,7 @@ import (
|
||||
"github.com/pbnjay/memory"
|
||||
)
|
||||
|
||||
// FromSystem returns the total system memory.
|
||||
// FromSystem returns the total memory of the system.
|
||||
func FromSystem() (uint64, error) {
|
||||
limit := memory.TotalMemory()
|
||||
if limit == 0 {
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package memlimit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
envAUTOMEMLIMIT_EXPERIMENT = "AUTOMEMLIMIT_EXPERIMENT"
|
||||
)
|
||||
|
||||
// Experiments is a set of experiment flags.
|
||||
// It is used to enable experimental features.
|
||||
//
|
||||
// You can set the flags by setting the environment variable AUTOMEMLIMIT_EXPERIMENT.
|
||||
// The value of the environment variable is a comma-separated list of experiment names.
|
||||
//
|
||||
// The following experiment names are known:
|
||||
//
|
||||
// - none: disable all experiments
|
||||
// - system: enable fallback to system memory limit
|
||||
type Experiments struct {
|
||||
// System enables fallback to system memory limit.
|
||||
System bool
|
||||
}
|
||||
|
||||
func parseExperiments() (Experiments, error) {
|
||||
var exp Experiments
|
||||
|
||||
// Create a map of known experiment names.
|
||||
names := make(map[string]func(bool))
|
||||
rv := reflect.ValueOf(&exp).Elem()
|
||||
rt := rv.Type()
|
||||
for i := 0; i < rt.NumField(); i++ {
|
||||
field := rv.Field(i)
|
||||
names[strings.ToLower(rt.Field(i).Name)] = field.SetBool
|
||||
}
|
||||
|
||||
// Parse names.
|
||||
for _, f := range strings.Split(os.Getenv(envAUTOMEMLIMIT_EXPERIMENT), ",") {
|
||||
if f == "" {
|
||||
continue
|
||||
}
|
||||
if f == "none" {
|
||||
exp = Experiments{}
|
||||
continue
|
||||
}
|
||||
val := true
|
||||
set, ok := names[f]
|
||||
if !ok {
|
||||
return Experiments{}, fmt.Errorf("unknown AUTOMEMLIMIT_EXPERIMENT %s", f)
|
||||
}
|
||||
set(val)
|
||||
}
|
||||
|
||||
return exp, nil
|
||||
}
|
||||
+5
-14
@@ -5,18 +5,9 @@ import (
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
var _ slog.Handler = discardHandler{}
|
||||
type noopLogger struct{}
|
||||
|
||||
type discardHandler struct{}
|
||||
|
||||
func (discardHandler) Enabled(context.Context, slog.Level) bool { return false }
|
||||
func (discardHandler) Handle(context.Context, slog.Record) error { return nil }
|
||||
func (dh discardHandler) WithAttrs([]slog.Attr) slog.Handler { return dh }
|
||||
func (dh discardHandler) WithGroup(string) slog.Handler { return dh }
|
||||
|
||||
func memlimitLogger(logger *slog.Logger) *slog.Logger {
|
||||
if logger == nil {
|
||||
return slog.New(discardHandler{})
|
||||
}
|
||||
return logger.With(slog.String("package", "github.com/KimMachineGun/automemlimit/memlimit"))
|
||||
}
|
||||
func (noopLogger) Enabled(context.Context, slog.Level) bool { return false }
|
||||
func (noopLogger) Handle(context.Context, slog.Record) error { return nil }
|
||||
func (d noopLogger) WithAttrs([]slog.Attr) slog.Handler { return d }
|
||||
func (d noopLogger) WithGroup(string) slog.Handler { return d }
|
||||
+161
-91
@@ -1,8 +1,6 @@
|
||||
// Package memlimit configures GOMEMLIMIT from a memory limit provider.
|
||||
package memlimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -16,28 +14,26 @@ import (
|
||||
const (
|
||||
envGOMEMLIMIT = "GOMEMLIMIT"
|
||||
envAUTOMEMLIMIT = "AUTOMEMLIMIT"
|
||||
// Deprecated: use memlimit.WithLogger instead
|
||||
envAUTOMEMLIMIT_DEBUG = "AUTOMEMLIMIT_DEBUG"
|
||||
|
||||
defaultAUTOMEMLIMIT = 0.9
|
||||
)
|
||||
|
||||
// ErrNoLimit indicates that a [Provider] reports no memory limit.
|
||||
// [Set] handles it as success by setting GOMEMLIMIT to [math.MaxInt64].
|
||||
// ErrNoLimit is returned when the memory limit is not set.
|
||||
var ErrNoLimit = errors.New("memory is not limited")
|
||||
|
||||
type config struct {
|
||||
logger *slog.Logger
|
||||
ratio float64
|
||||
minLimit int64
|
||||
provider Provider
|
||||
refresh time.Duration
|
||||
refreshCtx context.Context
|
||||
logger *slog.Logger
|
||||
ratio float64
|
||||
provider Provider
|
||||
refresh time.Duration
|
||||
}
|
||||
|
||||
// Option configures the behavior of [Set].
|
||||
// Option is a function that configures the behavior of SetGoMemLimitWithOptions.
|
||||
type Option func(cfg *config)
|
||||
|
||||
// WithRatio configures the fraction of the memory limit used for GOMEMLIMIT.
|
||||
// The ratio must be in (0.0, 1.0].
|
||||
// WithRatio configures the ratio of the memory limit to set as GOMEMLIMIT.
|
||||
//
|
||||
// Default: 0.9
|
||||
func WithRatio(ratio float64) Option {
|
||||
@@ -46,19 +42,9 @@ func WithRatio(ratio float64) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithMin configures the minimum GOMEMLIMIT after applying the ratio.
|
||||
// A non-positive value disables the minimum.
|
||||
// WithProvider configures the provider.
|
||||
//
|
||||
// Default: 0 (no minimum)
|
||||
func WithMin(minLimit int64) Option {
|
||||
return func(cfg *config) {
|
||||
cfg.minLimit = minLimit
|
||||
}
|
||||
}
|
||||
|
||||
// WithProvider configures the provider used by [Set].
|
||||
//
|
||||
// Default: [FromCgroup]
|
||||
// Default: FromCgroup
|
||||
func WithProvider(provider Provider) Option {
|
||||
return func(cfg *config) {
|
||||
cfg.provider = provider
|
||||
@@ -66,149 +52,233 @@ func WithProvider(provider Provider) Option {
|
||||
}
|
||||
|
||||
// WithLogger configures the logger.
|
||||
// It adds the "package" attribute to every log record.
|
||||
// It automatically attaches the "package" attribute to the logs.
|
||||
//
|
||||
// Default: logging disabled
|
||||
// Default: slog.New(noopLogger{})
|
||||
func WithLogger(logger *slog.Logger) Option {
|
||||
return func(cfg *config) {
|
||||
cfg.logger = memlimitLogger(logger)
|
||||
}
|
||||
}
|
||||
|
||||
// WithRefreshInterval configures [Set] to periodically refresh GOMEMLIMIT.
|
||||
//
|
||||
// Set starts a refresh goroutine after the initial provider call
|
||||
// when refresh is positive and ctx is non-nil.
|
||||
// The goroutine starts even if the initial call returns an error.
|
||||
// Canceling ctx stops the refresh loop but does not interrupt an active provider call.
|
||||
// Provider errors other than [ErrNoLimit] are reported to the configured logger
|
||||
// and do not stop later refreshes.
|
||||
// WithRefreshInterval configures the refresh interval for automemlimit.
|
||||
// If a refresh interval is greater than 0, automemlimit periodically fetches
|
||||
// the memory limit from the provider and reapplies it if it has changed.
|
||||
// If the provider returns an error, it logs the error and continues.
|
||||
// ErrNoLimit is treated as math.MaxInt64.
|
||||
//
|
||||
// Default: 0 (no refresh)
|
||||
func WithRefreshInterval(ctx context.Context, refresh time.Duration) Option {
|
||||
func WithRefreshInterval(refresh time.Duration) Option {
|
||||
return func(cfg *config) {
|
||||
cfg.refresh = refresh
|
||||
cfg.refreshCtx = ctx
|
||||
}
|
||||
}
|
||||
|
||||
// Set sets GOMEMLIMIT using the configured provider.
|
||||
// WithEnv configures whether to use environment variables.
|
||||
//
|
||||
// By default, Set uses 90% of the limit reported by [FromCgroup].
|
||||
// AUTOMEMLIMIT overrides the configured ratio with a value in (0.0, 1.0].
|
||||
// Setting it to "off" disables Set.
|
||||
// Default: false
|
||||
//
|
||||
// If the GOMEMLIMIT environment variable is present or AUTOMEMLIMIT is set to "off",
|
||||
// Set returns the current GOMEMLIMIT without calling the provider or starting a refresh goroutine.
|
||||
// Deprecated: currently this does nothing.
|
||||
func WithEnv() Option {
|
||||
return func(cfg *config) {}
|
||||
}
|
||||
|
||||
func memlimitLogger(logger *slog.Logger) *slog.Logger {
|
||||
if logger == nil {
|
||||
return slog.New(noopLogger{})
|
||||
}
|
||||
return logger.With(slog.String("package", "github.com/KimMachineGun/automemlimit/memlimit"))
|
||||
}
|
||||
|
||||
// SetGoMemLimitWithOpts sets GOMEMLIMIT with options and environment variables.
|
||||
//
|
||||
// Set returns the resulting GOMEMLIMIT on success.
|
||||
// On error, it returns the previous GOMEMLIMIT and the error.
|
||||
// It handles [ErrNoLimit] as success by setting GOMEMLIMIT to [math.MaxInt64].
|
||||
func Set(opts ...Option) (_limit int64, _err error) {
|
||||
// You can configure how much memory of the cgroup's memory limit to set as GOMEMLIMIT
|
||||
// through AUTOMEMLIMIT environment variable in the half-open range (0.0,1.0].
|
||||
//
|
||||
// If AUTOMEMLIMIT is not set, it defaults to 0.9. (10% is the headroom for memory sources the Go runtime is unaware of.)
|
||||
// If GOMEMLIMIT is already set or AUTOMEMLIMIT=off, this function does nothing.
|
||||
//
|
||||
// If AUTOMEMLIMIT_EXPERIMENT is set, it enables experimental features.
|
||||
// Please see the documentation of Experiments for more details.
|
||||
//
|
||||
// Options:
|
||||
// - WithRatio
|
||||
// - WithProvider
|
||||
// - WithLogger
|
||||
func SetGoMemLimitWithOpts(opts ...Option) (_ int64, _err error) {
|
||||
// init config
|
||||
cfg := &config{
|
||||
logger: slog.New(discardHandler{}),
|
||||
logger: slog.New(noopLogger{}),
|
||||
ratio: defaultAUTOMEMLIMIT,
|
||||
provider: FromCgroup,
|
||||
}
|
||||
// TODO: remove this
|
||||
if debug, ok := os.LookupEnv(envAUTOMEMLIMIT_DEBUG); ok {
|
||||
defaultLogger := memlimitLogger(slog.Default())
|
||||
defaultLogger.Warn("AUTOMEMLIMIT_DEBUG is deprecated, use memlimit.WithLogger instead")
|
||||
if debug == "true" {
|
||||
cfg.logger = defaultLogger
|
||||
}
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
// log error if any on return
|
||||
defer func() {
|
||||
if _err != nil {
|
||||
cfg.logger.Error("failed to set GOMEMLIMIT", slog.Any("error", _err))
|
||||
}
|
||||
}()
|
||||
|
||||
snapshot := debug.SetMemoryLimit(-1)
|
||||
|
||||
if val, ok := os.LookupEnv(envGOMEMLIMIT); ok {
|
||||
cfg.logger.Info("GOMEMLIMIT is already set, skipping", slog.String(envGOMEMLIMIT, val))
|
||||
return snapshot, nil
|
||||
// parse experiments
|
||||
exps, err := parseExperiments()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse experiments: %w", err)
|
||||
}
|
||||
if exps.System {
|
||||
cfg.logger.Info("system experiment is enabled: using system memory limit as a fallback")
|
||||
cfg.provider = ApplyFallback(cfg.provider, FromSystem)
|
||||
}
|
||||
|
||||
// rollback to previous memory limit on panic
|
||||
snapshot := debug.SetMemoryLimit(-1)
|
||||
defer rollbackOnPanic(cfg.logger, snapshot, &_err)
|
||||
|
||||
// check if GOMEMLIMIT is already set
|
||||
if val, ok := os.LookupEnv(envGOMEMLIMIT); ok {
|
||||
cfg.logger.Info("GOMEMLIMIT is already set, skipping", slog.String(envGOMEMLIMIT, val))
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// parse AUTOMEMLIMIT
|
||||
ratio := cfg.ratio
|
||||
if val, ok := os.LookupEnv(envAUTOMEMLIMIT); ok {
|
||||
if val == "off" {
|
||||
cfg.logger.Info("AUTOMEMLIMIT is off, skipping")
|
||||
return snapshot, nil
|
||||
cfg.logger.Info("AUTOMEMLIMIT is set to off, skipping")
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
r, err := strconv.ParseFloat(val, 64)
|
||||
ratio, err = strconv.ParseFloat(val, 64)
|
||||
if err != nil {
|
||||
return snapshot, fmt.Errorf("cannot parse AUTOMEMLIMIT: %s", val)
|
||||
return 0, fmt.Errorf("cannot parse AUTOMEMLIMIT: %s", val)
|
||||
}
|
||||
ratio = r
|
||||
}
|
||||
if math.IsNaN(ratio) || ratio <= 0 || ratio > 1 {
|
||||
return snapshot, fmt.Errorf(
|
||||
"failed to set GOMEMLIMIT: invalid ratio: %f, ratio should be in the range (0.0,1.0]",
|
||||
ratio,
|
||||
)
|
||||
}
|
||||
|
||||
provider := boundedProvider(ApplyRatio(cfg.provider, ratio), cfg.minLimit)
|
||||
limit, err := updateGoMemLimit(provider, cfg.logger)
|
||||
if cfg.refresh > 0 && cfg.refreshCtx != nil {
|
||||
go refresh(cfg.refreshCtx, provider, cfg.logger, cfg.refresh)
|
||||
}
|
||||
// apply ratio to the provider
|
||||
provider := capProvider(ApplyRatio(cfg.provider, ratio))
|
||||
|
||||
// set the memory limit and start refresh
|
||||
limit, err := updateGoMemLimit(uint64(snapshot), provider, cfg.logger)
|
||||
refresh(provider, cfg.logger, cfg.refresh)
|
||||
if err != nil {
|
||||
return snapshot, fmt.Errorf("failed to set GOMEMLIMIT: %w", err)
|
||||
if errors.Is(err, ErrNoLimit) {
|
||||
cfg.logger.Info("memory is not limited, skipping")
|
||||
// TODO: consider returning the snapshot
|
||||
return 0, nil
|
||||
}
|
||||
return 0, fmt.Errorf("failed to set GOMEMLIMIT: %w", err)
|
||||
}
|
||||
|
||||
return int64(limit), nil
|
||||
}
|
||||
|
||||
func updateGoMemLimit(provider Provider, logger *slog.Logger) (uint64, error) {
|
||||
// updateGoMemLimit updates the Go's memory limit, if it has changed.
|
||||
func updateGoMemLimit(currLimit uint64, provider Provider, logger *slog.Logger) (uint64, error) {
|
||||
newLimit, err := provider()
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNoLimit) {
|
||||
return updateGoMemLimit(Limit(math.MaxInt64), logger)
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
|
||||
previous := debug.SetMemoryLimit(int64(newLimit))
|
||||
if newLimit == uint64(previous) {
|
||||
logger.Debug("GOMEMLIMIT is unchanged", slog.Uint64(envGOMEMLIMIT, newLimit))
|
||||
if newLimit == currLimit {
|
||||
logger.Debug("GOMEMLIMIT is not changed, skipping", slog.Uint64(envGOMEMLIMIT, newLimit))
|
||||
return newLimit, nil
|
||||
}
|
||||
|
||||
logger.Info("GOMEMLIMIT is updated", slog.Uint64(envGOMEMLIMIT, newLimit), slog.Uint64("previous", uint64(previous)))
|
||||
debug.SetMemoryLimit(int64(newLimit))
|
||||
logger.Info("GOMEMLIMIT is updated", slog.Uint64(envGOMEMLIMIT, newLimit), slog.Uint64("previous", currLimit))
|
||||
|
||||
return newLimit, nil
|
||||
}
|
||||
|
||||
func refresh(ctx context.Context, provider Provider, logger *slog.Logger, refresh time.Duration) {
|
||||
// refresh spawns a goroutine that runs every refresh duration and updates the GOMEMLIMIT if it has changed.
|
||||
// See more details in the documentation of WithRefreshInterval.
|
||||
func refresh(provider Provider, logger *slog.Logger, refresh time.Duration) {
|
||||
if refresh == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(refresh)
|
||||
defer ticker.Stop()
|
||||
provider = noErrNoLimitProvider(provider)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
_, err := updateGoMemLimit(provider, logger)
|
||||
t := time.NewTicker(refresh)
|
||||
go func() {
|
||||
for range t.C {
|
||||
err := func() (_err error) {
|
||||
snapshot := debug.SetMemoryLimit(-1)
|
||||
defer rollbackOnPanic(logger, snapshot, &_err)
|
||||
|
||||
_, err := updateGoMemLimit(uint64(snapshot), provider, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
if err != nil {
|
||||
logger.Error("failed to refresh GOMEMLIMIT", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// rollbackOnPanic rollbacks to the snapshot on panic.
|
||||
// Since it uses recover, it should be called in a deferred function.
|
||||
func rollbackOnPanic(logger *slog.Logger, snapshot int64, err *error) {
|
||||
panicErr := recover()
|
||||
if panicErr != nil {
|
||||
if *err != nil {
|
||||
logger.Error("failed to set GOMEMLIMIT", slog.Any("error", *err))
|
||||
}
|
||||
*err = fmt.Errorf("panic during setting the Go's memory limit, rolling back to previous limit %d: %v",
|
||||
snapshot, panicErr,
|
||||
)
|
||||
debug.SetMemoryLimit(snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func boundedProvider(provider Provider, minLimit int64) Provider {
|
||||
// SetGoMemLimitWithEnv sets GOMEMLIMIT with the value from the environment variables.
|
||||
// Since WithEnv is deprecated, this function is equivalent to SetGoMemLimitWithOpts().
|
||||
// Deprecated: use SetGoMemLimitWithOpts instead.
|
||||
func SetGoMemLimitWithEnv() {
|
||||
_, _ = SetGoMemLimitWithOpts()
|
||||
}
|
||||
|
||||
// SetGoMemLimit sets GOMEMLIMIT with the value from the cgroup's memory limit and given ratio.
|
||||
func SetGoMemLimit(ratio float64) (int64, error) {
|
||||
return SetGoMemLimitWithOpts(WithRatio(ratio))
|
||||
}
|
||||
|
||||
// SetGoMemLimitWithProvider sets GOMEMLIMIT with the value from the given provider and ratio.
|
||||
func SetGoMemLimitWithProvider(provider Provider, ratio float64) (int64, error) {
|
||||
return SetGoMemLimitWithOpts(WithProvider(provider), WithRatio(ratio))
|
||||
}
|
||||
|
||||
func noErrNoLimitProvider(provider Provider) Provider {
|
||||
return func() (uint64, error) {
|
||||
limit, err := provider()
|
||||
if errors.Is(err, ErrNoLimit) {
|
||||
return math.MaxInt64, nil
|
||||
}
|
||||
return limit, err
|
||||
}
|
||||
}
|
||||
|
||||
func capProvider(provider Provider) Provider {
|
||||
return func() (uint64, error) {
|
||||
limit, err := provider()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
} else if limit > math.MaxInt64 {
|
||||
return math.MaxInt64, nil
|
||||
} else if minLimit > 0 && limit < uint64(minLimit) {
|
||||
return uint64(minLimit), nil
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
+6
-10
@@ -2,28 +2,25 @@ package memlimit
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// Provider returns a memory limit in bytes.
|
||||
// It should return [ErrNoLimit] when the source reports no limit.
|
||||
// Provider is a function that returns the memory limit.
|
||||
type Provider func() (uint64, error)
|
||||
|
||||
// Limit returns a [Provider] that always returns limit.
|
||||
func Limit(limit uint64) Provider {
|
||||
// Limit is a helper Provider function that returns the given limit.
|
||||
func Limit(limit uint64) func() (uint64, error) {
|
||||
return func() (uint64, error) {
|
||||
return limit, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyRatio wraps provider and applies ratio to its result.
|
||||
// The ratio must be in (0.0, 1.0].
|
||||
// ApplyRationA is a helper Provider function that applies the given ratio to the given provider.
|
||||
func ApplyRatio(provider Provider, ratio float64) Provider {
|
||||
if ratio == 1 {
|
||||
return provider
|
||||
}
|
||||
return func() (uint64, error) {
|
||||
if math.IsNaN(ratio) || ratio <= 0 || ratio > 1 {
|
||||
if ratio <= 0 || ratio > 1 {
|
||||
return 0, fmt.Errorf("invalid ratio: %f, ratio should be in the range (0.0,1.0]", ratio)
|
||||
}
|
||||
limit, err := provider()
|
||||
@@ -34,8 +31,7 @@ func ApplyRatio(provider Provider, ratio float64) Provider {
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyFallback returns a [Provider] that calls fallback when provider returns an error,
|
||||
// including [ErrNoLimit].
|
||||
// ApplyFallback is a helper Provider function that sets the fallback provider.
|
||||
func ApplyFallback(provider Provider, fallback Provider) Provider {
|
||||
return func() (uint64, error) {
|
||||
limit, err := provider()
|
||||
|
||||
+1
-5
@@ -50,8 +50,7 @@ func Key(key string) func(r *http.Request) (string, error) {
|
||||
|
||||
// CanonicalizeIP normalizes a client IP string for use as a rate-limit key:
|
||||
//
|
||||
// - IPv4 addresses are returned unchanged. IPv4 mapped IPv6 addresses use
|
||||
// their dotted IPv4 form.
|
||||
// - IPv4 addresses are returned unchanged.
|
||||
// - IPv6 addresses are reduced to their /64 prefix. An IPv6 client typically
|
||||
// controls a whole /64 (2^64 addresses via SLAAC), so keying on the full
|
||||
// address would let it rotate within its own /64 to win a fresh bucket per
|
||||
@@ -95,9 +94,6 @@ func CanonicalizeIP(ip string) string {
|
||||
if ipv6 == nil {
|
||||
return ip
|
||||
}
|
||||
if ipv4 := ipv6.To4(); ipv4 != nil {
|
||||
return ipv4.String()
|
||||
}
|
||||
|
||||
return ipv6.Mask(net.CIDRMask(64, 128)).String()
|
||||
}
|
||||
|
||||
+6
-6
@@ -83,16 +83,16 @@ func (l *Conn) Add(addRequest *AddRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationAddResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
if packet.Children[1].Tag == ApplicationAddResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+68
-125
@@ -6,15 +6,15 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
enchex "encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"unicode/utf16"
|
||||
|
||||
"github.com/Azure/go-ntlmssp"
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
//lint:ignore SA1019 NTLM requires MD4; there is no secure replacement for the protocol.
|
||||
"golang.org/x/crypto/md4" //nolint:staticcheck
|
||||
)
|
||||
|
||||
@@ -77,26 +77,15 @@ func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResu
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return decodeSimpleBindResult(packet)
|
||||
}
|
||||
|
||||
// decodeSimpleBindResult decodes a bind response envelope, including any
|
||||
// response controls. It is separated from the network loop so the full
|
||||
// response decoder can be fuzzed directly.
|
||||
func decodeSimpleBindResult(packet *ber.Packet) (*SimpleBindResult, error) {
|
||||
result := &SimpleBindResult{
|
||||
Controls: make([]Control, 0),
|
||||
}
|
||||
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controls.Children {
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, decodeErr := DecodeControl(child)
|
||||
if decodeErr != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
|
||||
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
@@ -207,35 +196,26 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
|
||||
Controls: make([]Control, 0),
|
||||
}
|
||||
var params map[string]string
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
challenge, perr := packetChild(packet, 1)
|
||||
if perr == nil {
|
||||
challengeChild, hasChallengeChild, cerr := packetChildIfPresent(challenge, 3)
|
||||
if cerr != nil {
|
||||
if len(packet.Children) == 2 {
|
||||
if len(packet.Children[1].Children) == 4 {
|
||||
child := packet.Children[1].Children[0]
|
||||
if child.Tag != ber.TagEnumerated {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if hasChallengeChild {
|
||||
child, perr := packetChild(challenge, 0)
|
||||
if perr != nil || child.Tag != ber.TagEnumerated {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
code, perr := packetInt64(child)
|
||||
if perr != nil || code != 14 {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
child = challengeChild
|
||||
if child.Tag != ber.TagObjectDescriptor || child.Data == nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
data, _ := io.ReadAll(child.Data)
|
||||
params, err = parseParams(string(data))
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("parsing digest-challenge: %s", err)
|
||||
}
|
||||
if child.Value.(int64) != 14 {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
child = packet.Children[1].Children[3]
|
||||
if child.Tag != ber.TagObjectDescriptor {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if child.Data == nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
data, _ := ioutil.ReadAll(child.Data)
|
||||
params, err = parseParams(string(data))
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("parsing digest-challenge: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -277,45 +257,30 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
}
|
||||
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
response, rerr := packetChild(packet, 1)
|
||||
if rerr != nil {
|
||||
if len(packet.Children) == 2 {
|
||||
response := packet.Children[1]
|
||||
if response == nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed {
|
||||
if _, rerr := packetChildCount(response, 3, -1, "bind response"); rerr == nil {
|
||||
resultCodeChild, rerr := packetChild(response, 0)
|
||||
if rerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagInteger) || ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode, rerr := packetResultCode(resultCodeChild)
|
||||
if rerr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 {
|
||||
if ber.Type(response.Children[0].Tag) == ber.Type(ber.TagInteger) || ber.Type(response.Children[0].Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode := uint16(response.Children[0].Value.(int64))
|
||||
if resultCode == 14 {
|
||||
msgCtx, err := l.doRequest(digestMD5BindRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resultCode == 14 {
|
||||
msgCtx, err := l.doRequest(digestMD5BindRequest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer l.finishMessage(msgCtx)
|
||||
packetResponse, ok := <-msgCtx.responses
|
||||
if !ok {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
|
||||
}
|
||||
packet, err = packetResponse.ReadPacket()
|
||||
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
}
|
||||
defer l.finishMessage(msgCtx)
|
||||
packetResponse, ok := <-msgCtx.responses
|
||||
if !ok {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
|
||||
}
|
||||
packet, err = packetResponse.ReadPacket()
|
||||
l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read packet: %s", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -408,7 +373,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cnonce := hex.EncodeToString(rb)
|
||||
cnonce := enchex.EncodeToString(rb)
|
||||
x := username + ":" + params["realm"] + ":" + password
|
||||
y := md5Hash([]byte(x))
|
||||
|
||||
@@ -419,8 +384,8 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
}
|
||||
a2 := bytes.NewBuffer([]byte("AUTHENTICATE"))
|
||||
a2.WriteString(":" + uri)
|
||||
ha1 := hex.EncodeToString(md5Hash(a1.Bytes()))
|
||||
ha2 := hex.EncodeToString(md5Hash(a2.Bytes()))
|
||||
ha1 := enchex.EncodeToString(md5Hash(a1.Bytes()))
|
||||
ha2 := enchex.EncodeToString(md5Hash(a2.Bytes()))
|
||||
|
||||
kd := ha1
|
||||
kd += ":" + params["nonce"]
|
||||
@@ -428,7 +393,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
|
||||
kd += ":" + cnonce
|
||||
kd += ":" + qop
|
||||
kd += ":" + ha2
|
||||
resp := hex.EncodeToString(md5Hash([]byte(kd)))
|
||||
resp := enchex.EncodeToString(md5Hash([]byte(kd)))
|
||||
return fmt.Sprintf(
|
||||
`username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`,
|
||||
quotedStringEscape(username),
|
||||
@@ -537,8 +502,8 @@ func (req *NTLMBindRequest) appendTo(envelope *ber.Packet) (err error) {
|
||||
var negMessage []byte
|
||||
|
||||
// generate an NTLMSSP Negotiation message for the specified domain (it can be blank)
|
||||
switch req.Negotiator {
|
||||
case nil:
|
||||
switch {
|
||||
case req.Negotiator == nil:
|
||||
negMessage, err = ntlmssp.NewNegotiateMessage(req.Domain, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create NTLM negotiate message: %s", err)
|
||||
@@ -631,29 +596,15 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
|
||||
var ntlmsspChallenge []byte
|
||||
|
||||
// now find the NTLM Response Message
|
||||
_, hasControls, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasControls {
|
||||
protocolOp, perr := packetChild(packet, 1)
|
||||
if perr == nil {
|
||||
protocolOpChildren, cerr := packetChildCount(protocolOp, 3, -1, "bind response")
|
||||
if cerr != nil {
|
||||
if len(packet.Children) == 2 {
|
||||
if len(packet.Children[1].Children) == 3 {
|
||||
child := packet.Children[1].Children[1]
|
||||
ntlmsspChallenge = child.ByteValue
|
||||
// Check to make sure we got the right message. It will always start with NTLMSSP
|
||||
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
if len(protocolOpChildren) == 3 {
|
||||
child, perr := packetChild(protocolOp, 1)
|
||||
if perr != nil {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
ntlmsspChallenge = child.ByteValue
|
||||
// Check to make sure we got the right message. It will always start with NTLMSSP
|
||||
if len(ntlmsspChallenge) < 7 || !bytes.Equal(ntlmsspChallenge[:7], []byte("NTLMSSP")) {
|
||||
return result, GetLDAPError(packet)
|
||||
}
|
||||
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
|
||||
}
|
||||
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
|
||||
}
|
||||
}
|
||||
if ntlmsspChallenge != nil {
|
||||
@@ -664,12 +615,11 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
|
||||
case ntlmBindRequest.Hash == "" && ntlmBindRequest.Password == "" && !ntlmBindRequest.AllowEmptyPassword:
|
||||
err = fmt.Errorf("need a password or hash to generate reply")
|
||||
case ntlmBindRequest.Negotiator == nil && ntlmBindRequest.Hash != "":
|
||||
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash, &ntlmssp.AuthenticateMessageOptions{
|
||||
PasswordHashed: true,
|
||||
})
|
||||
responseMessage, err = ntlmssp.ProcessChallengeWithHash(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash)
|
||||
case ntlmBindRequest.Negotiator == nil && (ntlmBindRequest.Password != "" || ntlmBindRequest.AllowEmptyPassword):
|
||||
// generate a response message to the challenge with the given Username/Password if password is provided
|
||||
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, nil)
|
||||
_, _, domainNeeded := ntlmssp.GetDomain(ntlmBindRequest.Username)
|
||||
responseMessage, err = ntlmssp.ProcessChallenge(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, domainNeeded)
|
||||
default:
|
||||
hash := ntlmBindRequest.Hash
|
||||
if len(hash) == 0 {
|
||||
@@ -789,7 +739,7 @@ func (l *Conn) GSSAPIBindRequest(client GSSAPIClient, req *GSSAPIBindRequest) er
|
||||
return l.GSSAPIBindRequestWithAPOptions(client, req, []int{})
|
||||
}
|
||||
|
||||
// GSSAPIBindRequestWithAPOptions performs the GSSAPI SASL bind using the provided GSSAPI client and AP options.
|
||||
// GSSAPIBindRequest performs the GSSAPI SASL bind using the provided GSSAPI client.
|
||||
func (l *Conn) GSSAPIBindRequestWithAPOptions(client GSSAPIClient, req *GSSAPIBindRequest, APOptions []int) error {
|
||||
//nolint:errcheck
|
||||
defer client.DeleteSecContext()
|
||||
@@ -869,40 +819,33 @@ func (l *Conn) saslBindTokenExchange(reqControls []Control, reqToken []byte) ([]
|
||||
// packet is an envelope
|
||||
// child 0 is message id
|
||||
// child 1 is protocolOp
|
||||
if _, err := packetChildCount(packet, 2, 2, "bind response"); err != nil {
|
||||
if len(packet.Children) != 2 {
|
||||
return nil, fmt.Errorf("bad bind response")
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad bind response")
|
||||
}
|
||||
protocolOp := packet.Children[1]
|
||||
RESP:
|
||||
switch protocolOp.Description {
|
||||
case "Bind Response": // Bind Response
|
||||
// Bind Reponse is an LDAP Response (https://www.rfc-editor.org/rfc/rfc4511#section-4.1.9)
|
||||
// with an additional optional serverSaslCreds string (https://www.rfc-editor.org/rfc/rfc4511#section-4.2.2)
|
||||
// child 0 is resultCode
|
||||
resultCode, rcErr := packetChild(protocolOp, 0)
|
||||
if rcErr != nil || resultCode.Tag != ber.TagEnumerated {
|
||||
resultCode := protocolOp.Children[0]
|
||||
if resultCode.Tag != ber.TagEnumerated {
|
||||
break RESP
|
||||
}
|
||||
code, rcErr := packetInt64(resultCode)
|
||||
if rcErr != nil {
|
||||
break RESP
|
||||
}
|
||||
switch code {
|
||||
switch resultCode.Value.(int64) {
|
||||
case 14: // Sasl bind in progress
|
||||
referral, ok, refErr := packetChildIfPresent(protocolOp, 3)
|
||||
if refErr != nil || !ok {
|
||||
if len(protocolOp.Children) < 3 {
|
||||
break RESP
|
||||
}
|
||||
referral := protocolOp.Children[3]
|
||||
switch referral.Description {
|
||||
case "Referral":
|
||||
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor || referral.Data == nil {
|
||||
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor {
|
||||
break RESP
|
||||
}
|
||||
return io.ReadAll(referral.Data)
|
||||
return ioutil.ReadAll(referral.Data)
|
||||
}
|
||||
// Optional:
|
||||
//if len(protocolOp.Children) == 4 {
|
||||
|
||||
+4
-5
@@ -46,11 +46,10 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return false, err
|
||||
if len(packet.Children) < 2 {
|
||||
return false, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationCompareResponse {
|
||||
if packet.Children[1].Tag == ApplicationCompareResponse {
|
||||
err := GetLDAPError(packet)
|
||||
|
||||
switch {
|
||||
@@ -62,5 +61,5 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return false, fmt.Errorf("unexpected Response: %d", protocolOp.Tag)
|
||||
return false, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag)
|
||||
}
|
||||
+5
-12
@@ -204,7 +204,7 @@ func (dc *DialContext) dial(u *url.URL) (net.Conn, error) {
|
||||
return tls.DialWithDialer(dc.dialer, "tcp", net.JoinHostPort(host, port), dc.tlsConfig)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unknown scheme '%s'", u.Scheme)
|
||||
return nil, fmt.Errorf("Unknown scheme '%s'", u.Scheme)
|
||||
}
|
||||
|
||||
// Dial connects to the given address on the given network using net.Dial
|
||||
@@ -463,13 +463,6 @@ func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags)
|
||||
if l.IsClosing() {
|
||||
return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed"))
|
||||
}
|
||||
messageID, err := packetInt64At(packet, 0)
|
||||
if err != nil {
|
||||
// The packet is built by this package, so a malformed one is our bug,
|
||||
// not a network failure: return the malformed-packet error as-is
|
||||
// instead of nesting it inside ErrorNetwork.
|
||||
return nil, err
|
||||
}
|
||||
l.messageMutex.Lock()
|
||||
l.Debug.Printf("flags&startTLS = %d", flags&startTLS)
|
||||
if l.isStartingTLS {
|
||||
@@ -488,6 +481,7 @@ func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags)
|
||||
l.messageMutex.Unlock()
|
||||
|
||||
responses := make(chan *PacketResponse)
|
||||
messageID := packet.Children[0].Value.(int64)
|
||||
message := &messagePacket{
|
||||
Op: MessageRequest,
|
||||
MessageID: messageID,
|
||||
@@ -665,9 +659,8 @@ func (l *Conn) reader() {
|
||||
if err := addLDAPDescriptions(packet); err != nil {
|
||||
l.Debug.Printf("descriptions error: %s", err)
|
||||
}
|
||||
messageID, err := packetInt64At(packet, 0)
|
||||
if err != nil {
|
||||
l.Debug.Printf("Received bad ldap packet: %s", err)
|
||||
if len(packet.Children) == 0 {
|
||||
l.Debug.Printf("Received bad ldap packet")
|
||||
continue
|
||||
}
|
||||
l.messageMutex.Lock()
|
||||
@@ -677,7 +670,7 @@ func (l *Conn) reader() {
|
||||
l.messageMutex.Unlock()
|
||||
message := &messagePacket{
|
||||
Op: MessageResponse,
|
||||
MessageID: messageID,
|
||||
MessageID: packet.Children[0].Value.(int64),
|
||||
Packet: packet,
|
||||
}
|
||||
if !l.sendProcessMessage(message) {
|
||||
|
||||
+175
-298
@@ -557,68 +557,65 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
value *ber.Packet
|
||||
)
|
||||
|
||||
children, err := packetChildCount(packet, 1, 3, "control")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(packet.Children) {
|
||||
case 0:
|
||||
// at least one child is required for control type
|
||||
return nil, fmt.Errorf("at least one child is required for control type")
|
||||
|
||||
typeChild, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
typeChild.Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
if typeChild.Value != nil {
|
||||
ct, err := packetString(typeChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("control type is not a string: %T: %w", typeChild.Value, err)
|
||||
case 1:
|
||||
// just type, no criticality or value
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
} else if typeChild.Data != nil {
|
||||
ControlType = typeChild.Data.String()
|
||||
} else {
|
||||
return nil, malformedf("not found where to get the control type")
|
||||
}
|
||||
|
||||
switch len(children) {
|
||||
case 3:
|
||||
// criticality and value present
|
||||
criticality, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
case 2:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
if packet.Children[0].Value != nil {
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
} else if packet.Children[0].Data != nil {
|
||||
ControlType = packet.Children[0].Data.String()
|
||||
} else {
|
||||
return nil, fmt.Errorf("not found where to get the control type")
|
||||
}
|
||||
criticality.Description = "Criticality"
|
||||
crit, err := packetBool(criticality)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T: %w", criticality.Value, err)
|
||||
|
||||
// Children[1] could be criticality or value (both are optional)
|
||||
// duck-type on whether this is a boolean
|
||||
if crit, ok := packet.Children[1].Value.(bool); ok {
|
||||
packet.Children[1].Description = "Criticality"
|
||||
Criticality = crit
|
||||
} else {
|
||||
packet.Children[1].Description = "Control Value"
|
||||
value = packet.Children[1]
|
||||
}
|
||||
|
||||
case 3:
|
||||
packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
|
||||
ct, ok := packet.Children[0].Value.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("control type is not a string: %T", packet.Children[0].Value)
|
||||
}
|
||||
ControlType = ct
|
||||
|
||||
packet.Children[1].Description = "Criticality"
|
||||
crit, ok := packet.Children[1].Value.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T", packet.Children[1].Value)
|
||||
}
|
||||
Criticality = crit
|
||||
|
||||
valueChild, err := packetChild(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valueChild.Description = "Control Value"
|
||||
value = valueChild
|
||||
case 2:
|
||||
// Children[1] is criticality or value. RFC 4511 declares
|
||||
// Control ::= SEQUENCE { controlType LDAPOID, criticality BOOLEAN
|
||||
// DEFAULT FALSE, controlValue OCTET STRING OPTIONAL }, so identify
|
||||
// it by its ASN.1 tag rather than by the Go type of Value.
|
||||
second, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if second.ClassType == ber.ClassUniversal && second.Tag == ber.TagBoolean {
|
||||
second.Description = "Criticality"
|
||||
crit, err := packetBool(second)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("criticality is not a bool: %T: %w", second.Value, err)
|
||||
}
|
||||
Criticality = crit
|
||||
} else {
|
||||
second.Description = "Control Value"
|
||||
value = second
|
||||
}
|
||||
packet.Children[2].Description = "Control Value"
|
||||
value = packet.Children[2]
|
||||
|
||||
default:
|
||||
// more than 3 children is invalid
|
||||
return nil, fmt.Errorf("more than 3 children is invalid for controls")
|
||||
}
|
||||
|
||||
switch ControlType {
|
||||
@@ -626,113 +623,74 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
return NewControlManageDsaIT(Criticality), nil
|
||||
case ControlTypePaging:
|
||||
if value == nil {
|
||||
return nil, malformedf("paging control value is missing")
|
||||
return nil, fmt.Errorf("paging control value is missing")
|
||||
}
|
||||
value.Description += " (Paging)"
|
||||
c := new(ControlPaging)
|
||||
if value.Value != nil {
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
first, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(value.Children) == 0 {
|
||||
return nil, fmt.Errorf("paging control value is empty")
|
||||
}
|
||||
value = first
|
||||
value = value.Children[0]
|
||||
value.Description = "Search Control Value"
|
||||
sizeChild, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(value.Children) < 2 {
|
||||
return nil, fmt.Errorf("paging control value has %d children, expected 2", len(value.Children))
|
||||
}
|
||||
cookieChild, err := packetChild(value, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sizeChild.Description = "Paging Size"
|
||||
cookieChild.Description = "Cookie"
|
||||
pagingSize, err := packetInt64(sizeChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("paging size is not an integer: %T: %w", sizeChild.Value, err)
|
||||
value.Children[0].Description = "Paging Size"
|
||||
value.Children[1].Description = "Cookie"
|
||||
pagingSize, ok := value.Children[0].Value.(int64)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("paging size is not an integer: %T", value.Children[0].Value)
|
||||
}
|
||||
c.PagingSize = uint32(pagingSize)
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Cookie = cookie
|
||||
cookieChild.Value = c.Cookie
|
||||
c.Cookie = value.Children[1].Data.Bytes()
|
||||
value.Children[1].Value = c.Cookie
|
||||
return c, nil
|
||||
case ControlTypeBeheraPasswordPolicy:
|
||||
if value == nil {
|
||||
return nil, fmt.Errorf("invalid value for Control Type ControlTypeBeheraPasswordPolicy: %v", value)
|
||||
}
|
||||
value.Description += " (Password Policy - Behera)"
|
||||
c := NewControlBeheraPasswordPolicy()
|
||||
if value.Value != nil {
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
|
||||
sequence, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sequence := value.Children[0]
|
||||
|
||||
for _, child := range sequence.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch child.Tag {
|
||||
case 0:
|
||||
if child.Tag == 0 {
|
||||
// Warning
|
||||
warningPacket, err := packetChild(child, 0)
|
||||
warningPacket := child.Children[0]
|
||||
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
data, err := packetData(warningPacket)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
val, err := ber.ParseInt64(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
switch warningPacket.Tag {
|
||||
case 0:
|
||||
if warningPacket.Tag == 0 {
|
||||
// timeBeforeExpiration
|
||||
c.Expire = val
|
||||
warningPacket.Value = c.Expire
|
||||
case 1:
|
||||
} else if warningPacket.Tag == 1 {
|
||||
// graceAuthNsRemaining
|
||||
c.Grace = val
|
||||
warningPacket.Value = c.Grace
|
||||
}
|
||||
case 1:
|
||||
} else if child.Tag == 1 {
|
||||
// Error
|
||||
bs, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bs := child.Data.Bytes()
|
||||
if len(bs) != 1 || bs[0] > 8 {
|
||||
return nil, malformedf("invalid PasswordPolicyResponse enum value")
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
|
||||
}
|
||||
val := int8(bs[0])
|
||||
c.Error = val
|
||||
@@ -753,7 +711,7 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
|
||||
expire, err := strconv.ParseInt(expireStr, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse value as int: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse value as int: %s", err)
|
||||
}
|
||||
c.Expire = expire
|
||||
value.Value = c.Expire
|
||||
@@ -768,58 +726,31 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
case ControlTypeSubtreeDelete:
|
||||
return NewControlSubtreeDelete(), nil
|
||||
case ControlTypeServerSideSorting:
|
||||
if value == nil {
|
||||
return nil, malformedf("server side sorting control value is missing")
|
||||
}
|
||||
return NewControlServerSideSorting(value)
|
||||
case ControlTypeServerSideSortingResult:
|
||||
return NewControlServerSideSortingResult(value)
|
||||
case ControlTypeDirSync:
|
||||
if value == nil {
|
||||
return nil, malformedf("dirSync control value is missing")
|
||||
}
|
||||
value.Description += " (DirSync)"
|
||||
return NewResponseControlDirSync(value)
|
||||
case ControlTypeSyncState:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync state control value is missing")
|
||||
}
|
||||
value.Description += " (Sync State)"
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
return NewControlSyncState(valueChildren)
|
||||
case ControlTypeSyncDone:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync done control value is missing")
|
||||
}
|
||||
value.Description += " (Sync Done)"
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
return NewControlSyncDone(valueChildren)
|
||||
case ControlTypeSyncInfo:
|
||||
if value == nil {
|
||||
return nil, malformedf("sync info control value is missing")
|
||||
}
|
||||
value.Description += " (Sync Info)"
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
return NewControlSyncInfo(valueChildren)
|
||||
default:
|
||||
@@ -832,10 +763,10 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
|
||||
// the calling goroutine, see #561. Fall back to the raw bytes
|
||||
// when the value isn't a string so we surface an error
|
||||
// instead of crashing.
|
||||
if s, err := packetString(value); err == nil {
|
||||
if s, ok := value.Value.(string); ok {
|
||||
c.ControlValue = s
|
||||
} else if data, err := packetData(value); err == nil {
|
||||
c.ControlValue = string(data)
|
||||
} else if value.Data != nil {
|
||||
c.ControlValue = value.Data.String()
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
@@ -929,64 +860,30 @@ func NewRequestControlDirSync(
|
||||
|
||||
// NewResponseControlDirSync returns a dir sync control
|
||||
func NewResponseControlDirSync(value *ber.Packet) (*ControlDirSync, error) {
|
||||
if value == nil {
|
||||
return nil, malformedf("dirSync control value is missing")
|
||||
}
|
||||
if value.Value != nil {
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
child, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
// also on initial creation, Cookie is an empty string
|
||||
if _, err := packetChildCount(child, 3, 3, "dirSync control value"); err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
flagsChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
maxAttrChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
}
|
||||
cookieChild, err := packetChild(child, 2)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control: %w", err)
|
||||
child := value.Children[0]
|
||||
if len(child.Children) != 3 { // also on initial creation, Cookie is an empty string
|
||||
return nil, fmt.Errorf("invalid number of children in dirSync control")
|
||||
}
|
||||
child.Description = "DirSync Control Value"
|
||||
flagsChild.Description = "Flags"
|
||||
maxAttrChild.Description = "MaxAttrCount"
|
||||
cookieChild.Description = "Cookie"
|
||||
child.Children[0].Description = "Flags"
|
||||
child.Children[1].Description = "MaxAttrCount"
|
||||
child.Children[2].Description = "Cookie"
|
||||
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cookieChild.Value = cookie
|
||||
flags, err := packetInt64(flagsChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
maxAttrCount, err := packetInt64(maxAttrChild)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cookie := child.Children[2].Data.Bytes()
|
||||
child.Children[2].Value = cookie
|
||||
return &ControlDirSync{
|
||||
Criticality: true,
|
||||
Flags: flags,
|
||||
MaxAttrCount: maxAttrCount,
|
||||
Flags: child.Children[0].Value.(int64),
|
||||
MaxAttrCount: child.Children[1].Value.(int64),
|
||||
Cookie: cookie,
|
||||
}, nil
|
||||
}
|
||||
@@ -1062,59 +959,39 @@ func (c *ControlServerSideSorting) GetControlType() string {
|
||||
}
|
||||
|
||||
func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error) {
|
||||
if value == nil {
|
||||
return nil, malformedf("server side sorting control value is missing")
|
||||
}
|
||||
data, err := packetData(value)
|
||||
val, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode packet err: %w", err)
|
||||
}
|
||||
val, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode packet err: %w", err)
|
||||
return nil, fmt.Errorf("decode packet err: %s", err)
|
||||
}
|
||||
|
||||
if _, err := packetChildCount(val, 1, -1, "sort key list"); err != nil {
|
||||
return nil, fmt.Errorf("no sequence value in packet: %w", err)
|
||||
if len(val.Children) == 0 {
|
||||
return nil, fmt.Errorf("no sequence value in packet")
|
||||
}
|
||||
|
||||
var sortKeys []*SortKey
|
||||
|
||||
for i, sequence := range val.Children {
|
||||
if sequence == nil {
|
||||
if len(sequence.Children) < 1 || len(sequence.Children) > 3 {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d", i)
|
||||
}
|
||||
if _, err := packetChildCount(sequence, 1, 3, "sort key sequence"); err != nil {
|
||||
return nil, fmt.Errorf("attributeType is missing from sequence %d: %w", i, err)
|
||||
}
|
||||
|
||||
sortKey := new(SortKey)
|
||||
|
||||
for _, child := range sequence.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case child.ClassType == ber.ClassUniversal && child.Tag == ber.TagOctetString:
|
||||
// A constructed-form OCTET STRING matches this case but leaves
|
||||
// Value nil; guard the assertion so a malformed attributeType is
|
||||
// rejected below rather than panicking.
|
||||
if attrType, err := packetString(child); err == nil {
|
||||
if attrType, ok := child.Value.(string); ok {
|
||||
sortKey.AttributeType = attrType
|
||||
}
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 0:
|
||||
b, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sortKey.MatchingRule = string(b)
|
||||
sortKey.MatchingRule = child.Data.String()
|
||||
|
||||
case child.ClassType == ber.ClassContext && child.Tag == 1:
|
||||
b, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := child.Data.Bytes()
|
||||
sortKey.Reverse = len(b) > 0 && b[0] != 0
|
||||
}
|
||||
}
|
||||
@@ -1221,7 +1098,7 @@ func (c ControlServerSideSortingCode) Valid() error {
|
||||
func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSortingResult, error) {
|
||||
control := new(ControlServerSideSortingResult)
|
||||
|
||||
if _, err := packetChildCount(pkt, 1, -1, "server side sorting result"); err != nil {
|
||||
if pkt == nil || len(pkt.Children) == 0 {
|
||||
// This is currently not compliant with the ServerSideSorting RFC (see https://datatracker.ietf.org/doc/html/rfc2891#section-1.2).
|
||||
// but it's necessary because there seems to be a bug in the implementation of the popular OpenLDAP server.
|
||||
//
|
||||
@@ -1229,11 +1106,7 @@ func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSorti
|
||||
return control, nil
|
||||
}
|
||||
|
||||
data, err := packetDataAt(pkt, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
codeInt, err := ber.ParseInt64(data)
|
||||
codeInt, err := ber.ParseInt64(pkt.Children[0].Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1256,7 +1129,7 @@ type ControlServerSideSortingResult struct {
|
||||
// AttributeType string
|
||||
}
|
||||
|
||||
func (c *ControlServerSideSortingResult) GetControlType() string {
|
||||
func (control *ControlServerSideSortingResult) GetControlType() string {
|
||||
return ControlTypeServerSideSortingResult
|
||||
}
|
||||
|
||||
@@ -1278,7 +1151,7 @@ func (c *ControlServerSideSortingResult) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// ControlSyncRequestMode is the mode for ControlTypeSyncRequest
|
||||
// Mode for ControlTypeSyncRequest
|
||||
type ControlSyncRequestMode int64
|
||||
|
||||
const (
|
||||
@@ -1352,7 +1225,7 @@ func (c *ControlSyncRequest) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// ControlSyncStateState is the state for ControlSyncState
|
||||
// State for ControlSyncState
|
||||
type ControlSyncStateState int64
|
||||
|
||||
const (
|
||||
@@ -1375,26 +1248,24 @@ func NewControlSyncState(pkt *ber.Packet) (*ControlSyncState, error) {
|
||||
state ControlSyncStateState
|
||||
entryUUID uuid.UUID
|
||||
cookie []byte
|
||||
err error
|
||||
)
|
||||
code, err := packetInt64At(pkt, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state = ControlSyncStateState(code)
|
||||
uuidChild, err := packetChild(pkt, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
entryUUID, err = uuid.FromBytes(uuidChild.ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
cookieChild, ok, err := packetChildIfPresent(pkt, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
cookie = cookieChild.ByteValue
|
||||
switch len(pkt.Children) {
|
||||
case 0, 1:
|
||||
return nil, fmt.Errorf("at least two children are required: %d", len(pkt.Children))
|
||||
case 2:
|
||||
state = ControlSyncStateState(pkt.Children[0].Value.(int64))
|
||||
entryUUID, err = uuid.FromBytes(pkt.Children[1].ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
case 3:
|
||||
state = ControlSyncStateState(pkt.Children[0].Value.(int64))
|
||||
entryUUID, err = uuid.FromBytes(pkt.Children[1].ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
}
|
||||
cookie = pkt.Children[2].ByteValue
|
||||
}
|
||||
return &ControlSyncState{
|
||||
Criticality: false,
|
||||
@@ -1434,30 +1305,19 @@ type ControlSyncDone struct {
|
||||
RefreshDeletes bool
|
||||
}
|
||||
|
||||
// parseSyncMembers identifies the members of an RFC 4533 sync sequence by tag.
|
||||
// cookie is OPTIONAL and the flags carry a DEFAULT, so a member's position is not
|
||||
// fixed and the count of present members does not identify them.
|
||||
func parseSyncMembers(children []*ber.Packet) (cookie []byte, flag *bool, uuidSet *ber.Packet) {
|
||||
for _, child := range children {
|
||||
switch child.Tag {
|
||||
case ber.TagOctetString:
|
||||
cookie = child.ByteValue
|
||||
case ber.TagBoolean:
|
||||
if b, err := packetBool(child); err == nil {
|
||||
flag = &b
|
||||
}
|
||||
case ber.TagSet:
|
||||
uuidSet = child
|
||||
}
|
||||
}
|
||||
return cookie, flag, uuidSet
|
||||
}
|
||||
|
||||
func NewControlSyncDone(pkt *ber.Packet) (*ControlSyncDone, error) {
|
||||
var refreshDeletes bool
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDeletes = *flag
|
||||
var (
|
||||
cookie []byte
|
||||
refreshDeletes bool
|
||||
)
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
}
|
||||
return &ControlSyncDone{
|
||||
Criticality: false,
|
||||
@@ -1488,7 +1348,7 @@ func (c *ControlSyncDone) String() string {
|
||||
)
|
||||
}
|
||||
|
||||
// ControlSyncInfoValue is the tag for ControlSyncInfo
|
||||
// Tag For ControlSyncInfo
|
||||
type ControlSyncInfoValue uint64
|
||||
|
||||
const (
|
||||
@@ -1570,12 +1430,13 @@ type ControlSyncInfo struct {
|
||||
|
||||
func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
var (
|
||||
cookie []byte
|
||||
refreshDone = true
|
||||
refreshDeletes bool
|
||||
syncUUIDs []uuid.UUID
|
||||
)
|
||||
c := &ControlSyncInfo{Criticality: false}
|
||||
switch ControlSyncInfoValue(pkt.Tag) {
|
||||
switch ControlSyncInfoValue(pkt.Identifier.Tag) {
|
||||
case SyncInfoNewcookie:
|
||||
c.Value = SyncInfoNewcookie
|
||||
c.NewCookie = &ControlSyncInfoNewCookie{
|
||||
@@ -1583,9 +1444,14 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoRefreshDelete:
|
||||
c.Value = SyncInfoRefreshDelete
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDone = *flag
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDone = pkt.Children[1].Value.(bool)
|
||||
}
|
||||
c.RefreshDelete = &ControlSyncInfoRefreshDelete{
|
||||
Cookie: cookie,
|
||||
@@ -1593,9 +1459,14 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoRefreshPresent:
|
||||
c.Value = SyncInfoRefreshPresent
|
||||
cookie, flag, _ := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDone = *flag
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDone = pkt.Children[1].Value.(bool)
|
||||
}
|
||||
c.RefreshPresent = &ControlSyncInfoRefreshPresent{
|
||||
Cookie: cookie,
|
||||
@@ -1603,13 +1474,19 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
}
|
||||
case SyncInfoSyncIdSet:
|
||||
c.Value = SyncInfoSyncIdSet
|
||||
cookie, flag, uuidSet := parseSyncMembers(pkt.Children)
|
||||
if flag != nil {
|
||||
refreshDeletes = *flag
|
||||
}
|
||||
if uuidSet != nil {
|
||||
syncUUIDs = make([]uuid.UUID, 0, len(uuidSet.Children))
|
||||
for _, child := range uuidSet.Children {
|
||||
switch len(pkt.Children) {
|
||||
case 0:
|
||||
// have nothing to do
|
||||
case 1:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
case 2:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
case 3:
|
||||
cookie = pkt.Children[0].ByteValue
|
||||
refreshDeletes = pkt.Children[1].Value.(bool)
|
||||
syncUUIDs = make([]uuid.UUID, 0, len(pkt.Children[2].Children))
|
||||
for _, child := range pkt.Children[2].Children {
|
||||
u, err := uuid.FromBytes(child.ByteValue)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode uuid: %w", err)
|
||||
@@ -1623,7 +1500,7 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
|
||||
SyncUUIDs: syncUUIDs,
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Tag)
|
||||
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Identifier.Tag)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ func (debug *debugging) Enable(b bool) {
|
||||
}
|
||||
|
||||
// Printf writes debug output.
|
||||
func (debug debugging) Printf(format string, args ...any) {
|
||||
func (debug debugging) Printf(format string, args ...interface{}) {
|
||||
if debug {
|
||||
logger.Printf(format, args...)
|
||||
}
|
||||
|
||||
+6
-6
@@ -52,16 +52,16 @@ func (l *Conn) Del(delRequest *DelRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationDelResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
if packet.Children[1].Tag == ApplicationDelResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+23
-71
@@ -90,7 +90,6 @@ const (
|
||||
ErrorUnexpectedMessage = 204
|
||||
ErrorUnexpectedResponse = 205
|
||||
ErrorEmptyPassword = 206
|
||||
ErrorMalformedPacket = 207
|
||||
)
|
||||
|
||||
// LDAPResultCodeMap contains string descriptions for LDAP error codes
|
||||
@@ -176,7 +175,6 @@ var LDAPResultCodeMap = map[uint16]string{
|
||||
ErrorUnexpectedMessage: "Unexpected Message",
|
||||
ErrorUnexpectedResponse: "Unexpected Response",
|
||||
ErrorEmptyPassword: "Empty password not allowed by the client",
|
||||
ErrorMalformedPacket: "Malformed Packet",
|
||||
}
|
||||
|
||||
// Error holds LDAP error information
|
||||
@@ -197,93 +195,47 @@ func (e *Error) Error() string {
|
||||
|
||||
func (e *Error) Unwrap() error { return e.Err }
|
||||
|
||||
// parseLDAPResult extracts resultCode, matchedDN, and diagnosticMessage from a
|
||||
// BER packet representing an LDAPResult (e.g. SearchResultDone).
|
||||
//
|
||||
// Unlike GetLDAPError, parseLDAPResult does not return early when resultCode is
|
||||
// success (0). This allows callers to read the diagnosticMessage even on a
|
||||
// successful operation, which some servers use to signal warnings or degraded
|
||||
// state (for example, a directory in read-only / reinitializing mode).
|
||||
//
|
||||
// Per RFC 4511, an LDAPResult must contain resultCode, matchedDN, and
|
||||
// diagnosticMessage. An error is returned if the packet is malformed.
|
||||
func parseLDAPResult(packet *ber.Packet) (resultCode uint16, matchedDN, diagnosticMessage string, err error) {
|
||||
response, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return 0, "", "", err
|
||||
}
|
||||
|
||||
children, err := packetChildCount(response, 3, 4, "LDAP Result")
|
||||
if err != nil {
|
||||
return 0, "", "", err
|
||||
}
|
||||
|
||||
resultCode, err = packetResultCode(children[0])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if matchedDN, err = packetString(children[1]); err != nil {
|
||||
return
|
||||
}
|
||||
diagnosticMessage, err = packetString(children[2])
|
||||
return
|
||||
}
|
||||
|
||||
// GetLDAPError creates an Error out of a BER packet representing a LDAPResult
|
||||
// The return is an error object. It can be casted to a Error structure.
|
||||
// This function returns nil if resultCode in the LDAPResult sequence is success(0).
|
||||
func GetLDAPError(packet *ber.Packet) error {
|
||||
if packet == nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("empty packet")}
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty packet")}
|
||||
}
|
||||
|
||||
if _, err := packetChildCount(packet, 2, -1, "LDAP response"); err == nil {
|
||||
response, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("empty response in packet"), Packet: packet}
|
||||
if len(packet.Children) >= 2 {
|
||||
response := packet.Children[1]
|
||||
if response == nil {
|
||||
return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty response in packet"), Packet: packet}
|
||||
}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed {
|
||||
if _, err := packetChildCount(response, 3, -1, "LDAP result"); err == nil {
|
||||
resultCodeChild, err := packetChild(response, 0)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid result code in packet"), Packet: packet}
|
||||
if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 {
|
||||
if ber.Type(response.Children[0].Tag) == ber.Type(ber.TagInteger) || ber.Type(response.Children[0].Tag) == ber.Type(ber.TagEnumerated) {
|
||||
if response.Children[0].Value == nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid result code in packet"), Packet: packet}
|
||||
}
|
||||
if ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagInteger) || ber.Type(resultCodeChild.Tag) == ber.Type(ber.TagEnumerated) {
|
||||
resultCode, err := packetResultCode(resultCodeChild)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid result code in packet"), Packet: packet}
|
||||
}
|
||||
|
||||
if resultCode == 0 { // No error
|
||||
return nil
|
||||
}
|
||||
resultCode := uint16(response.Children[0].Value.(int64))
|
||||
if resultCode == 0 { // No error
|
||||
return nil
|
||||
}
|
||||
|
||||
matchedDNChild, matchedDNErr := packetChild(response, 1)
|
||||
errorMessageChild, errorMessageErr := packetChild(response, 2)
|
||||
if matchedDNErr != nil || errorMessageErr != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid packet format"), Packet: packet}
|
||||
if ber.Type(response.Children[1].Tag) == ber.Type(ber.TagOctetString) &&
|
||||
ber.Type(response.Children[2].Tag) == ber.Type(ber.TagOctetString) {
|
||||
if response.Children[1].Value == nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid matchedDN in packet"), Packet: packet}
|
||||
}
|
||||
|
||||
if ber.Type(matchedDNChild.Tag) == ber.Type(ber.TagOctetString) &&
|
||||
ber.Type(errorMessageChild.Tag) == ber.Type(ber.TagOctetString) {
|
||||
matchedDN, err := packetString(matchedDNChild)
|
||||
if err != nil {
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid matchedDN in packet"), Packet: packet}
|
||||
}
|
||||
return &Error{
|
||||
ResultCode: resultCode,
|
||||
MatchedDN: matchedDN,
|
||||
Err: fmt.Errorf("%v", errorMessageChild.Value),
|
||||
Packet: packet,
|
||||
}
|
||||
return &Error{
|
||||
ResultCode: resultCode,
|
||||
MatchedDN: response.Children[1].Value.(string),
|
||||
Err: fmt.Errorf("%v", response.Children[2].Value),
|
||||
Packet: packet,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("invalid packet format"), Packet: packet}
|
||||
return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid packet format"), Packet: packet}
|
||||
}
|
||||
|
||||
// NewError creates an LDAP error with the given code and underlying error
|
||||
|
||||
+12
-38
@@ -32,7 +32,7 @@ func (er ExtendedRequest) appendTo(envelope *ber.Packet) error {
|
||||
pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Extended Request")
|
||||
pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, ber.TagEOC, er.Name, "Extended Request Name"))
|
||||
if er.Value != nil {
|
||||
pkt.AppendChild(encodeExtendedRequestValue(er.Value))
|
||||
pkt.AppendChild(er.Value)
|
||||
}
|
||||
envelope.AppendChild(pkt)
|
||||
if len(er.Controls) > 0 {
|
||||
@@ -41,16 +41,6 @@ func (er ExtendedRequest) appendTo(envelope *ber.Packet) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// encodeExtendedRequestValue wraps the caller payload as RFC 4511 requestValue
|
||||
// [1] OCTET STRING. Callers that already built that field (context class, tag 1)
|
||||
// are left unchanged so Password Modify-style packets are not double-wrapped.
|
||||
func encodeExtendedRequestValue(value *ber.Packet) *ber.Packet {
|
||||
if value.ClassType == ber.ClassContext && value.Tag == 1 {
|
||||
return value
|
||||
}
|
||||
return ber.NewString(ber.ClassContext, ber.TypePrimitive, 1, string(value.Bytes()), "Extended Request Value")
|
||||
}
|
||||
|
||||
// ExtendedResponse represents the response from the directory server
|
||||
// after sending an extended request
|
||||
// See: https://www.rfc-editor.org/rfc/rfc4511#section-4.12
|
||||
@@ -82,24 +72,16 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return decodeExtendedResponse(packet)
|
||||
}
|
||||
|
||||
// decodeExtendedResponse decodes an extended response envelope, including any
|
||||
// response controls. It is separated from the network loop so the full
|
||||
// response decoder can be fuzzed directly.
|
||||
func decodeExtendedResponse(packet *ber.Packet) (*ExtendedResponse, error) {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
extResp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := packetChildCount(extResp, 3, -1, "extended response"); err != nil {
|
||||
return nil, err
|
||||
extResp := packet.Children[1]
|
||||
if len(extResp.Children) < 3 {
|
||||
return nil, fmt.Errorf(
|
||||
"ldap: malformed extended response: expected at least 3 children, got %d",
|
||||
len(packet.Children),
|
||||
)
|
||||
}
|
||||
|
||||
response := &ExtendedResponse{
|
||||
@@ -117,25 +99,17 @@ func decodeExtendedResponse(packet *ber.Packet) (*ExtendedResponse, error) {
|
||||
}
|
||||
switch child.Tag {
|
||||
case ber.TagEnumerated:
|
||||
name, err := packetData(child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Name = string(name)
|
||||
response.Name = child.Data.String()
|
||||
case ber.TagEmbeddedPDV:
|
||||
response.Value = child
|
||||
}
|
||||
}
|
||||
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controlsChild.Children {
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, decodeErr := DecodeControl(child)
|
||||
if decodeErr != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
|
||||
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
|
||||
}
|
||||
response.Controls = append(response.Controls, decodedChild)
|
||||
}
|
||||
|
||||
+3
-18
@@ -208,12 +208,9 @@ func compileFilterSet(filter string, pos int, parent *ber.Packet) (int, error) {
|
||||
pos = newPos
|
||||
parent.AppendChild(child)
|
||||
}
|
||||
if pos >= len(filter) {
|
||||
if pos == len(filter) {
|
||||
return pos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
|
||||
}
|
||||
if filter[pos] != ')' {
|
||||
return pos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: expected ')' at position %d", pos))
|
||||
}
|
||||
|
||||
return pos + 1, nil
|
||||
}
|
||||
@@ -238,17 +235,8 @@ func compileFilter(filter string, pos int) (*ber.Packet, int, error) {
|
||||
return nil, 0, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos))
|
||||
case '(':
|
||||
packet, newPos, err = compileFilter(filter, pos+currentWidth)
|
||||
if err != nil {
|
||||
return nil, newPos, err
|
||||
}
|
||||
if newPos >= len(filter) {
|
||||
return nil, newPos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
|
||||
}
|
||||
if filter[newPos] != ')' {
|
||||
return nil, newPos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: expected ')' at position %d", newPos))
|
||||
}
|
||||
newPos++
|
||||
return packet, newPos, nil
|
||||
return packet, newPos, err
|
||||
case '&':
|
||||
packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterAnd, nil, FilterMap[FilterAnd])
|
||||
newPos, err = compileFilterSet(filter, pos+currentWidth, packet)
|
||||
@@ -261,11 +249,8 @@ func compileFilter(filter string, pos int) (*ber.Packet, int, error) {
|
||||
packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterNot, nil, FilterMap[FilterNot])
|
||||
var child *ber.Packet
|
||||
child, newPos, err = compileFilter(filter, pos+currentWidth)
|
||||
if err != nil {
|
||||
return nil, newPos, err
|
||||
}
|
||||
packet.AppendChild(child)
|
||||
return packet, newPos, nil
|
||||
return packet, newPos, err
|
||||
default:
|
||||
const (
|
||||
stateReadingAttr = 0
|
||||
|
||||
+68
-198
@@ -2,6 +2,7 @@ package ldap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -100,18 +101,10 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
}
|
||||
}()
|
||||
packet.Description = "LDAP Response"
|
||||
messageID, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messageID.Description = "Message ID"
|
||||
packet.Children[0].Description = "Message ID"
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
application := uint8(protocolOp.Tag)
|
||||
protocolOp.Description = ApplicationMap[application]
|
||||
application := uint8(packet.Children[1].Tag)
|
||||
packet.Children[1].Description = ApplicationMap[application]
|
||||
|
||||
switch application {
|
||||
case ApplicationBindRequest:
|
||||
@@ -123,46 +116,18 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
case ApplicationSearchRequest:
|
||||
err = addRequestDescriptions(packet)
|
||||
case ApplicationSearchResultEntry:
|
||||
objectName, err := packetChild(protocolOp, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objectName.Description = "Object Name"
|
||||
attrs, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrs.Description = "Attributes"
|
||||
for _, child := range attrs.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
packet.Children[1].Children[0].Description = "Object Name"
|
||||
packet.Children[1].Children[1].Description = "Attributes"
|
||||
for _, child := range packet.Children[1].Children[1].Children {
|
||||
child.Description = "Attribute"
|
||||
nameChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nameChild.Description = "Attribute Name"
|
||||
valuesChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
valuesChild.Description = "Attribute Values"
|
||||
for _, grandchild := range valuesChild.Children {
|
||||
if grandchild == nil {
|
||||
continue
|
||||
}
|
||||
child.Children[0].Description = "Attribute Name"
|
||||
child.Children[1].Description = "Attribute Values"
|
||||
for _, grandchild := range child.Children[1].Children {
|
||||
grandchild.Description = "Attribute Value"
|
||||
}
|
||||
}
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
if err = addControlDescriptions(controls); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(packet.Children) == 3 {
|
||||
err = addControlDescriptions(packet.Children[2])
|
||||
}
|
||||
case ApplicationSearchResultDone:
|
||||
err = addDefaultLDAPResponseDescriptions(packet)
|
||||
@@ -195,55 +160,42 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
|
||||
func addControlDescriptions(packet *ber.Packet) error {
|
||||
packet.Description = "Controls"
|
||||
for _, child := range packet.Children {
|
||||
if child == nil {
|
||||
return fmt.Errorf("nil control packet found")
|
||||
}
|
||||
var value *ber.Packet
|
||||
controlType := ""
|
||||
child.Description = "Control"
|
||||
switch len(child.Children) {
|
||||
case 0:
|
||||
// at least one child is required for control type
|
||||
return fmt.Errorf("at least one child is required for control type")
|
||||
|
||||
controlChildren, err := packetChildCount(child, 1, 3, "control packet")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case 1:
|
||||
// just type, no criticality or value
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
|
||||
typeChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
controlType, err = packetString(typeChild)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
typeChild.Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
|
||||
switch len(controlChildren) {
|
||||
case 2:
|
||||
second, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Children[1] is criticality or value; identify it by its ASN.1 tag.
|
||||
if second.ClassType == ber.ClassUniversal && second.Tag == ber.TagBoolean {
|
||||
second.Description = "Criticality"
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
// Children[1] could be criticality or value (both are optional)
|
||||
// duck-type on whether this is a boolean
|
||||
if _, ok := child.Children[1].Value.(bool); ok {
|
||||
child.Children[1].Description = "Criticality"
|
||||
} else {
|
||||
second.Description = "Control Value"
|
||||
value = second
|
||||
child.Children[1].Description = "Control Value"
|
||||
value = child.Children[1]
|
||||
}
|
||||
|
||||
case 3:
|
||||
// criticality and value present
|
||||
criticality, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
criticality.Description = "Criticality"
|
||||
valueChild, err := packetChild(child, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
valueChild.Description = "Control Value"
|
||||
value = valueChild
|
||||
controlType = child.Children[0].Value.(string)
|
||||
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
|
||||
child.Children[1].Description = "Criticality"
|
||||
child.Children[2].Description = "Control Value"
|
||||
value = child.Children[2]
|
||||
|
||||
default:
|
||||
// more than 3 children is invalid
|
||||
return fmt.Errorf("more than 3 children for control packet found")
|
||||
}
|
||||
|
||||
if value == nil {
|
||||
@@ -253,99 +205,53 @@ func addControlDescriptions(packet *ber.Packet) error {
|
||||
case ControlTypePaging:
|
||||
value.Description += " (Paging)"
|
||||
if value.Value != nil {
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
cookieChild, err := packetChild(valueChildren, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookie, err := packetData(cookieChild)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookieChild.Value = cookie
|
||||
valueChildren.Children[1].Value = valueChildren.Children[1].Data.Bytes()
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
real, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
real.Description = "Real Search Control Value"
|
||||
sizeChild, err := packetChild(real, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cookieChild, err := packetChild(real, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sizeChild.Description = "Paging Size"
|
||||
cookieChild.Description = "Cookie"
|
||||
value.Children[0].Description = "Real Search Control Value"
|
||||
value.Children[0].Children[0].Description = "Paging Size"
|
||||
value.Children[0].Children[1].Description = "Cookie"
|
||||
|
||||
case ControlTypeBeheraPasswordPolicy:
|
||||
value.Description += " (Password Policy - Behera Draft)"
|
||||
if value.Value != nil {
|
||||
data, err := packetData(value)
|
||||
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
valueChildren, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
value.Data.Truncate(0)
|
||||
value.Value = nil
|
||||
value.AppendChild(valueChildren)
|
||||
}
|
||||
sequence, err := packetChild(value, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sequence := value.Children[0]
|
||||
for _, child := range sequence.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
switch child.Tag {
|
||||
case 0:
|
||||
if child.Tag == 0 {
|
||||
// Warning
|
||||
warningPacket, err := packetChild(child, 0)
|
||||
warningPacket := child.Children[0]
|
||||
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to decode data bytes: %s", err)
|
||||
}
|
||||
data, err := packetData(warningPacket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
val, err := ber.ParseInt64(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode data bytes: %w", err)
|
||||
}
|
||||
switch warningPacket.Tag {
|
||||
case 0:
|
||||
if warningPacket.Tag == 0 {
|
||||
// timeBeforeExpiration
|
||||
value.Description += " (TimeBeforeExpiration)"
|
||||
warningPacket.Value = val
|
||||
case 1:
|
||||
} else if warningPacket.Tag == 1 {
|
||||
// graceAuthNsRemaining
|
||||
value.Description += " (GraceAuthNsRemaining)"
|
||||
warningPacket.Value = val
|
||||
}
|
||||
case 1:
|
||||
} else if child.Tag == 1 {
|
||||
// Error
|
||||
bs, err := packetData(child)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bs := child.Data.Bytes()
|
||||
if len(bs) != 1 || bs[0] > 8 {
|
||||
return malformedf("invalid PasswordPolicyResponse enum value")
|
||||
return fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
|
||||
}
|
||||
val := int8(bs[0])
|
||||
child.Description = "Error"
|
||||
@@ -359,22 +265,10 @@ func addControlDescriptions(packet *ber.Packet) error {
|
||||
|
||||
func addRequestDescriptions(packet *ber.Packet) error {
|
||||
packet.Description = "LDAP Request"
|
||||
messageID, err := packetChild(packet, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
messageID.Description = "Message ID"
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
protocolOp.Description = ApplicationMap[uint8(protocolOp.Tag)]
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return addControlDescriptions(controls)
|
||||
packet.Children[0].Description = "Message ID"
|
||||
packet.Children[1].Description = ApplicationMap[uint8(packet.Children[1].Tag)]
|
||||
if len(packet.Children) == 3 {
|
||||
return addControlDescriptions(packet.Children[2])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -389,52 +283,28 @@ func addDefaultLDAPResponseDescriptions(packet *ber.Packet) error {
|
||||
description = "Error Message"
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
packet.Children[1].Children[0].Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")"
|
||||
packet.Children[1].Children[1].Description = "Matched DN (" + matchedDN + ")"
|
||||
packet.Children[1].Children[2].Description = description
|
||||
if len(packet.Children[1].Children) > 3 {
|
||||
packet.Children[1].Children[3].Description = "Referral"
|
||||
}
|
||||
resultCodeChild, err := packetChild(protocolOp, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resultCodeChild.Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")"
|
||||
matchedDNChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
matchedDNChild.Description = "Matched DN (" + matchedDN + ")"
|
||||
errorMessageChild, err := packetChild(protocolOp, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
errorMessageChild.Description = description
|
||||
referral, ok, err := packetChildIfPresent(protocolOp, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
referral.Description = "Referral"
|
||||
}
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return addControlDescriptions(controls)
|
||||
if len(packet.Children) == 3 {
|
||||
return addControlDescriptions(packet.Children[2])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DebugBinaryFile reads and prints packets from the given filename
|
||||
func DebugBinaryFile(fileName string) error {
|
||||
file, err := os.ReadFile(fileName)
|
||||
file, err := ioutil.ReadFile(fileName)
|
||||
if err != nil {
|
||||
return NewError(ErrorDebugging, err)
|
||||
}
|
||||
ber.PrintBytes(os.Stdout, file, "")
|
||||
packet, err := ber.DecodePacketErr(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode packet: %w", err)
|
||||
return fmt.Errorf("failed to decode packet: %s", err)
|
||||
}
|
||||
if err := addLDAPDescriptions(packet); err != nil {
|
||||
return err
|
||||
|
||||
+6
-6
@@ -89,16 +89,16 @@ func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationModifyDNResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
if packet.Children[1].Tag == ApplicationModifyDNResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+13
-18
@@ -121,16 +121,16 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
|
||||
return err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
if len(packet.Children) < 2 {
|
||||
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationModifyResponse {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
if packet.Children[1].Tag == ApplicationModifyResponse {
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -162,22 +162,19 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
|
||||
return nil, err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if protocolOp.Tag == ApplicationModifyResponse {
|
||||
|
||||
switch packet.Children[1].Tag {
|
||||
case ApplicationModifyResponse:
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
result.Referral = getReferral(err, packet)
|
||||
|
||||
return result, err
|
||||
}
|
||||
controls, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controls.Children {
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return nil, errors.New("failed to decode child control: " + err.Error())
|
||||
@@ -185,8 +182,6 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nil, fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
|
||||
}
|
||||
l.Debug.Printf("%d: returning", msgCtx.id)
|
||||
return result, nil
|
||||
|
||||
-180
@@ -1,180 +0,0 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
ber "github.com/go-asn1-ber/asn1-ber"
|
||||
)
|
||||
|
||||
// ErrMalformedPacket is the sentinel wrapped by the structural decoding
|
||||
// failures reported by the helpers in this file, so callers can distinguish a
|
||||
// malformed packet with errors.Is. It is nested inside the LDAP-style *Error
|
||||
// (ResultCode ErrorMalformedPacket) built by malformedf; wrapping that error
|
||||
// with %s instead of %w drops the sentinel from the chain.
|
||||
var ErrMalformedPacket = errors.New("ldap: malformed packet")
|
||||
|
||||
// malformedf builds an LDAP-style error (NewError with ErrorMalformedPacket)
|
||||
// wrapping ErrMalformedPacket. Callers must wrap its result with %w, not %s,
|
||||
// to keep both the *Error and the sentinel matchable with errors.As/errors.Is.
|
||||
func malformedf(format string, args ...any) error {
|
||||
return NewError(ErrorMalformedPacket, fmt.Errorf("%w: %s", ErrMalformedPacket, fmt.Sprintf(format, args...)))
|
||||
}
|
||||
|
||||
// packetChildCount asserts that p has between min and max direct children
|
||||
// (inclusive) and returns them. A negative min disables the lower bound and a
|
||||
// negative max disables the upper bound. It centralizes the repeated
|
||||
// children-count validation so every decode path rejects malformed packets
|
||||
// with a consistent, descriptive error instead of a bespoke length check.
|
||||
//
|
||||
// min == max means an exact count is required.
|
||||
func packetChildCount(p *ber.Packet, min, max int, what string) ([]*ber.Packet, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("%s is missing", what)
|
||||
}
|
||||
n := len(p.Children)
|
||||
switch {
|
||||
case min >= 0 && max >= 0 && min == max && n != min:
|
||||
return nil, malformedf("%s: expected %d children, got %d", what, min, n)
|
||||
case min >= 0 && n < min:
|
||||
return nil, malformedf("%s: expected %d or more children, got %d", what, min, n)
|
||||
case max >= 0 && n > max:
|
||||
return nil, malformedf("%s: expected at most %d children, got %d", what, max, n)
|
||||
}
|
||||
return p.Children, nil
|
||||
}
|
||||
|
||||
// packetChild returns the i-th child of p. It is the primary accessor for
|
||||
// inbound packets: a field's position in its ASN.1 SEQUENCE is fixed by the
|
||||
// relevant RFC, so callers must address packets by order rather than by
|
||||
// inspecting the Go type of a child's Value.
|
||||
func packetChild(p *ber.Packet, i int) (*ber.Packet, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("nil packet")
|
||||
}
|
||||
if i < 0 || i >= len(p.Children) {
|
||||
return nil, malformedf("child index %d out of range, packet has %d children", i, len(p.Children))
|
||||
}
|
||||
child := p.Children[i]
|
||||
if child == nil {
|
||||
return nil, malformedf("child index %d is nil", i)
|
||||
}
|
||||
return child, nil
|
||||
}
|
||||
|
||||
// packetChildIfPresent is packetChild for OPTIONAL members: when the packet
|
||||
// has no child at index i it reports ok == false instead of an error. A nil
|
||||
// packet or a nil placeholder child is still an error, because those are
|
||||
// invalid rather than simply absent.
|
||||
func packetChildIfPresent(p *ber.Packet, i int) (child *ber.Packet, ok bool, err error) {
|
||||
if p == nil {
|
||||
return nil, false, malformedf("nil packet")
|
||||
}
|
||||
if i < 0 || i >= len(p.Children) {
|
||||
return nil, false, nil
|
||||
}
|
||||
child = p.Children[i]
|
||||
if child == nil {
|
||||
return nil, false, malformedf("child index %d is nil", i)
|
||||
}
|
||||
return child, true, nil
|
||||
}
|
||||
|
||||
// packetString returns the string value of p. The field's position or tag is
|
||||
// expected to have already fixed it as a string by the schema; this is the
|
||||
// single guarded leaf conversion, never a way to discover what a field is.
|
||||
func packetString(p *ber.Packet) (string, error) {
|
||||
if p == nil {
|
||||
return "", malformedf("missing string value")
|
||||
}
|
||||
s, ok := p.Value.(string)
|
||||
if !ok {
|
||||
return "", malformedf("expected string value, got %T", p.Value)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// packetInt64 returns the int64 value of p, whose schema position fixed it as
|
||||
// an INTEGER or ENUMERATED.
|
||||
func packetInt64(p *ber.Packet) (int64, error) {
|
||||
if p == nil {
|
||||
return 0, malformedf("missing integer value")
|
||||
}
|
||||
i, ok := p.Value.(int64)
|
||||
if !ok {
|
||||
return 0, malformedf("expected integer value, got %T", p.Value)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// packetResultCode returns the LDAPResult resultCode held by p. RFC 4511
|
||||
// declares resultCode an ENUMERATED and the codes it assigns all fit the uint16
|
||||
// this package exposes, so a value outside that range is malformed rather than
|
||||
// merely unknown. Narrowing it instead would alias it onto an unrelated code,
|
||||
// and any multiple of 2^16 onto success(0).
|
||||
func packetResultCode(p *ber.Packet) (uint16, error) {
|
||||
code, err := packetInt64(p)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if code < 0 || code > math.MaxUint16 {
|
||||
return 0, malformedf("result code %d out of range", code)
|
||||
}
|
||||
return uint16(code), nil
|
||||
}
|
||||
|
||||
// packetBool returns the bool value of p, whose schema position or BOOLEAN tag
|
||||
// fixed it as a boolean.
|
||||
func packetBool(p *ber.Packet) (bool, error) {
|
||||
if p == nil {
|
||||
return false, malformedf("missing boolean value")
|
||||
}
|
||||
b, ok := p.Value.(bool)
|
||||
if !ok {
|
||||
return false, malformedf("expected boolean value, got %T", p.Value)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// packetData returns the raw BER contents of p. Unlike p.Data.Bytes() it is
|
||||
// nil-safe, so a packet that carries no data buffer yields an error rather
|
||||
// than a nil-pointer panic.
|
||||
func packetData(p *ber.Packet) ([]byte, error) {
|
||||
if p == nil {
|
||||
return nil, malformedf("missing packet data")
|
||||
}
|
||||
if p.Data == nil {
|
||||
return nil, malformedf("packet has no data buffer")
|
||||
}
|
||||
return p.Data.Bytes(), nil
|
||||
}
|
||||
|
||||
// packetStringAt returns the string value of the i-th child of p. It combines
|
||||
// ordered access with the guarded leaf conversion and is the common shape for
|
||||
// response fields such as a DN or a referral URI.
|
||||
func packetStringAt(p *ber.Packet, i int) (string, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return packetString(child)
|
||||
}
|
||||
|
||||
// packetInt64At returns the int64 value of the i-th child of p.
|
||||
func packetInt64At(p *ber.Packet, i int) (int64, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return packetInt64(child)
|
||||
}
|
||||
|
||||
// packetDataAt returns the raw BER contents of the i-th child of p.
|
||||
func packetDataAt(p *ber.Packet, i int) ([]byte, error) {
|
||||
child, err := packetChild(p, i)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return packetData(child)
|
||||
}
|
||||
+10
-29
@@ -93,48 +93,29 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
|
||||
|
||||
result := &PasswordModifyResult{}
|
||||
|
||||
extendedResponse, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if len(packet.Children) < 2 {
|
||||
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
|
||||
}
|
||||
if extendedResponse.Tag == ApplicationExtendedResponse {
|
||||
if packet.Children[1].Tag == ApplicationExtendedResponse {
|
||||
if err = GetLDAPError(packet); err != nil {
|
||||
result.Referral = getReferral(err, packet)
|
||||
|
||||
return result, err
|
||||
}
|
||||
} else {
|
||||
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", extendedResponse.Tag))
|
||||
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag))
|
||||
}
|
||||
|
||||
extendedResponse := packet.Children[1]
|
||||
for _, child := range extendedResponse.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
if child.Tag == ber.TagEmbeddedPDV {
|
||||
data, err := packetData(child)
|
||||
passwordModifyResponseValue, err := ber.DecodePacketErr(child.Data.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %w", err)
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %s", err)
|
||||
}
|
||||
passwordModifyResponseValue, err := ber.DecodePacketErr(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %w", err)
|
||||
}
|
||||
pwChildren, err := packetChildCount(passwordModifyResponseValue, 0, 1, "password modify response value")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pwChildren) == 1 {
|
||||
generatedPasswordValue, err := packetChild(passwordModifyResponseValue, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if generatedPasswordValue.Tag == ber.TagEOC {
|
||||
pw, err := packetData(generatedPasswordValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result.GeneratedPassword = ber.DecodeString(pw)
|
||||
if len(passwordModifyResponseValue.Children) == 1 {
|
||||
if passwordModifyResponseValue.Children[0].Tag == ber.TagEOC {
|
||||
result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-13
@@ -76,8 +76,7 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
return ""
|
||||
}
|
||||
|
||||
protocolOp, perr := packetChild(packet, 1)
|
||||
if perr != nil {
|
||||
if len(packet.Children) < 2 {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -88,17 +87,13 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
//
|
||||
// Related Issues:
|
||||
// - https://github.com/authelia/authelia/issues/4199 (downstream)
|
||||
if protocolOp.TagType != ber.TypeConstructed || protocolOp.ClassType != ber.ClassApplication {
|
||||
return ""
|
||||
}
|
||||
if _, err := packetChildCount(protocolOp, 1, -1, "referral"); err != nil {
|
||||
if len(packet.Children[1].Children) == 0 || (packet.Children[1].TagType != ber.TypeConstructed || packet.Children[1].ClassType != ber.ClassApplication) {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, child := range protocolOp.Children {
|
||||
if child == nil {
|
||||
continue
|
||||
}
|
||||
var ok bool
|
||||
|
||||
for _, child := range packet.Children[1].Children {
|
||||
// The referral URI itself should be contained within a child which has a Tag of ber.BitString or
|
||||
// ber.TagPrintableString, and the Type of ber.TypeConstructed and the Class of ClassContext. As soon as any of
|
||||
// these conditions is not true we can skip this child.
|
||||
@@ -110,11 +105,11 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
|
||||
// malicious server can send an empty SEQUENCE. Skip it instead of indexing
|
||||
// child.Children[0], which would panic the goroutine that called Modify or
|
||||
// PasswordModify.
|
||||
uriChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
if len(child.Children) == 0 {
|
||||
continue
|
||||
}
|
||||
if referral, err := packetString(uriChild); err == nil {
|
||||
|
||||
if referral, ok = child.Children[0].Value.(string); ok {
|
||||
return referral
|
||||
}
|
||||
}
|
||||
|
||||
+33
-92
@@ -140,48 +140,60 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
ber.PrintPacket(packet)
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
switch protocolOp.Tag {
|
||||
switch packet.Children[1].Tag {
|
||||
case ApplicationSearchResultEntry:
|
||||
result, err := decodeSearchResultEntry(packet)
|
||||
result := &SearchSingleResult{
|
||||
Entry: &Entry{
|
||||
DN: packet.Children[1].Children[0].Value.(string),
|
||||
Attributes: unpackAttributes(packet.Children[1].Children[1].Children),
|
||||
},
|
||||
}
|
||||
if len(packet.Children) != 3 {
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
decoded, err := DecodeControl(packet.Children[2].Children[0])
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
werr := fmt.Errorf("failed to decode search result entry: %w", err)
|
||||
result.Error = werr
|
||||
r.send(ctx, result)
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationSearchResultDone:
|
||||
result, err := decodeSearchResultDone(packet)
|
||||
if err != nil {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
if result != nil {
|
||||
if !r.send(ctx, result) {
|
||||
return
|
||||
if len(packet.Children) == 3 {
|
||||
result := &SearchSingleResult{}
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode child control: %w", err)
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
return
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
r.send(ctx, result)
|
||||
}
|
||||
foundSearchSingleResultDone = true
|
||||
|
||||
case ApplicationSearchResultReference:
|
||||
ref, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
ref := packet.Children[1].Children[0].Value.(string)
|
||||
if !r.send(ctx, &SearchSingleResult{Referral: ref}) {
|
||||
return
|
||||
}
|
||||
|
||||
case ApplicationIntermediateResponse:
|
||||
decoded, err := DecodeControl(protocolOp)
|
||||
decoded, err := DecodeControl(packet.Children[1])
|
||||
if err != nil {
|
||||
werr := fmt.Errorf("failed to decode intermediate response: %w", err)
|
||||
r.send(ctx, &SearchSingleResult{Error: werr})
|
||||
@@ -194,7 +206,7 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
}
|
||||
|
||||
default:
|
||||
err := fmt.Errorf("unknown tag: %d", protocolOp.Tag)
|
||||
err := fmt.Errorf("unknown tag: %d", packet.Children[1].Tag)
|
||||
r.send(ctx, &SearchSingleResult{Error: err})
|
||||
return
|
||||
}
|
||||
@@ -204,77 +216,6 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
|
||||
}()
|
||||
}
|
||||
|
||||
// decodeSearchResultEntry decodes a SearchResultEntry envelope, including any
|
||||
// response controls. It is kept out of the network loop so the full response
|
||||
// decoder can be exercised directly by the fuzz targets.
|
||||
func decodeSearchResultEntry(packet *ber.Packet) (*SearchSingleResult, error) {
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributesChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attributes, err := unpackAttributes(attributesChild.Children)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dn, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := &SearchSingleResult{
|
||||
Entry: &Entry{
|
||||
DN: dn,
|
||||
Attributes: attributes,
|
||||
},
|
||||
}
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
for _, controlChild := range controlsChild.Children {
|
||||
decoded, err := DecodeControl(controlChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode search result entry: %w", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decoded)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// decodeSearchResultDone decodes a SearchResultDone envelope. It returns a nil
|
||||
// result with a nil error when the response carries no controls, so the caller
|
||||
// does not enqueue an empty result.
|
||||
func decodeSearchResultDone(packet *ber.Packet) (*SearchSingleResult, error) {
|
||||
if err := GetLDAPError(packet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
result := &SearchSingleResult{}
|
||||
for _, child := range controlsChild.Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decode child control: %w", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
if len(result.Controls) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func newSearchResponse(conn *Conn, bufferSize int) *searchResponse {
|
||||
var ch chan *SearchSingleResult
|
||||
if bufferSize > 0 {
|
||||
|
||||
+25
-101
@@ -245,7 +245,7 @@ func readTag(f reflect.StructField) (string, bool) {
|
||||
// if err := result.Unmarshal(&user); err != nil {
|
||||
// // ...
|
||||
// }
|
||||
func (e *Entry) Unmarshal(i any) (err error) {
|
||||
func (e *Entry) Unmarshal(i interface{}) (err error) {
|
||||
return e.UnmarshalFunc(i, func(entry *Entry, ft reflect.StructField, fv reflect.Value) error {
|
||||
// omitempty can be safely discarded, as it's not needed when unmarshalling
|
||||
fieldTag, _ := readTag(ft)
|
||||
@@ -307,10 +307,10 @@ func (e *Entry) Unmarshal(i any) (err error) {
|
||||
|
||||
// UnmarshalFunc allows you to define a custom unmarshaler to parse an Entry values.
|
||||
// A custom unmarshaler can be found in the Unmarshal function or in the test files.
|
||||
func (e *Entry) UnmarshalFunc(i any,
|
||||
func (e *Entry) UnmarshalFunc(i interface{},
|
||||
fn func(entry *Entry, fieldType reflect.StructField, fieldValue reflect.Value) error) error {
|
||||
// Make sure it's a ptr
|
||||
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Pointer {
|
||||
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Ptr {
|
||||
return fmt.Errorf("ldap: cannot use %s, expected pointer to a struct", vo)
|
||||
}
|
||||
|
||||
@@ -377,22 +377,6 @@ type SearchResult struct {
|
||||
Referrals []string
|
||||
// Controls are the returned controls
|
||||
Controls []Control
|
||||
// ResultCode is the LDAP resultCode from SearchResultDone (0 = success).
|
||||
// Populated even on success so callers can inspect it alongside DiagnosticMessage.
|
||||
//
|
||||
// Note: for paged searches (SearchWithPaging), appendTo overwrites this field
|
||||
// on each page, so only the last page's ResultCode is preserved.
|
||||
// SearchAsync does not populate this field.
|
||||
ResultCode uint16
|
||||
// DiagnosticMessage is the server's free-text message from SearchResultDone.
|
||||
// Per RFC 4511, this may be set even when resultCode is 0 (success).
|
||||
// GetLDAPError returns nil on success and does not expose this field;
|
||||
// it is preserved here so callers can log or act on it.
|
||||
//
|
||||
// Note: for paged searches (SearchWithPaging), appendTo overwrites this field
|
||||
// on each page, so only the last page's DiagnosticMessage is preserved.
|
||||
// SearchAsync does not populate this field.
|
||||
DiagnosticMessage string
|
||||
}
|
||||
|
||||
// Print outputs a human-readable description
|
||||
@@ -414,8 +398,6 @@ func (s *SearchResult) appendTo(r *SearchResult) {
|
||||
r.Entries = append(r.Entries, s.Entries...)
|
||||
r.Referrals = append(r.Referrals, s.Referrals...)
|
||||
r.Controls = append(r.Controls, s.Controls...)
|
||||
r.ResultCode = s.ResultCode
|
||||
r.DiagnosticMessage = s.DiagnosticMessage
|
||||
}
|
||||
|
||||
// SearchSingleResult holds the server's single entry response to a search request
|
||||
@@ -601,12 +583,7 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
|
||||
return result, err
|
||||
}
|
||||
|
||||
protocolOp, err := packetChild(packet, 1)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
switch protocolOp.Tag {
|
||||
switch packet.Children[1].Tag {
|
||||
case 4:
|
||||
if searchRequest.EnforceSizeLimit &&
|
||||
searchRequest.SizeLimit > 0 &&
|
||||
@@ -614,59 +591,32 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
|
||||
return result, ErrSizeLimitExceeded
|
||||
}
|
||||
|
||||
// RFC 4511 declares SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
|
||||
// objectName LDAPDN, attributes PartialAttributeList }, and
|
||||
// PartialAttributeList is a SEQUENCE OF, so the attributes element
|
||||
// must be present even when it is empty. Both search paths treat a
|
||||
// missing element as malformed.
|
||||
attributesChild, err := packetChild(protocolOp, 1)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
attributes, err := unpackAttributes(attributesChild.Children)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
dn, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return result, err
|
||||
attr := make([]*ber.Packet, 0)
|
||||
if len(packet.Children[1].Children) > 1 {
|
||||
attr = packet.Children[1].Children[1].Children
|
||||
}
|
||||
entry := &Entry{
|
||||
DN: dn,
|
||||
Attributes: attributes,
|
||||
DN: packet.Children[1].Children[0].Value.(string),
|
||||
Attributes: unpackAttributes(attr),
|
||||
}
|
||||
result.Entries = append(result.Entries, entry)
|
||||
case 5:
|
||||
rc, _, diag, parseErr := parseLDAPResult(packet)
|
||||
if parseErr != nil {
|
||||
return result, NewError(ErrorNetwork, fmt.Errorf("malformed SearchResultDone: %w", parseErr))
|
||||
}
|
||||
result.ResultCode = rc
|
||||
result.DiagnosticMessage = diag
|
||||
err := GetLDAPError(packet)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
controlsChild, ok, err := packetChildIfPresent(packet, 2)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if ok {
|
||||
for _, child := range controlsChild.Children {
|
||||
if len(packet.Children) == 3 {
|
||||
for _, child := range packet.Children[2].Children {
|
||||
decodedChild, err := DecodeControl(child)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("failed to decode child control: %w", err)
|
||||
return result, fmt.Errorf("failed to decode child control: %s", err)
|
||||
}
|
||||
result.Controls = append(result.Controls, decodedChild)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
case 19:
|
||||
ref, err := packetStringAt(protocolOp, 0)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Referrals = append(result.Referrals, ref)
|
||||
result.Referrals = append(result.Referrals, packet.Children[1].Children[0].Value.(string))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -703,52 +653,26 @@ func (l *Conn) Syncrepl(
|
||||
|
||||
// unpackAttributes will extract all given LDAP attributes and it's values
|
||||
// from the ber.Packet
|
||||
func unpackAttributes(children []*ber.Packet) ([]*EntryAttribute, error) {
|
||||
entries := make([]*EntryAttribute, 0, len(children))
|
||||
for _, child := range children {
|
||||
// A conforming PartialAttribute is SEQUENCE { type, vals SET OF value }.
|
||||
// A non-conforming or malicious server can omit the vals element or send
|
||||
// a non-string type/value; return an error instead of panicking the
|
||||
// search goroutine, so the caller can handle it.
|
||||
if child == nil {
|
||||
return nil, malformedf("malformed attribute: nil attribute")
|
||||
}
|
||||
nameChild, err := packetChild(child, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: %w", err)
|
||||
}
|
||||
valuesChild, err := packetChild(child, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: %w", err)
|
||||
}
|
||||
name, err := packetString(nameChild)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute: type is not a string: %T: %w", nameChild.Value, err)
|
||||
}
|
||||
values := valuesChild.Children
|
||||
func unpackAttributes(children []*ber.Packet) []*EntryAttribute {
|
||||
entries := make([]*EntryAttribute, len(children))
|
||||
for i, child := range children {
|
||||
length := len(child.Children[1].Children)
|
||||
entry := &EntryAttribute{
|
||||
Name: name,
|
||||
Name: child.Children[0].Value.(string),
|
||||
// pre-allocate the slice since we can determine
|
||||
// the number of attributes at this point
|
||||
Values: make([]string, len(values)),
|
||||
ByteValues: make([][]byte, len(values)),
|
||||
Values: make([]string, length),
|
||||
ByteValues: make([][]byte, length),
|
||||
}
|
||||
|
||||
for i, value := range values {
|
||||
if value == nil {
|
||||
return nil, malformedf("malformed attribute %q: value is nil", name)
|
||||
}
|
||||
v, err := packetString(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ldap: malformed attribute %q: value is not a string: %T: %w", name, value.Value, err)
|
||||
}
|
||||
for i, value := range child.Children[1].Children {
|
||||
entry.ByteValues[i] = value.ByteValue
|
||||
entry.Values[i] = v
|
||||
entry.Values[i] = value.Value.(string)
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
entries[i] = entry
|
||||
}
|
||||
|
||||
return entries, nil
|
||||
return entries
|
||||
}
|
||||
|
||||
// DirSync does a Search with dirSync Control.
|
||||
@@ -793,7 +717,7 @@ func (l *Conn) DirSync(
|
||||
return searchResult, nil
|
||||
}
|
||||
|
||||
// DirSyncAsync performs a search request and returns all search results
|
||||
// DirSyncDirSyncAsync performs a search request and returns all search results
|
||||
// asynchronously. This is efficient when the server returns lots of entries.
|
||||
func (l *Conn) DirSyncAsync(
|
||||
ctx context.Context, searchRequest *SearchRequest, bufferSize int,
|
||||
|
||||
+5
-30
@@ -95,11 +95,6 @@ type advancedState struct {
|
||||
index int
|
||||
hashMatch [maxMatchLength + minMatchLength]uint32
|
||||
|
||||
// litBits[i] is the number of bits needed to encode window[index:i]
|
||||
// as literals, where index is the window index at the start of the
|
||||
// current deflateLazy call. Only allocated when d.chain > 100 (level 9).
|
||||
litBits []int32
|
||||
|
||||
// Input hash chains
|
||||
// hashHead[hashValue] contains the largest inputIndex with the specified hash value
|
||||
// If hashHead[hashValue] is within the current window, then
|
||||
@@ -289,9 +284,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
minIndex := max(pos-windowSize, 0)
|
||||
offset = 0
|
||||
|
||||
// The gain estimate below needs the tables that deflateLazy only
|
||||
// generates when d.chain > 100, so the conditions must match.
|
||||
if d.chain <= 100 {
|
||||
if d.chain < 100 {
|
||||
for i := prevHead; tries > 0; tries-- {
|
||||
if wEnd == win[i+length] {
|
||||
n := matchLen(win[i:i+minMatchLook], wPos)
|
||||
@@ -319,25 +312,21 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
}
|
||||
|
||||
// Minimum gain to accept a match.
|
||||
cGain := int32(4)
|
||||
cGain := 4
|
||||
|
||||
// Some like it higher (CSV), some like it lower (JSON)
|
||||
const baseCost = 3
|
||||
// Base is 4 bytes at with an additional cost.
|
||||
// Matches must be better than this.
|
||||
|
||||
s := d.state
|
||||
hashPrev := &s.hashPrev
|
||||
hashOffset := s.hashOffset
|
||||
litBits := s.litBits[pos : pos+minMatchLook+1]
|
||||
|
||||
for i := prevHead; tries > 0; tries-- {
|
||||
if wEnd == win[i+length] {
|
||||
n := matchLen(win[i:i+minMatchLook], wPos)
|
||||
if n > length {
|
||||
// Calculate gain. Estimate
|
||||
newGain := litBits[n] - litBits[0] - int32(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int32(lengthExtraBits[lengthCodes[(n-3)&255]])
|
||||
newGain := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]])
|
||||
|
||||
//fmt.Println("gain:", newGain, "prev:", cGain, "raw:", d.h.bitLengthRaw(wPos[:n]), "this-len:", n, "prev-len:", length)
|
||||
if newGain > cGain {
|
||||
length = n
|
||||
offset = pos - i
|
||||
@@ -355,7 +344,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
|
||||
// hashPrev[i & windowMask] has already been overwritten, so stop now.
|
||||
break
|
||||
}
|
||||
i = int(hashPrev[i&windowMask]) - hashOffset
|
||||
i = int(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
|
||||
if i < minIndex {
|
||||
break
|
||||
}
|
||||
@@ -439,20 +428,6 @@ func (d *compressor) deflateLazy() {
|
||||
tmp[v]++
|
||||
}
|
||||
d.h.generate(tmp[:], 15)
|
||||
|
||||
// Compute the cumulative cost of encoding the window as literals,
|
||||
// so findMatch can look up the cost of any range in constant time.
|
||||
if s.litBits == nil {
|
||||
s.litBits = make([]int32, 2*windowSize+1)
|
||||
}
|
||||
codes := d.h.codes[:256]
|
||||
litBits := s.litBits[s.index : d.windowEnd+1]
|
||||
total := int32(0)
|
||||
litBits[0] = 0
|
||||
for i, v := range d.window[s.index:d.windowEnd] {
|
||||
total += int32(codes[v].len())
|
||||
litBits[i+1] = total
|
||||
}
|
||||
}
|
||||
|
||||
s.maxInsertIndex = d.windowEnd - (minMatchLength - 1)
|
||||
|
||||
+130
-96
@@ -32,12 +32,14 @@ const (
|
||||
|
||||
// bufferFlushSize indicates the buffer size
|
||||
// after which bytes are flushed to the writer.
|
||||
// Between checks, at most 7 bytes are added to the buffer,
|
||||
// and writes are done as unconditional 8-byte stores, so the
|
||||
// buffer must have at least bufferFlushSize+7+8 bytes.
|
||||
// Should preferably be a multiple of 6, since
|
||||
// we accumulate 6 bytes between writes to the buffer.
|
||||
bufferFlushSize = 246
|
||||
)
|
||||
|
||||
// Minimum length code that emits bits.
|
||||
const lengthExtraBitsMinCode = 8
|
||||
|
||||
// The number of extra bits needed by length code X - LENGTH_CODES_START.
|
||||
var lengthExtraBits = [32]uint8{
|
||||
/* 257 */ 0, 0, 0,
|
||||
@@ -53,6 +55,9 @@ var lengthBase = [32]uint8{
|
||||
64, 80, 96, 112, 128, 160, 192, 224, 255,
|
||||
}
|
||||
|
||||
// Minimum offset code that emits bits.
|
||||
const offsetExtraBitsMinCode = 4
|
||||
|
||||
// offset code word extra bits.
|
||||
var offsetExtraBits = [32]int8{
|
||||
0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
|
||||
@@ -62,24 +67,8 @@ var offsetExtraBits = [32]int8{
|
||||
14, 14,
|
||||
}
|
||||
|
||||
// offsetCombined combines the number of extra bits and the base offset
|
||||
// of each offset code in a single table: extra bits in the low 8 bits,
|
||||
// and the base offset (already reduced by baseMatchOffset) in the upper bits.
|
||||
// Entries for the extended window codes 30 and 31 are unused.
|
||||
var offsetCombined = [32]uint32{}
|
||||
|
||||
// lengthCombined combines, for each match length (reduced by
|
||||
// baseMatchLength), the length code (relative to lengthCodesStart) in
|
||||
// bits 0-4, the number of extra bits in bits 5-7 and the value of the
|
||||
// extra bits in bits 8-12.
|
||||
var lengthCombined = func() (t [256]uint32) {
|
||||
for i := range t {
|
||||
code := lengthCodes[i]
|
||||
t[i] = uint32(code) | uint32(lengthExtraBits[code])<<5 | uint32(uint8(i)-lengthBase[code])<<8
|
||||
}
|
||||
return t
|
||||
}()
|
||||
|
||||
func init() {
|
||||
var offsetBase = [32]uint32{
|
||||
/* normal deflate */
|
||||
@@ -96,7 +85,7 @@ func init() {
|
||||
|
||||
for i := range offsetCombined[:] {
|
||||
// Don't use extended window values...
|
||||
if offsetBase[i] > 0x006000 {
|
||||
if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 {
|
||||
continue
|
||||
}
|
||||
offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8)
|
||||
@@ -126,14 +115,10 @@ type huffmanBitWriter struct {
|
||||
lastHeader int
|
||||
// Set between 0 (reused block can be up to 2x the size)
|
||||
logNewTablePenalty uint
|
||||
|
||||
// bytes must hold at least bufferFlushSize+7+8 bytes (see bufferFlushSize).
|
||||
// Its size is rounded up to a multiple of 8 to keep the following
|
||||
// fields aligned, which is measurably faster in writeBlockHuff.
|
||||
bytes [(bufferFlushSize + 7 + 8 + 7) &^ 7]byte
|
||||
literalFreq [lengthCodesStart + 32]uint16
|
||||
offsetFreq [32]uint16
|
||||
codegenFreq [codegenCodeCount]uint16
|
||||
bytes [256 + 8]byte
|
||||
literalFreq [lengthCodesStart + 32]uint16
|
||||
offsetFreq [32]uint16
|
||||
codegenFreq [codegenCodeCount]uint16
|
||||
|
||||
// codegen must have an extra space for the final symbol.
|
||||
codegen [literalCount + offsetCodeCount + 1]uint8
|
||||
@@ -857,75 +842,124 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode)
|
||||
lengths := leCodes[lengthCodesStart:]
|
||||
lengths = lengths[:32]
|
||||
|
||||
// Keeping these on the stack instead of in w is significantly faster.
|
||||
// Go 1.16 LOVES having these on stack.
|
||||
bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
|
||||
|
||||
// Flush whole bytes, so that nbits <= 7 when entering the loop below.
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
nbytes += nbits >> 3
|
||||
bits >>= nbits & 56
|
||||
nbits &= 7
|
||||
if nbytes >= bufferFlushSize {
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
if w.err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// The loop below flushes whole bytes at the end of every iteration,
|
||||
// so that nbits <= 7 at the top of every iteration.
|
||||
// A literal adds at most 15 bits and a match at most
|
||||
// 15+5+15+13 = 48 bits, so up to three literals or a single match
|
||||
// can be added to the 64-bit accumulator without an intermediate flush.
|
||||
// Unconditionally storing 8 bytes and advancing by the number of
|
||||
// whole bytes avoids a poorly predicted branch per token.
|
||||
for i := 0; i < len(tokens); i++ {
|
||||
t := tokens[i]
|
||||
for _, t := range tokens {
|
||||
if t < 256 {
|
||||
//w.writeCode(lits[t.literal()])
|
||||
c := lits[t]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
// Add up to two more literals before flushing.
|
||||
if i+1 < len(tokens) && tokens[i+1] < 256 {
|
||||
i++
|
||||
c := lits[tokens[i]]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if i+1 < len(tokens) && tokens[i+1] < 256 {
|
||||
i++
|
||||
c := lits[tokens[i]]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Write the length code and its extra bits as one unit.
|
||||
lc := lengthCombined[t.length()]
|
||||
c := lengths[lc&31]
|
||||
bits |= (c.code64() | uint64(lc>>8)<<(c.len()&63)) << (nbits & 63)
|
||||
nbits += c.len() + uint8(lc>>5)&7
|
||||
|
||||
// Write the offset code and its extra bits as one unit.
|
||||
offset := t.offset()
|
||||
offCode := (offset >> 16) & 31
|
||||
c = offs[offCode]
|
||||
offComb := offsetCombined[offCode]
|
||||
extra := (offset - (offComb >> 8)) & matchOffsetOnlyMask
|
||||
bits |= (c.code64() | uint64(extra)<<(c.len()&63)) << (nbits & 63)
|
||||
nbits += c.len() + uint8(offComb)
|
||||
continue
|
||||
}
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
nbytes += nbits >> 3
|
||||
bits >>= nbits & 56
|
||||
nbits &= 7
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
|
||||
// Write the length
|
||||
length := t.length()
|
||||
lengthCode := lengthCode(length) & 31
|
||||
if false {
|
||||
w.writeCode(lengths[lengthCode])
|
||||
} else {
|
||||
// inlined
|
||||
c := lengths[lengthCode]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if lengthCode >= lengthExtraBitsMinCode {
|
||||
extraLengthBits := lengthExtraBits[lengthCode]
|
||||
//w.writeBits(extraLength, extraLengthBits)
|
||||
extraLength := int32(length - lengthBase[lengthCode])
|
||||
bits |= uint64(extraLength) << (nbits & 63)
|
||||
nbits += extraLengthBits
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
// Write the offset
|
||||
offset := t.offset()
|
||||
offsetCode := (offset >> 16) & 31
|
||||
if false {
|
||||
w.writeCode(offs[offsetCode])
|
||||
} else {
|
||||
// inlined
|
||||
c := offs[offsetCode]
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if offsetCode >= offsetExtraBitsMinCode {
|
||||
offsetComb := offsetCombined[offsetCode]
|
||||
//w.writeBits(extraOffset, extraOffsetBits)
|
||||
bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63)
|
||||
nbits += uint8(offsetComb)
|
||||
if nbits >= 48 {
|
||||
le.Store64(w.bytes[:], nbytes, bits)
|
||||
bits >>= 48
|
||||
nbits -= 48
|
||||
nbytes += 6
|
||||
if nbytes >= bufferFlushSize {
|
||||
if w.err != nil {
|
||||
nbytes = 0
|
||||
return
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
}
|
||||
// Restore...
|
||||
@@ -1060,8 +1094,8 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
|
||||
if debugDeflate {
|
||||
count -= int(nbytes)*8 + int(nbits)
|
||||
}
|
||||
// Write 3 codes per iteration. The three codes are combined first,
|
||||
// independently of the accumulator, and merged with a single shift.
|
||||
// Unroll, write 3 codes/loop.
|
||||
// Fastest number of unrolls.
|
||||
for len(input) > 3 {
|
||||
// We must have at least 48 bits free.
|
||||
if nbits >= 8 {
|
||||
@@ -1082,13 +1116,13 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
|
||||
_, w.err = w.writer.Write(w.bytes[:nbytes])
|
||||
nbytes = 0
|
||||
}
|
||||
a, b, c := encoding[input[0]], encoding[input[1]], encoding[input[2]]
|
||||
v := a.code64() | b.code64()<<(a.len()&63)
|
||||
n := a.len() + b.len()
|
||||
v |= c.code64() << (n & 63)
|
||||
n += c.len()
|
||||
bits |= v << (nbits & 63)
|
||||
nbits += n
|
||||
a, b := encoding[input[0]], encoding[input[1]]
|
||||
bits |= a.code64() << (nbits & 63)
|
||||
bits |= b.code64() << ((nbits + a.len()) & 63)
|
||||
c := encoding[input[2]]
|
||||
nbits += b.len() + a.len()
|
||||
bits |= c.code64() << (nbits & 63)
|
||||
nbits += c.len()
|
||||
input = input[3:]
|
||||
}
|
||||
|
||||
|
||||
+36
-102
@@ -38,9 +38,6 @@ type huffmanEncoder struct {
|
||||
// Possible lengths are codegenCodeCount, offsetCodeCount and literalCount.
|
||||
// The largest of these is literalCount, so we allocate for that case.
|
||||
freqcache [literalCount + 1]literalNode
|
||||
|
||||
// sortcache is scratch space for sortByFreq.
|
||||
sortcache [literalCount + 1]literalNode
|
||||
}
|
||||
|
||||
type literalNode struct {
|
||||
@@ -142,6 +139,14 @@ func (h *huffmanEncoder) bitLength(freq []uint16) int {
|
||||
return total
|
||||
}
|
||||
|
||||
func (h *huffmanEncoder) bitLengthRaw(b []byte) int {
|
||||
var total int
|
||||
for _, f := range b {
|
||||
total += int(h.codes[f].len())
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// canReuseBits returns the number of bits or math.MaxInt32 if the encoder cannot be reused.
|
||||
func (h *huffmanEncoder) canReuseBits(freq []uint16) int {
|
||||
var total int
|
||||
@@ -304,93 +309,27 @@ func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 {
|
||||
}
|
||||
|
||||
// Look at the leaves and assign them a bit count and an encoding as specified
|
||||
// in RFC 1951 3.2.2.
|
||||
// list must be sorted by increasing frequency and codes must have
|
||||
// all entries for literals not in list set to zero.
|
||||
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode, codes []hcode) {
|
||||
// The literals list[len(list)-bits] .. list[len(list)-1]
|
||||
// are encoded using "bits" bits. Record the length of each literal
|
||||
// temporarily in codes.
|
||||
// in RFC 1951 3.2.2
|
||||
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
|
||||
code := uint16(0)
|
||||
for n, bits := range bitCount {
|
||||
code <<= 1
|
||||
if n == 0 || bits == 0 {
|
||||
continue
|
||||
}
|
||||
for _, node := range list[len(list)-int(bits):] {
|
||||
codes[node.literal] = hcode(n)
|
||||
// The literals list[len(list)-bits] .. list[len(list)-bits]
|
||||
// are encoded using "bits" bits, and get the values
|
||||
// code, code + 1, .... The code values are
|
||||
// assigned in literal order (not frequency order).
|
||||
chunk := list[len(list)-int(bits):]
|
||||
|
||||
sortByLiteral(chunk)
|
||||
for _, node := range chunk {
|
||||
h.codes[node.literal] = newhcode(reverseBits(code, uint8(n)), uint8(n))
|
||||
code++
|
||||
}
|
||||
list = list[0 : len(list)-int(bits)]
|
||||
}
|
||||
|
||||
// Code values are assigned in literal order (not frequency order)
|
||||
// within each code length, starting from the first code of each length.
|
||||
var nextCode [maxBitsLimit]uint16
|
||||
code := uint16(0)
|
||||
for n := 1; n < len(bitCount); n++ {
|
||||
code = (code + uint16(bitCount[n-1])) << 1
|
||||
nextCode[n] = code
|
||||
}
|
||||
for i, c := range codes {
|
||||
if c == 0 {
|
||||
continue
|
||||
}
|
||||
// n is at most maxBitsLimit-1; the mask only elides bounds checks.
|
||||
n := uint8(c)
|
||||
codes[i] = newhcode(reverseBits(nextCode[n&15], n), n)
|
||||
nextCode[n&15]++
|
||||
}
|
||||
}
|
||||
|
||||
// sortByFreq sorts list by increasing frequency.
|
||||
// The sort is stable, so nodes with equal frequencies keep their order.
|
||||
func (h *huffmanEncoder) sortByFreq(list []literalNode) {
|
||||
if len(list) <= 32 {
|
||||
// Insertion sort is faster for small lists.
|
||||
for i := 1; i < len(list); i++ {
|
||||
n := list[i]
|
||||
j := i
|
||||
for ; j > 0 && list[j-1].freq > n.freq; j-- {
|
||||
list[j] = list[j-1]
|
||||
}
|
||||
list[j] = n
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Counting sort on the low byte and then on the high byte
|
||||
// of the frequency. Both passes are stable.
|
||||
tmp := h.sortcache[:len(list)]
|
||||
var count [256]uint16
|
||||
var maxFreq uint16
|
||||
for _, n := range list {
|
||||
count[n.freq&0xff]++
|
||||
maxFreq |= n.freq
|
||||
}
|
||||
var pos uint16
|
||||
for i, c := range count {
|
||||
count[i] = pos
|
||||
pos += c
|
||||
}
|
||||
for _, n := range list {
|
||||
tmp[count[n.freq&0xff]] = n
|
||||
count[n.freq&0xff]++
|
||||
}
|
||||
if maxFreq < 256 {
|
||||
copy(list, tmp)
|
||||
return
|
||||
}
|
||||
count = [256]uint16{}
|
||||
for _, n := range tmp {
|
||||
count[n.freq>>8]++
|
||||
}
|
||||
pos = 0
|
||||
for i, c := range count {
|
||||
count[i] = pos
|
||||
pos += c
|
||||
}
|
||||
for _, n := range tmp {
|
||||
list[count[n.freq>>8]] = n
|
||||
count[n.freq>>8]++
|
||||
}
|
||||
}
|
||||
|
||||
// Update this Huffman Code object to be the minimum code for the specified frequency count.
|
||||
@@ -423,14 +362,12 @@ func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) {
|
||||
}
|
||||
return
|
||||
}
|
||||
// list is in order of increasing literal value, so a stable sort
|
||||
// by frequency orders it by (frequency, literal).
|
||||
h.sortByFreq(list)
|
||||
sortByFreq(list)
|
||||
|
||||
// Get the number of literals for each bit count
|
||||
bitCount := h.bitCounts(list, maxBits)
|
||||
// And do the assignment
|
||||
h.assignEncodingAndSize(bitCount, list, codes)
|
||||
h.assignEncodingAndSize(bitCount, list)
|
||||
}
|
||||
|
||||
// atLeastOne clamps the result between 1 and 15.
|
||||
@@ -457,27 +394,24 @@ func histogram(b []byte, h []uint16) {
|
||||
}
|
||||
|
||||
func histogramSplit(b []byte, h []uint16) {
|
||||
// Walk four quarters in parallel, each into its own table.
|
||||
// Tested to be faster than walking halves. Using separate tables
|
||||
// avoids the load/store dependencies that arise when two of the
|
||||
// streams hit the same byte value, which is common for text.
|
||||
var h0, h1, h2, h3 [256]uint16
|
||||
// Make size divisible by 4
|
||||
// Tested, and slightly faster than 2-way.
|
||||
// Writing to separate arrays and combining is also slightly slower.
|
||||
h = h[:256]
|
||||
for len(b)&3 != 0 {
|
||||
h0[b[0]]++
|
||||
h[b[0]]++
|
||||
b = b[1:]
|
||||
}
|
||||
n := len(b) / 4
|
||||
x, y, z, w := b[:n], b[n:], b[n+n:], b[n+n+n:]
|
||||
y, z, w = y[:len(x)], z[:len(x)], w[:len(x)]
|
||||
for i, t := range x {
|
||||
h0[t]++
|
||||
h1[y[i]]++
|
||||
h2[z[i]]++
|
||||
h3[w[i]]++
|
||||
}
|
||||
h = h[:256]
|
||||
for i := range h {
|
||||
h[i] += h0[i] + h1[i] + h2[i] + h3[i]
|
||||
v0 := &h[t]
|
||||
v1 := &h[y[i]]
|
||||
v2 := &h[z[i]]
|
||||
v3 := &h[w[i]]
|
||||
*v0++
|
||||
*v1++
|
||||
*v2++
|
||||
*v3++
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
// 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
@@ -0,0 +1,201 @@
|
||||
// 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]
|
||||
}
|
||||
+15
-15
@@ -120,7 +120,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -148,7 +148,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -216,7 +216,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -371,7 +371,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -399,7 +399,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -467,7 +467,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -638,7 +638,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -674,7 +674,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -757,7 +757,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -918,7 +918,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -946,7 +946,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1014,7 +1014,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1169,7 +1169,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits n>0:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1197,7 +1197,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<5:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
@@ -1265,7 +1265,7 @@ readLiteral:
|
||||
if debugDecode {
|
||||
fmt.Println("morebits f.nb<nb:", err)
|
||||
}
|
||||
f.err = noEOF(err)
|
||||
f.err = err
|
||||
return
|
||||
}
|
||||
f.roffset++
|
||||
|
||||
+7
-6
@@ -12,17 +12,18 @@ import (
|
||||
// matchLen returns the maximum common prefix length of a and b.
|
||||
// a must be the shortest of the two.
|
||||
func matchLen(a, b []byte) (n int) {
|
||||
// Keeping a and b the same length and reslicing them as we go
|
||||
// lets the compiler prove that no bounds checks are needed.
|
||||
b = b[:len(a)]
|
||||
for len(a) >= 8 {
|
||||
diff := le.Load64(a, 0) ^ le.Load64(b, 0)
|
||||
left := len(a)
|
||||
for left >= 8 {
|
||||
diff := le.Load64(a, n) ^ le.Load64(b, n)
|
||||
if diff != 0 {
|
||||
return n + bits.TrailingZeros64(diff)>>3
|
||||
}
|
||||
a, b = a[8:], b[8:]
|
||||
n += 8
|
||||
left -= 8
|
||||
}
|
||||
|
||||
a = a[n:]
|
||||
b = b[n:]
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
break
|
||||
|
||||
+7
-11
@@ -215,11 +215,7 @@ func mFastLog2(val float32) float32 {
|
||||
ux &= -0x7f800001
|
||||
ux += 127 << 23
|
||||
uval := math.Float32frombits(uint32(ux))
|
||||
|
||||
p := float32(-0.34484843*uval) + 2.02466578
|
||||
q := float32(p*uval) - 0.67487759
|
||||
log2 += q
|
||||
|
||||
log2 += ((-0.34484843)*uval+2.02466578)*uval - 0.67487759
|
||||
return log2
|
||||
}
|
||||
|
||||
@@ -236,8 +232,7 @@ func (t *tokens) EstimatedBits() int {
|
||||
for _, v := range t.litHist[:] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
}
|
||||
}
|
||||
// Just add 15 for EOB
|
||||
@@ -245,8 +240,7 @@ func (t *tokens) EstimatedBits() int {
|
||||
for i, v := range t.extraHist[1 : literalCount-256] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
bits += int(lengthExtraBits[i&31]) * int(v)
|
||||
nMatches += int(v)
|
||||
}
|
||||
@@ -257,8 +251,7 @@ func (t *tokens) EstimatedBits() int {
|
||||
for i, v := range t.offHist[:offsetCodeCount] {
|
||||
if v > 0 {
|
||||
n := float32(v)
|
||||
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
|
||||
shannon += w
|
||||
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
|
||||
bits += int(offsetExtraBits[i&31]) * int(v)
|
||||
}
|
||||
}
|
||||
@@ -365,6 +358,9 @@ func (t token) offset() uint32 { return uint32(t) & offsetMask }
|
||||
|
||||
func (t token) length() uint8 { return uint8(t >> lengthShift) }
|
||||
|
||||
// Convert length to code.
|
||||
func lengthCode(len uint8) uint8 { return lengthCodes[len] }
|
||||
|
||||
// Returns the offset code corresponding to a specific offset
|
||||
func offsetCode(off uint32) uint32 {
|
||||
if false {
|
||||
|
||||
-63
@@ -9,7 +9,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/bits"
|
||||
|
||||
"github.com/klauspost/compress/internal/le"
|
||||
)
|
||||
@@ -211,68 +210,6 @@ func (b *bitReaderShifted) remaining() uint {
|
||||
return b.off*8 + uint(64-b.bitsRead)
|
||||
}
|
||||
|
||||
// canUseAsm reports whether the reader has a full 8-byte window ahead of
|
||||
// its read pointer, which the Decompress4X asm loops need to take over.
|
||||
func (b *bitReaderShifted) canUseAsm() bool {
|
||||
return b.off >= 8
|
||||
}
|
||||
|
||||
// prepareForAsm establishes the invariant the Decompress4X asm loops rely
|
||||
// on: value == load64(in[off:off+8]) << bitsRead with bitsRead <= 7, so
|
||||
// that a full group of symbols can never shift their sentinel bit out of
|
||||
// the container. init leaves bitsRead == 8 when the final byte of the
|
||||
// stream is exactly 0x01; that whole byte is consumed, so the same position
|
||||
// is the window one byte lower with nothing consumed. Requires canUseAsm.
|
||||
func (b *bitReaderShifted) prepareForAsm() {
|
||||
if b.bitsRead >= 8 {
|
||||
b.off--
|
||||
b.value = le.Load64(b.in, b.off)
|
||||
b.bitsRead -= 8
|
||||
}
|
||||
}
|
||||
|
||||
// restoreFromAsm converts the state left behind by the Decompress4X asm
|
||||
// loops back to the invariant the Go code relies on: value holds the 8
|
||||
// bytes at in[off:off+8] shifted left by bitsRead, with the low bitsRead
|
||||
// bits zero.
|
||||
//
|
||||
// The asm keeps a sentinel bit in value just below the unread bits, so its
|
||||
// trailing zero count is the number of consumed bits. The sentinel is ORed
|
||||
// over the lowest bit of the window, which the loop never consumes before
|
||||
// re-reading memory, so the window is re-read here too rather than taken
|
||||
// from value. The asm reports off as the signed distance from the start of
|
||||
// the stream, and it can be negative: a reload always reads a whole 8-byte
|
||||
// window, so a stream that is nearly drained ends with up to 7 bytes of the
|
||||
// previous stream (or the jump table) below its start inside the window.
|
||||
// Those bytes sit below the stream's own bits and count as consumed.
|
||||
// Anything further below, or more bits consumed than the stream holds, is
|
||||
// corruption.
|
||||
func (b *bitReaderShifted) restoreFromAsm() error {
|
||||
off := int(b.off)
|
||||
consumed := uint(bits.TrailingZeros64(b.value))
|
||||
if off < 0 {
|
||||
if off < -7 {
|
||||
return errors.New("corruption detected: stream underrun")
|
||||
}
|
||||
consumed += uint(-off) * 8
|
||||
if consumed > 64 {
|
||||
return errors.New("corruption detected: stream underrun")
|
||||
}
|
||||
off = 0
|
||||
}
|
||||
if off+8 > len(b.in) {
|
||||
return errors.New("corruption detected: stream overrun")
|
||||
}
|
||||
b.off = uint(off)
|
||||
b.bitsRead = uint8(consumed)
|
||||
if consumed >= 64 {
|
||||
b.value = 0
|
||||
} else {
|
||||
b.value = le.Load64(b.in, b.off) << consumed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// close the bitstream and returns an error if out-of-buffer reads occurred.
|
||||
func (b *bitReaderShifted) close() error {
|
||||
// Release reference.
|
||||
|
||||
+8
-87
@@ -8,99 +8,36 @@ import (
|
||||
)
|
||||
|
||||
// decompress4x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
|
||||
// stream between bit container reloads.
|
||||
// of Decompress4X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_bmi2 is the BMI2 twin of decompress4x_4b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_main_loop_bmi2 is the BMI2 twin of decompress4x_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_bmi2 is the BMI2 twin of decompress4x_8b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_bmi2(ctx *decompress4xContext)
|
||||
|
||||
// decompress1x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
|
||||
// between bit container reloads.
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_8b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_main_loop_bmi2 is the BMI2 twin of decompress1x_main_loop_amd64.
|
||||
// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_8b_main_loop_bmi2 is the BMI2 twin of decompress1x_8b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_bmi2 is the BMI2 twin of decompress1x_4b_main_loop_amd64.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_main_loop_amd64(ctx)
|
||||
}
|
||||
decompress4x_main_loop_amd64(ctx)
|
||||
}
|
||||
|
||||
func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_8b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress4x_4b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress4x_4b_main_loop_amd64(ctx)
|
||||
}
|
||||
decompress4x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
@@ -110,19 +47,3 @@ func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_8b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress1x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_4b_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress1x_4b_main_loop_amd64(ctx)
|
||||
}
|
||||
}
|
||||
+753
-3309
File diff suppressed because it is too large.
Load diff
+4
-39
@@ -6,47 +6,24 @@
|
||||
package huff0
|
||||
|
||||
// decompress4x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
|
||||
// stream between bit container reloads.
|
||||
// of Decompress4X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_4b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// per stream between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_4b_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress1x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
|
||||
// between bit container reloads.
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_8b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog <= 8, decoding fast8bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_8b_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
// decompress1x_4b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog <= 4, decoding fast4bSymbols symbols
|
||||
// between bit container reloads.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_4b_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_main_loop_arm64(ctx)
|
||||
}
|
||||
@@ -55,18 +32,6 @@ func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_8b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress4x_4b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_4b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_8b_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_8b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_4b_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_4b_main_loop_arm64(ctx)
|
||||
}
|
||||
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user