Compare commits

...
Author SHA1 Message Date
Lukas Hirt 14ca73fa83 feat: [OCISDEV-1061] add llm proxy service
Add a new llm service that proxies chat-completion requests from AI web extensions to a configured OpenAI-compatible endpoint, replacing the standalone Node.js sidecar. It is part of the oCIS single binary, opt-in via OCIS_ADD_RUN_SERVICES=llm, and exposed through the proxy at POST /graph/v1beta1/extensions/org.libregraph/llm/chat/completions.

Authentication is delegated to oCIS. Requests are rate-limited per user with a sliding window backed by the shared store, and the request body is sanitized before forwarding. Streaming requests are rejected.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-10-15 14:31:07 +02:00
Roman Perekhod e76dc49698 fix: [OCISDEV-1502] The global variable OCIS_CACHE_DATABASE was replaced (#13158) 2026-10-15 13:29:49 +02:00
Pradip Subedi c17c33b6d8 [full-ci][tests-only] test: fix flaky cliCommands tests (#13133)
* test: fix flaky blobstore test

* test: fix flaky backupconsistency test
2026-10-15 14:03:05 +05:45
owncloud-translations-bot[bot] 66e93ceaf3 chore: update translations from transifex (#13143)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-15 07:28:51 +00:00
Matteo fba139fdec fix(web): [OCISDEV-1543] show details preview for public link files with spaces in the name (#13150) 2026-10-14 14:03:08 +02:00
Lukas Hirt e0dd0e4348 fix(web): [OCISDEV-1527] disable vertical page overscroll in file apps (#13140)
Scrolling inside an app such as OnlyOffice could make the whole page bounce
with it, exposing the blank page background behind the app frame. Set
overscroll-behavior-y: none on the root element while AppWrapper is mounted
and restore the previous value on unmount. The logic lives in a new
useDisableRootOverscroll composable, which is covered by unit tests.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-10-13 21:18:12 +02:00
Matteo 710bdf380a fix(web): [OCISDEV-1513] clean up trash view in the Safe (#13136) 2026-10-13 15:42:01 +02:00
Michal Klos 7b83f36060 fix(proxy): [OCISDEV-1517] add missing /vault/graph routes for activities and invitations (#13109) 2026-10-13 13:15:20 +00:00
Michal Klos 2a23956a8b fix(web): [OCISDEV-1518] show correct message when Safe access is denied for lacking permission (#13111)
* fix(web): [OCISDEV-1518] show correct message when Safe access is denied for lacking permission

* chore: changelog
2026-10-13 11:29:58 +00:00
Prajwol Amatya 9269643c0e [tests-only][full-ci][k8s] test: run e2e app-provider with k8s setup (#13046)
* test: run e2e app-provider with k8s setup

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

* test: limit app-registry mimetypes

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

* test: add host for onlyoffice

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

* test: enable secure view

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

* test: add available unified roles

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

---------

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-10-13 16:23:20 +05:45
Matteo 6c8fe4ebf7 fix(web): [OCISDEV-1511] refresh files stuck in processing after upload or copy (#13134)
* fix(web): [OCISDEV-1511] refresh files stuck in processing after upload or copy

A postprocessing-finished event that arrives while a folder reload or a
fetch after copy is still in flight is dropped, because the resource is
not in the store yet. The response then adds the resource as processing
and nothing clears it until a page reload.

Remember finished items for a short time and refetch them when they show
up in the store as processing.

* chore: [OCISDEV-1511] add changelog
2026-10-13 12:22:01 +02:00
kobergjandClaude Opus 5 037ac76d26 ci(release): remove the disabled docker jobs from the release pipeline (#13129)
ci(release): remove the disabled docker jobs from the release pipeline (#13128)

Tagging v9.0.0-rc.1 produced a startup_failure: the workflow was rejected
before any job ran. owncloud pins Actions to an org allowlist
(owncloud/admin:actions-allowlist.yml, allowed_actions: selected with
sha_pinning_required), and three pins in this file are not on it:

  docker/setup-buildx-action @f87e5991 v4.4.1 (allowlist has v4.0.0)
  docker/login-action        @dbcb8138 v4.6.0 (allowlist has v4.1.0)
  docker/build-push-action   @c3c9e263 v7.4.0 (allowlist has v7.0.0)

Allowlist validation happens at parse time, so it does not care that all
three only appear in jobs already marked `if: false`.

Rather than pin them back, drop the jobs. Building, scanning and publishing
the production image moved to owncloud-docker/ocis, which is why these were
disabled in the first place; the image Trivy scan now runs there on every PR.
That leaves nothing to maintain here and removes all three offending pins.

Removes docker-build, docker-scan (dead too: it needs docker-build),
docker-manifest and docker-readme. Nothing outside that subgraph depended on
them, so the `docker_repos` and `is_production` outputs, the
PRODUCTION_RELEASE_TAGS / DOCKER_REPO_ROLLING / DOCKER_REPO_PRODUCTION env
vars and the REPOS computation go with them. is_prerelease stays, as
create-github-release still reads it.

The filesystem scan in security-scan-trivy is untouched.



(cherry picked from commit aab12d018e)

Signed-off-by: Julian Koberg <julian.koberg@kiteworks.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-13 09:12:10 +02:00
owncloud-translations-bot[bot] 9faaefa83a chore: update translations from transifex (#13130)
Co-authored-by: owncloud-translations-bot[bot] <274778013+owncloud-translations-bot[bot]@users.noreply.github.com>
2026-10-13 07:11:18 +00:00
Prajwol Amatya 85700efcd1 [tests-ony][full-ci][k8s] test: update storageusersvault setup for k8s (#13131)
test: update storageusersvault settings for k8s

Signed-off-by: Prajwol Amatya <prajwolamatya11@gmail.com>
2026-10-13 10:52:53 +05:45
dependabot[bot] 91a8c76bdb build(deps): bump actions/setup-node from 6.4.0 to 7.1.0 (#13118)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 6.4.0 to 7.1.0.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v6.4.0...949feb2413d6458794dcd2491c4babbbce0c15c1)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 19:44:39 +02:00
dependabot[bot] 88e2780a54 build(deps): bump actions/upload-artifact from 4.6.2 to 7.0.2 (#13117)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4.6.2 to 7.0.2.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4.6.2...cf430e030ddbb5b0abf93d22962f4752f3646cd9)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: 7.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 16:22:42 +02:00
dependabot[bot] 60fcb2e214 build(deps): bump actions/download-artifact from 4.3.0 to 8.0.2 (#13119)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4.3.0 to 8.0.2.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4.3.0...9000827ccba6bdab643e8b6fd33ac0654aef8333)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: 8.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 16:22:20 +02:00
dependabot[bot] c8224fd434 build(deps): bump the minor-and-patch group across 1 directory with 7 updates (#13126)
Bumps the minor-and-patch group with 7 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [github.com/go-chi/httprate](https://github.com/go-chi/httprate) | `0.16.0` | `0.16.1` |
| [github.com/go-ldap/ldap/v3](https://github.com/go-ldap/ldap) | `3.4.14` | `3.4.15` |
| [github.com/nats-io/nats-server/v2](https://github.com/nats-io/nats-server) | `2.15.0` | `2.15.1` |
| [github.com/prometheus/client_golang](https://github.com/prometheus/client_golang) | `1.24.1` | `1.25.0` |
| [github.com/tidwall/gjson](https://github.com/tidwall/gjson) | `1.19.1` | `1.20.0` |
| [go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp](https://github.com/open-telemetry/opentelemetry-go-contrib) | `0.71.0` | `0.72.0` |
| [golang.org/x/sync](https://github.com/golang/sync) | `0.23.0` | `0.24.0` |



Updates `github.com/go-chi/httprate` from 0.16.0 to 0.16.1
- [Release notes](https://github.com/go-chi/httprate/releases)
- [Commits](https://github.com/go-chi/httprate/compare/v0.16.0...v0.16.1)

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

Updates `github.com/nats-io/nats-server/v2` from 2.15.0 to 2.15.1
- [Release notes](https://github.com/nats-io/nats-server/releases)
- [Changelog](https://github.com/nats-io/nats-server/blob/main/RELEASES.md)
- [Commits](https://github.com/nats-io/nats-server/compare/v2.15.0...v2.15.1)

Updates `github.com/prometheus/client_golang` from 1.24.1 to 1.25.0
- [Release notes](https://github.com/prometheus/client_golang/releases)
- [Changelog](https://github.com/prometheus/client_golang/blob/v1.25.0/CHANGELOG.md)
- [Commits](https://github.com/prometheus/client_golang/compare/v1.24.1...v1.25.0)

Updates `github.com/tidwall/gjson` from 1.19.1 to 1.20.0
- [Commits](https://github.com/tidwall/gjson/compare/v1.19.1...v1.20.0)

Updates `go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp` from 0.71.0 to 0.72.0
- [Release notes](https://github.com/open-telemetry/opentelemetry-go-contrib/releases)
- [Changelog](https://github.com/open-telemetry/opentelemetry-go-contrib/blob/main/CHANGELOG.md)
- [Commits](https://github.com/open-telemetry/opentelemetry-go-contrib/compare/zpages/v0.71.0...zpages/v0.72.0)

Updates `golang.org/x/sync` from 0.23.0 to 0.24.0
- [Commits](https://github.com/golang/sync/compare/v0.23.0...v0.24.0)

---
updated-dependencies:
- dependency-name: github.com/go-chi/httprate
  dependency-version: 0.16.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/go-ldap/ldap/v3
  dependency-version: 3.4.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/nats-io/nats-server/v2
  dependency-version: 2.15.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: minor-and-patch
- dependency-name: github.com/prometheus/client_golang
  dependency-version: 1.25.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: github.com/tidwall/gjson
  dependency-version: 1.20.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
  dependency-version: 0.72.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
- dependency-name: golang.org/x/sync
  dependency-version: 0.24.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-12 16:13:34 +02:00
263 changed files with 16819 additions and 5876 deletions

No files matched your search

+21 -21
View File
@@ -62,7 +62,7 @@ jobs:
go-version-file: go.mod
cache: true
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
@@ -165,7 +165,7 @@ jobs:
exit $FAILED
- name: Upload build artifacts
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ocis-build-artifacts
path: |
@@ -280,7 +280,7 @@ jobs:
'
- name: Download build artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -294,7 +294,7 @@ jobs:
- name: Upload raw coverage data
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: api-coverage-${{ matrix.suite }}
path: ${{ env.GOCOVERDIR }}
@@ -328,7 +328,7 @@ jobs:
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
- name: Download build artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -342,7 +342,7 @@ jobs:
- name: Upload raw coverage data
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: api-coverage-cli-${{ matrix.suite }}
path: ${{ env.GOCOVERDIR }}
@@ -376,7 +376,7 @@ jobs:
sudo NEEDRESTART_MODE=a apt-get install -y libvips42t64
- name: Download build artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -390,7 +390,7 @@ jobs:
- name: Upload raw coverage data
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: api-coverage-ldap-pool-${{ matrix.suite }}
path: ${{ env.GOCOVERDIR }}
@@ -468,7 +468,7 @@ jobs:
'
- name: Download build artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -485,7 +485,7 @@ jobs:
- name: Upload raw coverage data
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.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@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -683,7 +683,7 @@ jobs:
- name: Upload tracing result
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
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@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: ocis-build-artifacts
@@ -809,7 +809,7 @@ jobs:
go-version-file: go.mod
cache: true
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
@@ -842,7 +842,7 @@ jobs:
go-version-file: go.mod
cache: true
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: "24"
@@ -876,7 +876,7 @@ jobs:
cache: true
- name: Download raw coverage data
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: api-coverage-*
path: ${{ env.GOCOVERDIR }}
+78 -7
View File
@@ -482,9 +482,9 @@ jobs:
# - 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: app-provider
args: "--type playwright --suites app-provider"
collaboration: true
# - suite: ocm
# args: "--type playwright --suites ocm"
# federated: true
@@ -497,7 +497,7 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Setup Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.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,14 +540,84 @@ jobs:
run: make -C tests/config/k8s create-cluster
- name: Prepare Helm Charts
env:
ENABLE_WOPI: ${{ matrix.suite == 'app-provider' }}
run: make -C tests/config/k8s prepare-charts
- 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
- name: Deploy oCIS
run: |
cd tests/config/k8s
kubectl get pods -n "$TEST_SERVER_DOMAIN" -Aw &
make deploy-ocis
- 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:
FILE_URL: ${{ env.TEST_SERVER_URL }}/remote.php/dav/files/admin/hello1.txt
@@ -618,11 +688,12 @@ jobs:
E2E_ARGS: "${{ matrix.args }}"
K8S: ${{ env.K8S }}
TEST_SERVER_URL: ${{ env.TEST_SERVER_URL }}
COLLABORATION_NEEDED: ${{ matrix.collaboration == true && 'true' || 'false' }}
run: python3 tests/acceptance/run-e2e.py
- name: Upload Playwright traces
if: failure()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: playwright-traces-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
path: web/reports/e2e
@@ -630,7 +701,7 @@ jobs:
- name: Upload a11y result
if: ${{ !cancelled() }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: playwright-a11y-result-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
path: web/reports/e2e/a11y-report.json
@@ -638,7 +709,7 @@ jobs:
- name: Upload oCIS logs
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ocis-logs-${{ matrix.suite }}-k8s-${{ github.run_attempt }}
path: tests/config/k8s/logs
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24.15.0
registry-url: "https://registry.npmjs.org"
+15 -186
View File
@@ -14,9 +14,6 @@ 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'
@@ -27,9 +24,7 @@ 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 == '') }}
@@ -75,23 +70,10 @@ 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
@@ -102,7 +84,7 @@ jobs:
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- run: npm install --silent -g yarn npx --force
@@ -119,7 +101,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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: generated-code
path: |
@@ -128,159 +110,6 @@ 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
@@ -291,7 +120,7 @@ jobs:
os: [linux, darwin]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: generated-code
path: .
@@ -304,7 +133,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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: binaries-${{ matrix.os }}
path: ocis/dist/release/*
@@ -329,11 +158,11 @@ jobs:
needs: [determine-release-type, generate-code]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: generated-code
path: .
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ env.NODE_VERSION }}
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -347,7 +176,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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: third-party-licenses
path: third-party-licenses.tar.gz
@@ -371,7 +200,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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: changelog
path: ocis/dist/CHANGELOG.md
@@ -382,19 +211,19 @@ jobs:
timeout-minutes: 30
needs: [determine-release-type, build-binaries, license-check, generate-changelog, security-scan-trivy]
steps:
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: binaries-linux
path: release-assets
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: binaries-darwin
path: release-assets
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: third-party-licenses
path: release-assets
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: changelog
path: .
@@ -419,15 +248,15 @@ jobs:
- create-github-release
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: binaries-linux
path: release-assets
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: binaries-darwin
path: release-assets
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: third-party-licenses
path: release-assets
+1 -1
View File
@@ -77,7 +77,7 @@ jobs:
version: 10.33.3
- name: Setup Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24.15.0
cache: pnpm
+1
View File
@@ -41,6 +41,7 @@ OCIS_MODULES = \
services/idm \
services/idp \
services/invitations \
services/llm \
services/nats \
services/notifications \
services/ocdav \
@@ -0,0 +1,9 @@
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
@@ -0,0 +1,10 @@
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
@@ -0,0 +1,11 @@
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
@@ -0,0 +1,10 @@
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
@@ -0,0 +1,8 @@
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
@@ -0,0 +1,13 @@
Enhancement: Add LLM proxy service
oCIS now ships a native `llm` microservice, as part of the single binary,
that proxies chat-completion requests from AI web extensions to a
configured OpenAI-compatible LLM endpoint, so AI-enabled oCIS deployments
no longer need a separate process or image.
The service trusts oCIS's existing authentication (no independent OIDC
validation), rate-limits requests per user using oCIS's shared store
abstraction (shared across multiple replicas), and forwards a sanitized
request body — only the fields the LLM needs are passed through.
https://github.com/owncloud/ocis/pull/12965
@@ -0,0 +1,14 @@
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
+10 -10
View File
@@ -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.0
github.com/go-chi/httprate v0.16.1
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.14
github.com/go-ldap/ldap/v3 v3.4.15
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.0
github.com/nats-io/nats-server/v2 v2.15.1
github.com/nats-io/nats.go v1.54.0
github.com/olekukonko/tablewriter v1.1.5
github.com/onsi/ginkgo v1.16.5
@@ -70,7 +70,7 @@ require (
github.com/owncloud/reva/v2 v2.0.0-20261012083840-8b649a4c3899
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.24.1
github.com/prometheus/client_golang v1.25.0
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.19.1
github.com/tidwall/gjson v1.20.0
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.71.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.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
@@ -102,7 +102,7 @@ require (
golang.org/x/image v0.46.0
golang.org/x/net v0.60.0
golang.org/x/oauth2 v0.37.0
golang.org/x/sync v0.23.0
golang.org/x/sync v0.24.0
golang.org/x/term v0.46.0
golang.org/x/text v0.42.0
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
@@ -238,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.0 // indirect
github.com/klauspost/compress v1.20.1 // 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
@@ -292,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.70.1 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/prometheus/common v0.72.0 // indirect
github.com/prometheus/procfs v0.22.0 // 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
+20 -20
View File
@@ -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.0 h1:8V5DH9j6pSK6UQoBsTpvMyFxycqaKEIToyPKzHJjUa8=
github.com/go-chi/httprate v0.16.0/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
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.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
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/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.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA=
github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/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.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-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.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=
@@ -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.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
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_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.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
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.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
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/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.19.1 h1:uKxUTe/+mtjSY3Sf1EIND83MyH+jWf1SixZ7DHpjbJU=
github.com/tidwall/gjson v1.19.1/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
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/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.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/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/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=
@@ -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.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.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=
+2
View File
@@ -22,6 +22,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/config"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config"
@@ -103,6 +104,7 @@ type Config struct {
IDM *idm.Config `yaml:"idm"`
IDP *idp.Config `yaml:"idp"`
Invitations *invitations.Config `yaml:"invitations"`
LLM *llm.Config `yaml:"llm"`
Nats *nats.Config `yaml:"nats"`
Notifications *notifications.Config `yaml:"notifications"`
OCDav *ocdav.Config `yaml:"ocdav"`
+2
View File
@@ -22,6 +22,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config/defaults"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config/defaults"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config/defaults"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config/defaults"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config/defaults"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config/defaults"
@@ -77,6 +78,7 @@ func DefaultConfig() *Config {
IDM: idm.DefaultConfig(),
IDP: idp.DefaultConfig(),
Invitations: invitations.DefaultConfig(),
LLM: llm.DefaultConfig(),
Nats: nats.DefaultConfig(),
Notifications: notifications.DefaultConfig(),
OCDav: ocdav.DefaultConfig(),
+6
View File
@@ -28,6 +28,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/command"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/command"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/command"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/command"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/command"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/command"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/command"
@@ -58,6 +59,11 @@ var svccmds = []register.Command{
cfg.Activitylog.Commons = cfg.Commons
})
},
func(cfg *config.Config) *cli.Command {
return ServiceCommand(cfg, cfg.LLM.Service.Name, llm.GetCommands(cfg.LLM), func(c *config.Config) {
cfg.LLM.Commons = cfg.Commons
})
},
func(cfg *config.Config) *cli.Command {
return ServiceCommand(cfg, cfg.Antivirus.Service.Name, antivirus.GetCommands(cfg.Antivirus), func(c *config.Config) {
// cfg.Antivirus.Commons = cfg.Commons // antivirus needs no commons atm
+6
View File
@@ -48,6 +48,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/command"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/command"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/command"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/command"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/command"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/command"
ocm "github.com/owncloud/ocis/v2/services/ocm/pkg/command"
@@ -355,6 +356,11 @@ func NewService(ctx context.Context, options ...Option) (*Service, error) {
cfg.Notifications.Commons = cfg.Commons
return runServerCommand(ctx, notifications.Server(cfg.Notifications))
})
areg(opts.Config.LLM.Service.Name, func(ctx context.Context, cfg *ociscfg.Config) error {
cfg.LLM.Context = ctx
cfg.LLM.Commons = cfg.Commons
return runServerCommand(ctx, llm.Server(cfg.LLM))
})
return s, nil
}
+10 -10
View File
@@ -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" 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"`
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"`
}
+37
View File
@@ -0,0 +1,37 @@
SHELL := bash
NAME := llm
include ../../.make/recursion.mk
############ tooling ############
ifneq (, $(shell command -v go 2> /dev/null)) # suppress `command not found warnings` for non go targets in CI
include ../../.bingo/Variables.mk
endif
############ go tooling ############
include ../../.make/go.mk
############ release ############
include ../../.make/release.mk
############ docs generate ############
include ../../.make/docs.mk
.PHONY: docs-generate
docs-generate: config-docs-generate
############ generate ############
include ../../.make/generate.mk
.PHONY: ci-go-generate
ci-go-generate: # CI runs ci-node-generate automatically before this target
.PHONY: ci-node-generate
ci-node-generate:
############ licenses ############
.PHONY: ci-node-check-licenses
ci-node-check-licenses:
.PHONY: ci-node-save-licenses
ci-node-save-licenses:
+46
View File
@@ -0,0 +1,46 @@
# LLM Proxy
The `llm` service proxies chat-completion requests from oCIS AI web
extensions to a configured, OpenAI-compatible LLM endpoint, so extensions
never see the upstream API key.
The public endpoint is reached through the `proxy` service at
`POST /graph/v1beta1/extensions/org.libregraph/llm/chat/completions`.
`LLM_ENDPOINT` is a **required** environment variable; the service will not
start without it. `llm` is an **opt-in** service — it must be explicitly
enabled via `OCIS_ADD_RUN_SERVICES=llm` (the same way `antivirus`,
`auth-app`, and `invitations` are enabled) for `ocis server` to run it.
## Limitations
Streaming responses are not supported. Requests with `"stream": true` are
rejected with `400 Bad Request`; the full completion is always returned as a
single JSON response.
## Auth
The `llm` service does not authenticate callers itself. It trusts the
`proxy` service, which validates the caller's OIDC token and forwards a
signed identity via the `X-Access-Token` header before the request reaches
`llm`.
## Rate limiting
Requests are rate-limited per user using a sliding window backed by the
configured store (`LLM_STORE`, defaults to `nats-js-kv`), so the limit is
shared across replicas when `llm` runs multiple instances. Configure the
window and request ceiling with `LLM_RATE_LIMIT_WINDOW` /
`LLM_RATE_LIMIT_MAX_REQUESTS`.
Each request is stored as its own record, so concurrent replicas never
overwrite each other's counts; under heavy concurrency at the limit a
request may be rejected, but the limit is never exceeded. Only requests
that are forwarded to the LLM count. Expiry is handled by the store, so
`LLM_STORE_TTL` must not be shorter than `LLM_RATE_LIMIT_WINDOW` (the
service refuses to start otherwise).
## Configuration
See the `LLM_*` environment variables in `pkg/config` for the upstream
endpoint, API key, model override, timeout, and body-size limit.
+20
View File
@@ -0,0 +1,20 @@
// services/llm/cmd/llm/main.go
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/owncloud/ocis/v2/services/llm/pkg/command"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
)
func main() {
cfg := defaults.DefaultConfig()
cfg.Context, _ = signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
if err := command.Execute(cfg); err != nil {
os.Exit(1)
}
}
+41
View File
@@ -0,0 +1,41 @@
// services/llm/pkg/command/health.go
package command
import (
"fmt"
"net/http"
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/parser"
"github.com/owncloud/ocis/v2/services/llm/pkg/logging"
"github.com/urfave/cli/v2"
)
// Health is the entrypoint for the health command.
func Health(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "health",
Usage: "check health status",
Category: "info",
Before: func(c *cli.Context) error {
return configlog.ReturnError(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
resp, err := http.Get(fmt.Sprintf("http://%s/healthz", cfg.Debug.Addr))
if err != nil {
logger.Fatal().Err(err).Msg("Failed to request health check")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Fatal().Int("code", resp.StatusCode).Msg("Health seems to be in bad state")
}
logger.Debug().Int("code", resp.StatusCode).Msg("Health got a good state")
return nil
},
}
}
+30
View File
@@ -0,0 +1,30 @@
// services/llm/pkg/command/root.go
package command
import (
"os"
"github.com/owncloud/ocis/v2/ocis-pkg/clihelper"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/urfave/cli/v2"
)
// GetCommands provides all commands for this service.
func GetCommands(cfg *config.Config) cli.Commands {
return []*cli.Command{
Server(cfg),
Health(cfg),
Version(cfg),
}
}
// Execute is the entry point for the ocis llm command.
func Execute(cfg *config.Config) error {
app := clihelper.DefaultApp(&cli.App{
Name: "llm",
Usage: "serve the LLM proxy for oCIS AI extensions",
Commands: GetCommands(cfg),
})
return app.RunContext(cfg.Context, os.Args)
}
+104
View File
@@ -0,0 +1,104 @@
// services/llm/pkg/command/server.go
package command
import (
"context"
"fmt"
"os/signal"
"github.com/owncloud/reva/v2/pkg/store"
"github.com/urfave/cli/v2"
microstore "go-micro.dev/v4/store"
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/parser"
"github.com/owncloud/ocis/v2/services/llm/pkg/logging"
"github.com/owncloud/ocis/v2/services/llm/pkg/metrics"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/owncloud/ocis/v2/services/llm/pkg/server/debug"
"github.com/owncloud/ocis/v2/services/llm/pkg/server/http"
)
// Server is the entrypoint for the server command.
func Server(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "server",
Usage: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
Category: "server",
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
tracerProvider, err := tracing.GetServiceTraceProvider(cfg.Tracing, cfg.Service.Name)
if err != nil {
logger.Error().Err(err).Msg("Failed to initialize tracer")
return err
}
var cancel context.CancelFunc
if cfg.Context == nil {
cfg.Context, cancel = signal.NotifyContext(context.Background(), runner.StopSignals...)
defer cancel()
}
ctx := cfg.Context
m := metrics.New()
m.BuildInfo.WithLabelValues(version.GetString()).Set(1)
rateLimitStore := store.Create(
store.Store(cfg.Store.Store),
store.TTL(cfg.Store.TTL),
microstore.Nodes(cfg.Store.Nodes...),
microstore.Database(cfg.Store.Database),
microstore.Table(cfg.Store.Table),
store.Authentication(cfg.Store.AuthUsername, cfg.Store.AuthPassword),
store.TLS(cfg.Store.EnableTLS, cfg.Store.TLSInsecure, cfg.Store.TLSRootCACertificate),
)
limiter := ratelimit.New(rateLimitStore, cfg.RateLimit.Window, cfg.RateLimit.MaxRequests)
gr := runner.NewGroup()
{
httpServer, err := http.Server(
http.Logger(logger),
http.Context(ctx),
http.Config(cfg),
http.Limiter(limiter),
http.TraceProvider(tracerProvider),
)
if err != nil {
logger.Info().Err(err).Str("server", "http").Msg("Failed to initialize server")
return err
}
gr.Add(runner.NewGoMicroHttpServerRunner(cfg.Service.Name+".http", httpServer))
}
{
debugServer, err := debug.Server(
debug.Logger(logger),
debug.Context(ctx),
debug.Config(cfg),
)
if err != nil {
logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
return err
}
gr.Add(runner.NewGolangHttpServerRunner(cfg.Service.Name+".debug", debugServer))
}
logger.Warn().Msgf("starting service %s", cfg.Service.Name)
grResults := gr.Run(ctx)
if err := runner.ProcessResults(grResults); err != nil {
logger.Error().Err(err).Msgf("service %s stopped with error", cfg.Service.Name)
return err
}
logger.Warn().Msgf("service %s stopped without error", cfg.Service.Name)
return nil
},
}
}
+49
View File
@@ -0,0 +1,49 @@
// services/llm/pkg/command/version.go
package command
import (
"fmt"
"os"
"github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/urfave/cli/v2"
)
// Version prints the service versions of all running instances.
func Version(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "version",
Usage: "print the version of this binary and the running service instances",
Category: "info",
Action: func(c *cli.Context) error {
fmt.Println("Version: " + version.GetString())
fmt.Printf("Compiled: %s\n", version.Compiled())
fmt.Println("")
reg := registry.GetRegistry()
services, err := reg.GetService(cfg.HTTP.Namespace + "." + cfg.Service.Name)
if err != nil {
fmt.Println(fmt.Errorf("could not get %s services from the registry: %v", cfg.Service.Name, err))
return err
}
if len(services) == 0 {
fmt.Println("No running " + cfg.Service.Name + " service found.")
return nil
}
table := tablewriter.NewTable(os.Stdout)
table.Header("Version", "Address", "Id")
for _, s := range services {
for _, n := range s.Nodes {
table.Append([]string{s.Version, n.Address, n.Id})
}
}
table.Render()
return nil
},
}
}
+64
View File
@@ -0,0 +1,64 @@
package config
import (
"context"
"time"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
)
// Config combines all available configuration parts.
type Config struct {
Commons *shared.Commons `yaml:"-"` // don't use this directly as configuration for a service
Service Service `yaml:"-"`
Tracing *Tracing `yaml:"tracing"`
Log *Log `yaml:"log"`
Debug Debug `yaml:"debug"`
HTTP HTTP `yaml:"http"`
TokenManager *TokenManager `yaml:"token_manager"`
Store Store `yaml:"store"`
RateLimit RateLimit `yaml:"rate_limit"`
LLM LLM `yaml:"llm"`
Context context.Context `yaml:"-"`
}
// TokenManager is the config for using the reva token manager.
type TokenManager struct {
JWTSecret string `yaml:"jwt_secret" env:"OCIS_JWT_SECRET;LLM_JWT_SECRET" desc:"The secret to mint and validate jwt tokens." introductionVersion:"%%NEXT%%"`
}
// Store configures the store used for per-user rate limiting.
type Store struct {
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;LLM_STORE" desc:"The type of the store. Supported values are: 'memory', 'nats-js-kv', 'redis-sentinel', 'noop'. See the text description for details." introductionVersion:"%%NEXT%%"`
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;LLM_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:"%%NEXT%%"`
Database string `yaml:"database" env:"LLM_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"%%NEXT%%"`
Table string `yaml:"table" env:"LLM_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"%%NEXT%%"`
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;LLM_STORE_TTL" desc:"Time to live for rate-limit entries in the store. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;LLM_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;LLM_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;LLM_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;LLM_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"%%NEXT%%"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;LLM_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
}
// RateLimit configures the per-user request rate limit.
type RateLimit struct {
Window time.Duration `yaml:"window" env:"LLM_RATE_LIMIT_WINDOW" desc:"The sliding time window over which requests per user are counted. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
MaxRequests int `yaml:"max_requests" env:"LLM_RATE_LIMIT_MAX_REQUESTS" desc:"The maximum number of chat completion requests a single user may make within the configured window. Set to 0 to disable rate limiting." introductionVersion:"%%NEXT%%"`
}
// LLM configures the upstream OpenAI-compatible LLM endpoint.
type LLM struct {
Endpoint string `yaml:"endpoint" env:"LLM_ENDPOINT" desc:"The base URL of the OpenAI-compatible LLM endpoint, without the trailing '/chat/completions' path, e.g. 'https://api.openai.com/v1'." introductionVersion:"%%NEXT%%"`
APIKey string `yaml:"api_key" env:"LLM_API_KEY" desc:"The API key used to authenticate with the LLM endpoint. Leave empty for LLM endpoints that require no authentication." introductionVersion:"%%NEXT%%" mask:"password"`
Model string `yaml:"model" env:"LLM_MODEL" desc:"When set, overrides the 'model' field of every client request, regardless of what the client sent." introductionVersion:"%%NEXT%%"`
MaxTokensLimit int `yaml:"max_tokens_limit" env:"LLM_MAX_TOKENS_LIMIT" desc:"Hard ceiling on the 'max_tokens' value forwarded to the LLM. A client-requested value above this is clamped to it." introductionVersion:"%%NEXT%%"`
Timeout time.Duration `yaml:"timeout" env:"LLM_TIMEOUT" desc:"Timeout for the upstream LLM request. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
MaxBodyBytes int64 `yaml:"max_body_bytes" env:"LLM_MAX_BODY_BYTES" desc:"Maximum request body size in bytes the service will buffer from a client before rejecting the request." introductionVersion:"%%NEXT%%"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Debug defines the available debug configuration.
type Debug struct {
Addr string `yaml:"addr" env:"LLM_DEBUG_ADDR" desc:"Bind address of the debug server, where metrics, health, config and debug endpoints will be exposed." introductionVersion:"%%NEXT%%"`
Token string `yaml:"token" env:"LLM_DEBUG_TOKEN" desc:"Token to secure the metrics endpoint." introductionVersion:"%%NEXT%%"`
Pprof bool `yaml:"pprof" env:"LLM_DEBUG_PPROF" desc:"Enables pprof, which can be used for profiling." introductionVersion:"%%NEXT%%"`
Zpages bool `yaml:"zpages" env:"LLM_DEBUG_ZPAGES" desc:"Enables zpages, which can be used for collecting and viewing in-memory traces." introductionVersion:"%%NEXT%%"`
}
@@ -0,0 +1,101 @@
package defaults
import (
"time"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// FullDefaultConfig returns the full default config.
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
EnsureDefaults(cfg)
Sanitize(cfg)
return cfg
}
// DefaultConfig returns the default configuration.
func DefaultConfig() *config.Config {
return &config.Config{
Debug: config.Debug{
Addr: "127.0.0.1:9346",
Token: "",
Pprof: false,
Zpages: false,
},
Service: config.Service{
Name: "llm",
},
HTTP: config.HTTP{
Addr: "127.0.0.1:9345",
Root: "/",
Namespace: "com.owncloud.web",
CORS: config.CORS{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"POST"},
AllowedHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With", "X-Request-Id"},
AllowCredentials: true,
},
},
Store: config.Store{
Store: "nats-js-kv",
Nodes: []string{"127.0.0.1:9233"},
Database: "llm",
Table: "rate-limit",
TTL: 10 * time.Minute,
},
RateLimit: config.RateLimit{
Window: time.Minute,
MaxRequests: 20,
},
LLM: config.LLM{
MaxTokensLimit: 4096,
Timeout: 60 * time.Second,
MaxBodyBytes: 6291456, // 6 MiB, covers a 4 MiB image after base64 encoding
},
}
}
// EnsureDefaults ensures the config contains default values.
func EnsureDefaults(cfg *config.Config) {
// provide with defaults for shared logging, since we need a valid destination address for "envdecode".
if cfg.Log == nil && cfg.Commons != nil && cfg.Commons.Log != nil {
cfg.Log = &config.Log{
Level: cfg.Commons.Log.Level,
Pretty: cfg.Commons.Log.Pretty,
Color: cfg.Commons.Log.Color,
File: cfg.Commons.Log.File,
}
} else if cfg.Log == nil {
cfg.Log = &config.Log{}
}
if cfg.TokenManager == nil && cfg.Commons != nil && cfg.Commons.TokenManager != nil {
cfg.TokenManager = &config.TokenManager{
JWTSecret: cfg.Commons.TokenManager.JWTSecret,
}
} else if cfg.TokenManager == nil {
cfg.TokenManager = &config.TokenManager{}
}
if cfg.Commons != nil {
cfg.HTTP.TLS = cfg.Commons.HTTPServiceTLS
}
// provide with defaults for shared tracing, since we need a valid destination address for "envdecode".
if cfg.Tracing == nil && cfg.Commons != nil && cfg.Commons.Tracing != nil {
cfg.Tracing = &config.Tracing{
Enabled: cfg.Commons.Tracing.Enabled,
Type: cfg.Commons.Tracing.Type,
Endpoint: cfg.Commons.Tracing.Endpoint,
Collector: cfg.Commons.Tracing.Collector,
}
} else if cfg.Tracing == nil {
cfg.Tracing = &config.Tracing{}
}
}
// Sanitize sanitizes the config.
func Sanitize(cfg *config.Config) {
// sanitize config
}
+20
View File
@@ -0,0 +1,20 @@
package config
import "github.com/owncloud/ocis/v2/ocis-pkg/shared"
// CORS defines the available cors configuration.
type CORS struct {
AllowedOrigins []string `yaml:"allow_origins" env:"OCIS_CORS_ALLOW_ORIGINS;LLM_CORS_ALLOW_ORIGINS" desc:"A list of allowed CORS origins. See following chapter for more details: *Access-Control-Allow-Origin* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowedMethods []string `yaml:"allow_methods" env:"OCIS_CORS_ALLOW_METHODS;LLM_CORS_ALLOW_METHODS" desc:"A list of allowed CORS methods. See following chapter for more details: *Access-Control-Request-Method* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowedHeaders []string `yaml:"allow_headers" env:"OCIS_CORS_ALLOW_HEADERS;LLM_CORS_ALLOW_HEADERS" desc:"A list of allowed CORS headers. See following chapter for more details: *Access-Control-Request-Headers* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowCredentials bool `yaml:"allow_credentials" env:"OCIS_CORS_ALLOW_CREDENTIALS;LLM_CORS_ALLOW_CREDENTIALS" desc:"Allow credentials for CORS. See following chapter for more details: *Access-Control-Allow-Credentials* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials." introductionVersion:"%%NEXT%%"`
}
// HTTP defines the available http configuration.
type HTTP struct {
Addr string `yaml:"addr" env:"LLM_HTTP_ADDR" desc:"The bind address of the HTTP service." introductionVersion:"%%NEXT%%"`
Namespace string `yaml:"-"`
Root string `yaml:"root" env:"LLM_HTTP_ROOT" desc:"Subdirectory that serves as the root for this HTTP service." introductionVersion:"%%NEXT%%"`
CORS CORS `yaml:"cors"`
TLS shared.HTTPServiceTLS `yaml:"tls"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Log defines the available log configuration.
type Log struct {
Level string `mapstructure:"level" env:"OCIS_LOG_LEVEL;LLM_LOG_LEVEL" desc:"The log level. Valid values are: 'panic', 'fatal', 'error', 'warn', 'info', 'debug', 'trace'." introductionVersion:"%%NEXT%%"`
Pretty bool `mapstructure:"pretty" env:"OCIS_LOG_PRETTY;LLM_LOG_PRETTY" desc:"Activates pretty log output." introductionVersion:"%%NEXT%%"`
Color bool `mapstructure:"color" env:"OCIS_LOG_COLOR;LLM_LOG_COLOR" desc:"Activates colorized log output." introductionVersion:"%%NEXT%%"`
File string `mapstructure:"file" env:"OCIS_LOG_FILE;LLM_LOG_FILE" desc:"The path to the log file. Activates logging to this file if set." introductionVersion:"%%NEXT%%"`
}
+61
View File
@@ -0,0 +1,61 @@
package parser
import (
"errors"
"fmt"
"net/url"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/config/envdecode"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
)
// ParseConfig loads configuration from known paths.
func ParseConfig(cfg *config.Config) error {
err := ociscfg.BindSourcesToStructs(cfg.Service.Name, cfg)
if err != nil {
return err
}
defaults.EnsureDefaults(cfg)
// load all env variables relevant to the config in the current context.
if err := envdecode.Decode(cfg); err != nil {
// no environment variable set for this config is an expected "error"
if !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
return err
}
}
defaults.Sanitize(cfg)
return Validate(cfg)
}
// Validate validates the config.
func Validate(cfg *config.Config) error {
if cfg.LLM.Endpoint == "" {
return errors.New("llm: LLM_ENDPOINT is required")
}
u, err := url.Parse(cfg.LLM.Endpoint)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("llm: LLM_ENDPOINT must be an http(s) URL, got %q", cfg.LLM.Endpoint)
}
if cfg.LLM.MaxTokensLimit <= 0 {
return errors.New("llm: LLM_MAX_TOKENS_LIMIT must be greater than 0")
}
if cfg.LLM.Timeout < 0 {
return errors.New("llm: LLM_TIMEOUT must not be negative")
}
if cfg.RateLimit.Window < 0 || cfg.RateLimit.MaxRequests < 0 {
return errors.New("llm: LLM_RATE_LIMIT_WINDOW and LLM_RATE_LIMIT_MAX_REQUESTS must not be negative")
}
// Rate-limit records are expired by the store; a store TTL shorter than
// the window would silently shrink the effective window.
if cfg.RateLimit.Window > 0 && cfg.RateLimit.MaxRequests > 0 &&
cfg.Store.TTL > 0 && cfg.Store.TTL < cfg.RateLimit.Window {
return fmt.Errorf("llm: LLM_STORE_TTL (%s) must not be shorter than LLM_RATE_LIMIT_WINDOW (%s)", cfg.Store.TTL, cfg.RateLimit.Window)
}
return nil
}
@@ -0,0 +1,68 @@
package parser
import (
"testing"
"time"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
func TestValidate_RequiresEndpoint(t *testing.T) {
cfg := &config.Config{}
if err := Validate(cfg); err == nil {
t.Fatal("expected an error when LLM.Endpoint is empty")
}
}
func TestValidate_PassesWhenEndpointSet(t *testing.T) {
cfg := validConfig()
if err := Validate(cfg); err != nil {
t.Fatalf("expected no error when LLM.Endpoint is set, got: %v", err)
}
}
func validConfig() *config.Config {
return &config.Config{
LLM: config.LLM{
Endpoint: "https://api.example.com/v1",
MaxTokensLimit: 4096,
},
}
}
func TestValidate_RejectsInvalidValues(t *testing.T) {
tests := map[string]func(*config.Config){
"endpoint without scheme": func(c *config.Config) { c.LLM.Endpoint = "api.example.com/v1" },
"endpoint wrong scheme": func(c *config.Config) { c.LLM.Endpoint = "ftp://api.example.com" },
"zero max tokens": func(c *config.Config) { c.LLM.MaxTokensLimit = 0 },
"negative timeout": func(c *config.Config) { c.LLM.Timeout = -time.Second },
"negative window": func(c *config.Config) { c.RateLimit.Window = -time.Second },
"store ttl below window": func(c *config.Config) {
c.RateLimit.Window = time.Hour
c.RateLimit.MaxRequests = 10
c.Store.TTL = 10 * time.Minute
},
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
cfg := validConfig()
mutate(cfg)
if err := Validate(cfg); err == nil {
t.Fatal("expected a validation error")
}
})
}
}
func TestValidate_AcceptsStoreTTLCoveringWindow(t *testing.T) {
cfg := validConfig()
cfg.RateLimit.Window = time.Minute
cfg.RateLimit.MaxRequests = 20
cfg.Store.TTL = 10 * time.Minute
if err := Validate(cfg); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
+6
View File
@@ -0,0 +1,6 @@
package config
// Service defines the available service configuration.
type Service struct {
Name string `yaml:"-"`
}
+21
View File
@@ -0,0 +1,21 @@
package config
import "github.com/owncloud/ocis/v2/ocis-pkg/tracing"
// Tracing defines the available tracing configuration.
type Tracing struct {
Enabled bool `yaml:"enabled" env:"OCIS_TRACING_ENABLED;LLM_TRACING_ENABLED" desc:"Activates tracing." introductionVersion:"%%NEXT%%"`
Type string `yaml:"type" env:"OCIS_TRACING_TYPE;LLM_TRACING_TYPE" desc:"The type of tracing. Defaults to '', which is the same as 'jaeger'. Allowed tracing types are 'jaeger', 'otlp' and '' as of now." introductionVersion:"%%NEXT%%"`
Endpoint string `yaml:"endpoint" env:"OCIS_TRACING_ENDPOINT;LLM_TRACING_ENDPOINT" desc:"The endpoint of the tracing agent." introductionVersion:"%%NEXT%%"`
Collector string `yaml:"collector" env:"OCIS_TRACING_COLLECTOR;LLM_TRACING_COLLECTOR" desc:"The HTTP endpoint for sending spans directly to a collector, i.e. http://jaeger-collector:14268/api/traces. Only used if the tracing endpoint is unset." introductionVersion:"%%NEXT%%"`
}
// Convert Tracing to the tracing package's Config struct.
func (t Tracing) Convert() tracing.Config {
return tracing.Config{
Enabled: t.Enabled,
Type: t.Type,
Endpoint: t.Endpoint,
Collector: t.Collector,
}
}
+18
View File
@@ -0,0 +1,18 @@
// services/llm/pkg/logging/logging.go
package logging
import (
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// Configure initializes a service-specific logger instance.
func Configure(name string, cfg *config.Log) log.Logger {
return log.NewLogger(
log.Name(name),
log.Level(cfg.Level),
log.Pretty(cfg.Pretty),
log.Color(cfg.Color),
log.File(cfg.File),
)
}
+33
View File
@@ -0,0 +1,33 @@
// services/llm/pkg/metrics/metrics.go
package metrics
import "github.com/prometheus/client_golang/prometheus"
var (
// Namespace defines the namespace for the defined metrics.
Namespace = "ocis"
// Subsystem defines the subsystem for the defined metrics.
Subsystem = "llm"
)
// Metrics defines the available metrics of this service.
type Metrics struct {
BuildInfo *prometheus.GaugeVec
}
// New initializes the available metrics.
func New() *Metrics {
m := &Metrics{
BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: Subsystem,
Name: "build_info",
Help: "Build information",
}, []string{"version"}),
}
_ = prometheus.Register(m.BuildInfo)
return m
}
+105
View File
@@ -0,0 +1,105 @@
// Package ratelimit implements a per-key sliding-window request limiter
// backed by a go-micro store.
//
// The go-micro store interface has no compare-and-swap, so a read-modify-write
// of a single shared counter would let concurrent replicas overwrite each
// other. Instead every request writes its own record (key "<key>/<unixnano>-<nonce>")
// and then counts the key's records within the window. A request that finds
// itself over the limit removes its own record and is denied. Because records
// are never overwritten, the limit holds across replicas: concurrent requests
// at the boundary may all be denied, but more than the maximum are never
// admitted.
//
// Records are expired by the store (a per-write TTL where supported, the
// store-wide TTL otherwise, which must therefore be at least the window).
package ratelimit
import (
"crypto/rand"
"encoding/hex"
"strconv"
"strings"
"time"
microstore "go-micro.dev/v4/store"
)
const separator = "/"
// Limiter enforces a per-key sliding-window request limit.
type Limiter struct {
store microstore.Store
window time.Duration
maxRequests int
}
// New creates a Limiter. If window <= 0 or maxRequests <= 0, the limiter is
// disabled and Allow always returns true.
func New(store microstore.Store, window time.Duration, maxRequests int) *Limiter {
return &Limiter{
store: store,
window: window,
maxRequests: maxRequests,
}
}
// Allow registers a request for key and reports whether it is within the
// configured limit. A denied request does not count against the limit.
func (l *Limiter) Allow(key string) (bool, error) {
if l == nil {
return true, nil
}
if l.window <= 0 || l.maxRequests <= 0 {
return true, nil
}
nonce := make([]byte, 4)
if _, err := rand.Read(nonce); err != nil {
return false, err
}
now := time.Now()
recordKey := key + separator + strconv.FormatInt(now.UnixNano(), 10) + "-" + hex.EncodeToString(nonce)
if err := l.store.Write(&microstore.Record{Key: recordKey}, microstore.WriteTTL(l.window)); err != nil {
return false, err
}
prefix := key + separator
keys, err := l.store.List(microstore.ListPrefix(prefix))
if err != nil {
// do not leave an uncounted-for record behind when we cannot decide
_ = l.store.Delete(recordKey)
return false, err
}
cutoff := now.Add(-l.window).UnixNano()
count := 0
for _, k := range keys {
if recordTime(k, prefix) >= cutoff {
count++
}
}
if count > l.maxRequests {
if err := l.store.Delete(recordKey); err != nil && err != microstore.ErrNotFound {
return false, err
}
return false, nil
}
return true, nil
}
// recordTime extracts the request timestamp from a record key. Keys that do
// not belong to prefix or are malformed yield 0 (i.e. "expired").
func recordTime(recordKey, prefix string) int64 {
if !strings.HasPrefix(recordKey, prefix) {
return 0
}
suffix := strings.TrimPrefix(recordKey, prefix)
ts, _, _ := strings.Cut(suffix, "-")
n, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return 0
}
return n
}
@@ -0,0 +1,181 @@
package ratelimit
import (
"sync"
"sync/atomic"
"testing"
"time"
microstore "go-micro.dev/v4/store"
)
func TestLimiter_AllowsUpToMax(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 3)
for i := 0; i < 3; i++ {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatalf("request %d should have been allowed", i+1)
}
}
}
func TestLimiter_DeniesOverMax(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 2)
for i := 0; i < 2; i++ {
if _, err := l.Allow("user-1"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("third request should have been denied")
}
}
func TestLimiter_TracksUsersIndependently(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 1)
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("user-1 first request should be allowed, got allowed=%v err=%v", allowed, err)
}
allowed, err = l.Allow("user-2")
if err != nil || !allowed {
t.Fatalf("user-2 first request should be allowed, got allowed=%v err=%v", allowed, err)
}
allowed, err = l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("user-1 second request should have been denied")
}
}
func TestLimiter_WindowExpiryClearsOldEntries(t *testing.T) {
l := New(microstore.NewMemoryStore(), 10*time.Millisecond, 1)
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("first request should be allowed, got allowed=%v err=%v", allowed, err)
}
time.Sleep(20 * time.Millisecond)
allowed, err = l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatal("request after window expiry should have been allowed")
}
}
func TestLimiter_DisabledWhenMaxRequestsIsZero(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 0)
for i := 0; i < 50; i++ {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatalf("request %d should have been allowed when the limiter is disabled", i+1)
}
}
}
// Two limiters sharing one store stand in for two llm replicas.
func TestLimiter_SharedAcrossReplicas(t *testing.T) {
shared := microstore.NewMemoryStore()
a := New(shared, time.Minute, 4)
b := New(shared, time.Minute, 4)
for i := 0; i < 2; i++ {
for _, l := range []*Limiter{a, b} {
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("request should be allowed, got allowed=%v err=%v", allowed, err)
}
}
}
for _, l := range []*Limiter{a, b} {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("request beyond the shared limit should have been denied")
}
}
}
func TestLimiter_ConcurrentRequestsNeverExceedMax(t *testing.T) {
shared := microstore.NewMemoryStore()
const max = 5
var admitted int32
var wg sync.WaitGroup
for i := 0; i < 40; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// each goroutine is its own "replica" with no shared mutex
allowed, err := New(shared, time.Minute, max).Allow("user-1")
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if allowed {
atomic.AddInt32(&admitted, 1)
}
}(i)
}
wg.Wait()
if admitted > max {
t.Fatalf("admitted %d requests, limit is %d", admitted, max)
}
}
func TestLimiter_DeniedRequestsDoNotCount(t *testing.T) {
l := New(microstore.NewMemoryStore(), 50*time.Millisecond, 1)
if allowed, _ := l.Allow("user-1"); !allowed {
t.Fatal("first request should be allowed")
}
for i := 0; i < 5; i++ {
if allowed, _ := l.Allow("user-1"); allowed {
t.Fatal("request should be denied")
}
}
time.Sleep(80 * time.Millisecond)
if allowed, _ := l.Allow("user-1"); !allowed {
t.Fatal("denied requests must not extend the window")
}
}
func TestLimiter_KeyPrefixDoesNotLeak(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 1)
if allowed, _ := l.Allow("user"); !allowed {
t.Fatal("first request should be allowed")
}
if allowed, _ := l.Allow("user/other"); !allowed {
t.Fatal("a key that merely starts with another key must be tracked separately")
}
}
+75
View File
@@ -0,0 +1,75 @@
// Package sanitize validates and sanitizes the JSON body a client sends to
// the chat-completions endpoint before it is forwarded to the upstream LLM.
// Only the fields the LLM actually needs are forwarded; everything else the
// client sent is dropped, so a client cannot inject unexpected upstream
// parameters.
package sanitize
import "errors"
// Request is the sanitized body forwarded to the upstream LLM.
type Request struct {
Model string `json:"model"`
Messages []interface{} `json:"messages"`
MaxTokens int `json:"max_tokens"`
Temperature *float64 `json:"temperature,omitempty"`
}
// Body validates and sanitizes a client's decoded JSON body.
//
// modelOverride, when non-empty, replaces whatever model the client sent.
// maxTokensLimit is a hard ceiling: the client's max_tokens is used only if
// positive, and is always clamped to this limit, which must itself be positive.
func Body(raw map[string]interface{}, modelOverride string, maxTokensLimit int) (Request, error) {
if maxTokensLimit <= 0 {
return Request{}, errors.New("max tokens limit must be positive")
}
if stream, ok := raw["stream"].(bool); ok && stream {
return Request{}, errors.New("streaming is not supported")
}
model := modelOverride
if model == "" {
if m, ok := raw["model"].(string); ok {
model = m
}
}
if model == "" {
return Request{}, errors.New("model is required")
}
messages, ok := raw["messages"].([]interface{})
if !ok || len(messages) == 0 {
return Request{}, errors.New("messages must be a non-empty array")
}
for _, m := range messages {
msg, ok := m.(map[string]interface{})
if !ok {
return Request{}, errors.New("each message must be an object")
}
if _, ok := msg["role"].(string); !ok {
return Request{}, errors.New("each message must have a string role")
}
}
maxTokens := maxTokensLimit
if v, ok := raw["max_tokens"].(float64); ok && v > 0 {
maxTokens = int(v)
}
if maxTokens > maxTokensLimit {
maxTokens = maxTokensLimit
}
req := Request{
Model: model,
Messages: messages,
MaxTokens: maxTokens,
}
if t, ok := raw["temperature"].(float64); ok {
req.Temperature = &t
}
return req, nil
}
+172
View File
@@ -0,0 +1,172 @@
package sanitize
import "testing"
var validMessages = []interface{}{map[string]interface{}{"role": "user", "content": "hi"}}
func TestBody_RequiresModel(t *testing.T) {
_, err := Body(map[string]interface{}{
"messages": validMessages,
}, "", 4096)
if err == nil {
t.Fatal("expected an error when model is missing and no override is set")
}
}
func TestBody_ModelOverrideWins(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "client-requested-model",
"messages": validMessages,
}, "forced-model", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "forced-model" {
t.Fatalf("expected model override to win, got %q", req.Model)
}
}
func TestBody_ClientModelUsedWhenNoOverride(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "client-model",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "client-model" {
t.Fatalf("expected client model, got %q", req.Model)
}
}
func TestBody_RequiresMessagesArray(t *testing.T) {
_, err := Body(map[string]interface{}{
"model": "m",
"messages": "not-an-array",
}, "", 4096)
if err == nil {
t.Fatal("expected an error when messages is not an array")
}
}
func TestBody_MaxTokensClampedToLimit(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"max_tokens": float64(999999),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens clamped to 4096, got %d", req.MaxTokens)
}
}
func TestBody_MaxTokensDefaultsToLimitWhenAbsent(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens to default to the limit, got %d", req.MaxTokens)
}
}
func TestBody_MaxTokensDefaultsToLimitWhenNotPositive(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"max_tokens": float64(-1),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens to default to the limit for a non-positive value, got %d", req.MaxTokens)
}
}
func TestBody_TemperaturePassedThrough(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"temperature": float64(0.7),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Temperature == nil || *req.Temperature != 0.7 {
t.Fatalf("expected temperature 0.7, got %v", req.Temperature)
}
}
func TestBody_TemperatureOmittedWhenAbsent(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Temperature != nil {
t.Fatalf("expected temperature to be nil, got %v", req.Temperature)
}
}
func TestBody_DropsUnknownFields(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"some_random_field": "should be dropped",
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "m" || len(req.Messages) != 1 {
t.Fatalf("unexpected sanitized request: %+v", req)
}
}
func TestBody_RejectsInvalidMessages(t *testing.T) {
tests := map[string][]interface{}{
"empty": {},
"non-object": {"hi"},
"missing role": {map[string]interface{}{"content": "hi"}},
"non-string role": {map[string]interface{}{"role": 1}},
}
for name, messages := range tests {
t.Run(name, func(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": messages}, "", 4096)
if err == nil {
t.Fatal("expected an error")
}
})
}
}
func TestBody_RejectsNonPositiveMaxTokensLimit(t *testing.T) {
for _, limit := range []int{0, -1} {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages}, "", limit)
if err == nil {
t.Fatalf("expected an error for limit %d", limit)
}
}
}
func TestBody_RejectsStreaming(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages, "stream": true}, "", 4096)
if err == nil {
t.Fatal("expected an error when stream is true")
}
}
func TestBody_AllowsStreamFalse(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages, "stream": false}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
+43
View File
@@ -0,0 +1,43 @@
// services/llm/pkg/server/debug/option.go
package debug
import (
"context"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Context context.Context
Config *config.Config
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) { o.Logger = val }
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) { o.Context = val }
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) { o.Config = val }
}
+38
View File
@@ -0,0 +1,38 @@
// services/llm/pkg/server/debug/server.go
package debug
import (
"net/http"
"github.com/owncloud/ocis/v2/ocis-pkg/checks"
"github.com/owncloud/ocis/v2/ocis-pkg/handlers"
"github.com/owncloud/ocis/v2/ocis-pkg/service/debug"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
)
// Server initializes the debug service and server.
func Server(opts ...Option) (*http.Server, error) {
options := newOptions(opts...)
checkHandler := handlers.NewCheckHandler(
handlers.NewCheckHandlerConfiguration().
WithLogger(options.Logger).
WithCheck("llm reachability", checks.NewHTTPCheck(options.Config.HTTP.Addr)),
)
return debug.NewService(
debug.Logger(options.Logger),
debug.Name(options.Config.Service.Name),
debug.Version(version.GetString()),
debug.Address(options.Config.Debug.Addr),
debug.Token(options.Config.Debug.Token),
debug.Pprof(options.Config.Debug.Pprof),
debug.Zpages(options.Config.Debug.Zpages),
debug.Health(checkHandler),
debug.Ready(checkHandler),
debug.CorsAllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
debug.CorsAllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
debug.CorsAllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
debug.CorsAllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
), nil
}
+67
View File
@@ -0,0 +1,67 @@
// services/llm/pkg/server/http/option.go
package http
import (
"context"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/urfave/cli/v2"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Context context.Context
Config *config.Config
Flags []cli.Flag
Limiter *ratelimit.Limiter
TraceProvider trace.TracerProvider
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) { o.Logger = val }
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) { o.Context = val }
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) { o.Config = val }
}
// Limiter provides a function to set the rate limiter option.
func Limiter(val *ratelimit.Limiter) Option {
return func(o *Options) { o.Limiter = val }
}
// TraceProvider provides a function to configure the trace provider.
func TraceProvider(traceProvider trace.TracerProvider) Option {
return func(o *Options) {
if traceProvider != nil {
o.TraceProvider = traceProvider
} else {
o.TraceProvider = noop.NewTracerProvider()
}
}
}
+94
View File
@@ -0,0 +1,94 @@
// services/llm/pkg/server/http/server.go
package http
import (
nethttp "net/http"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"go-micro.dev/v4"
"github.com/owncloud/ocis/v2/ocis-pkg/account"
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
ohttp "github.com/owncloud/ocis/v2/ocis-pkg/service/http"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/service"
)
// Server initializes the http service and server.
func Server(opts ...Option) (ohttp.Service, error) {
options := newOptions(opts...)
newService, err := ohttp.NewService(
ohttp.TLSConfig(options.Config.HTTP.TLS),
ohttp.Logger(options.Logger),
ohttp.Namespace(options.Config.HTTP.Namespace),
ohttp.Name(options.Config.Service.Name),
ohttp.Version(version.GetString()),
ohttp.Address(options.Config.HTTP.Addr),
ohttp.Context(options.Context),
ohttp.Flags(options.Flags...),
ohttp.TraceProvider(options.TraceProvider),
)
if err != nil {
options.Logger.Error().Err(err).Msg("Error initializing http service")
return ohttp.Service{}, err
}
svc := service.New(options.Config, options.Limiter, options.Logger)
mux := chi.NewMux()
mux.Use(
middleware.GetOtelhttpMiddleware(options.Config.Service.Name, options.TraceProvider),
chimiddleware.RequestID,
middleware.Version(options.Config.Service.Name, version.GetString()),
middleware.Logger(options.Logger),
requireIdentity(middleware.ExtractAccountUUID(
account.Logger(options.Logger),
account.JWTSecret(options.Config.TokenManager.JWTSecret),
)),
middleware.Cors(
cors.Logger(options.Logger),
cors.AllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
cors.AllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
cors.AllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
cors.AllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
),
)
mux.Route(options.Config.HTTP.Root, func(r chi.Router) {
// proxy forwards the original request path unchanged (it does not
// strip the matched prefix — see activitylog's route registration
// for the same pattern), so this must be the full external path.
r.Post("/graph/v1beta1/extensions/org.libregraph/llm/chat/completions", svc.HandleChatCompletions)
})
if err := micro.RegisterHandler(newService.Server(), mux); err != nil {
options.Logger.Error().Err(err).Msg("failed to register the handler")
return ohttp.Service{}, err
}
newService.Init()
return newService, nil
}
// requireIdentity wraps the account middleware, which silently returns an
// empty 200 when the token is invalid or out of scope. Reject those requests
// explicitly instead.
func requireIdentity(extract func(nethttp.Handler) nethttp.Handler) func(nethttp.Handler) nethttp.Handler {
return func(next nethttp.Handler) nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
passed := false
extract(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
passed = true
next.ServeHTTP(w, r)
})).ServeHTTP(w, r)
if !passed {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(nethttp.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":"invalid access token"}` + "\n"))
}
})
}
}
@@ -0,0 +1,40 @@
package http
import (
nethttp "net/http"
"net/http/httptest"
"testing"
)
func TestRequireIdentity_RejectsWhenAccountMiddlewareStopsTheRequest(t *testing.T) {
// stands in for ExtractAccountUUID returning early on an invalid token
extract := func(next nethttp.Handler) nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {})
}
called := false
h := requireIdentity(extract)(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { called = true }))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(nethttp.MethodPost, "/", nil))
if rec.Code != nethttp.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
if called {
t.Fatal("next handler must not run")
}
}
func TestRequireIdentity_PassesThroughWhenAccountMiddlewareContinues(t *testing.T) {
extract := func(next nethttp.Handler) nethttp.Handler { return next }
h := requireIdentity(extract)(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusNoContent)
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(nethttp.MethodPost, "/", nil))
if rec.Code != nethttp.StatusNoContent {
t.Fatalf("expected 204, got %d", rec.Code)
}
}
+21
View File
@@ -0,0 +1,21 @@
package service
import (
"errors"
"io"
)
var errBodyTooLarge = errors.New("request body too large")
// readLimited reads r fully, returning errBodyTooLarge if the body exceeds
// maxBytes.
func readLimited(r io.Reader, maxBytes int64) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(r, maxBytes+1))
if err != nil {
return nil, err
}
if int64(len(data)) > maxBytes {
return nil, errBodyTooLarge
}
return data, nil
}
+168
View File
@@ -0,0 +1,168 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/owncloud/ocis/v2/services/llm/pkg/sanitize"
)
// maxUpstreamResponseBytes caps how much of the upstream LLM's response body
// this service will buffer before giving up.
const maxUpstreamResponseBytes = 10 * 1024 * 1024 // 10 MiB
// Service handles chat completion requests, proxying them to the configured
// upstream LLM endpoint.
type Service struct {
cfg *config.Config
limiter *ratelimit.Limiter
client *http.Client
log log.Logger
}
// New creates a new Service.
func New(cfg *config.Config, limiter *ratelimit.Limiter, logger log.Logger) *Service {
return &Service{
cfg: cfg,
limiter: limiter,
client: &http.Client{},
log: logger,
}
}
// HandleChatCompletions handles POST requests forwarding chat completions to
// the configured LLM.
func (s *Service) HandleChatCompletions(w http.ResponseWriter, r *http.Request) {
user, ok := revactx.ContextGetUser(r.Context())
if !ok {
writeError(w, http.StatusUnauthorized, "missing authenticated user")
return
}
body, err := readLimited(r.Body, s.cfg.LLM.MaxBodyBytes)
if err != nil {
if errors.Is(err, errBodyTooLarge) {
writeError(w, http.StatusRequestEntityTooLarge, "request body too large")
} else {
writeError(w, http.StatusBadRequest, "could not read request body")
}
return
}
var raw map[string]interface{}
if err := json.Unmarshal(body, &raw); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
sanitized, err := sanitize.Body(raw, s.cfg.LLM.Model, s.cfg.LLM.MaxTokensLimit)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// only requests that are valid and about to hit the upstream count
// against the user's quota.
allowed, err := s.limiter.Allow(user.GetId().GetOpaqueId())
if err != nil {
s.log.Warn().Err(err).Msg("rate limit check failed")
writeError(w, http.StatusInternalServerError, "rate limit check failed")
return
}
if !allowed {
writeError(w, http.StatusTooManyRequests, "rate limit exceeded. Please slow down.")
return
}
payload, err := json.Marshal(sanitized)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not encode upstream request")
return
}
ctx, cancel := contextWithTimeout(r.Context(), s.cfg.LLM.Timeout)
defer cancel()
upstreamURL := strings.TrimSuffix(s.cfg.LLM.Endpoint, "/") + "/chat/completions"
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, upstreamURL, bytes.NewReader(payload))
if err != nil {
writeError(w, http.StatusInternalServerError, "could not build upstream request")
return
}
upstreamReq.Header.Set("Content-Type", "application/json")
if s.cfg.LLM.APIKey != "" {
upstreamReq.Header.Set("Authorization", "Bearer "+s.cfg.LLM.APIKey)
}
resp, err := s.client.Do(upstreamReq)
if err != nil {
s.log.Warn().Err(err).Msg("could not reach upstream LLM endpoint")
writeError(w, http.StatusBadGateway, "could not reach LLM endpoint")
return
}
defer resp.Body.Close()
respBody, err := readLimited(resp.Body, maxUpstreamResponseBytes)
if err != nil {
s.log.Warn().Err(err).Msg("could not read upstream LLM response")
writeError(w, http.StatusBadGateway, "could not read LLM response")
return
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
// Do not relay upstream errors: a 401/403 caused by a bad API key
// would look like an expired session to the web client, and the
// error text can contain provider account details.
s.log.Warn().
Int("status", resp.StatusCode).
Str("body", truncate(string(respBody), 512)).
Msg("upstream LLM endpoint returned an error")
if resp.StatusCode == http.StatusTooManyRequests {
writeError(w, http.StatusTooManyRequests, "the LLM endpoint is busy. Please try again later.")
} else {
writeError(w, http.StatusBadGateway, "the LLM endpoint returned an error")
}
return
}
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(respBody)
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
func writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}
// contextWithTimeout wraps context.WithTimeout; a timeout <= 0 means "no
// explicit timeout beyond whatever the parent context already has" instead
// of expiring immediately.
func contextWithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if timeout <= 0 {
return parent, func() {}
}
return context.WithTimeout(parent, timeout)
}
+300
View File
@@ -0,0 +1,300 @@
package service
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
microstore "go-micro.dev/v4/store"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
)
func testUser(id string) *userpb.User {
return &userpb.User{Id: &userpb.UserId{OpaqueId: id}}
}
func newTestService(t *testing.T, llmServerURL string, maxRequests int) *Service {
t.Helper()
cfg := &config.Config{
LLM: config.LLM{
Endpoint: llmServerURL,
MaxTokensLimit: 4096,
Timeout: 5 * time.Second,
MaxBodyBytes: 1024,
},
}
limiter := ratelimit.New(microstore.NewMemoryStore(), time.Minute, maxRequests)
return New(cfg, limiter, log.NewLogger(log.Level("error")))
}
func requestWithUser(body []byte, userID string) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/chat/completions", bytes.NewReader(body))
if userID != "" {
ctx := revactx.ContextSetUser(req.Context(), testUser(userID))
req = req.WithContext(ctx)
}
return req
}
func TestHandleChatCompletions_NoUser_Returns401(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`{}`), "")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
}
func TestHandleChatCompletions_RateLimited_Returns429(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 1)
// first request consumes the only allowed slot; the upstream call will
// fail (no server listening at unused.invalid), which is fine — we only
// care about the rate limiter state after this call.
first := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
svc.HandleChatCompletions(httptest.NewRecorder(), first)
second := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, second)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("expected 429, got %d", rec.Code)
}
}
func TestHandleChatCompletions_OversizedBody_Returns413(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
oversized := bytes.Repeat([]byte("a"), 2048)
req := requestWithUser(oversized, "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d", rec.Code)
}
}
func TestHandleChatCompletions_InvalidJSON_Returns400(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`not json`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
func TestHandleChatCompletions_MissingMessages_Returns400(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`{"model":"m"}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
func TestHandleChatCompletions_HappyPath_RelaysUpstreamResponse(t *testing.T) {
var receivedPath string
var receivedAuth string
var receivedBody []byte
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
receivedAuth = r.Header.Get("Authorization")
receivedBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"hi"}}]}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
svc.cfg.LLM.APIKey = "test-key"
req := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":999999,"some_unknown_field":"should be dropped"}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d, body: %s", rec.Code, rec.Body.String())
}
if receivedPath != "/chat/completions" {
t.Fatalf("expected upstream path /chat/completions, got %q", receivedPath)
}
if receivedAuth != "Bearer test-key" {
t.Fatalf("expected upstream Authorization header, got %q", receivedAuth)
}
var got map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("expected valid JSON relayed back, got error: %v, body: %s", err, rec.Body.String())
}
var forwarded map[string]interface{}
if err := json.Unmarshal(receivedBody, &forwarded); err != nil {
t.Fatalf("expected valid JSON forwarded to upstream, got error: %v, body: %s", err, receivedBody)
}
if _, present := forwarded["some_unknown_field"]; present {
t.Fatalf("expected unknown field to be dropped from forwarded body, got: %s", receivedBody)
}
maxTokens, ok := forwarded["max_tokens"].(float64)
if !ok {
t.Fatalf("expected max_tokens to be forwarded, got: %s", receivedBody)
}
if int(maxTokens) != svc.cfg.LLM.MaxTokensLimit {
t.Fatalf("expected max_tokens clamped to %d, got %v", svc.cfg.LLM.MaxTokensLimit, maxTokens)
}
}
func TestHandleChatCompletions_ModelOverride_ReplacesClientModel(t *testing.T) {
var receivedBody []byte
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"hi"}}]}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
svc.cfg.LLM.Model = "forced-model"
req := requestWithUser([]byte(`{"model":"client-requested-model","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d, body: %s", rec.Code, rec.Body.String())
}
var forwarded map[string]interface{}
if err := json.Unmarshal(receivedBody, &forwarded); err != nil {
t.Fatalf("expected valid JSON forwarded to upstream, got error: %v, body: %s", err, receivedBody)
}
if forwarded["model"] != "forced-model" {
t.Fatalf("expected forwarded model to be overridden to %q, got %v", "forced-model", forwarded["model"])
}
}
func TestHandleChatCompletions_UpstreamUnreachable_Returns502(t *testing.T) {
svc := newTestService(t, "http://127.0.0.1:1", 20) // nothing listens here
req := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadGateway {
t.Fatalf("expected 502, got %d", rec.Code)
}
}
func TestHandleChatCompletions_ClientDisconnect_CancelsUpstreamCall(t *testing.T) {
upstreamStarted := make(chan struct{})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Drain the request body before waiting: net/http's server only starts
// watching the connection for a client disconnect (which cancels
// r.Context()) once the request body has been fully read. Without this,
// r.Context().Done() below would never fire and the test would hang -
// this is standard net/http behavior, not something the handler under
// test can influence, since it is the *client* whose context we cancel.
_, _ = io.Copy(io.Discard, r.Body)
close(upstreamStarted)
<-r.Context().Done() // the client cancellation below should propagate here
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequest(http.MethodPost, "/chat/completions", bytes.NewReader([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`)))
req = req.WithContext(revactx.ContextSetUser(ctx, testUser("user-1")))
done := make(chan struct{})
go func() {
svc.HandleChatCompletions(httptest.NewRecorder(), req)
close(done)
}()
<-upstreamStarted
cancel()
select {
case <-done:
// handler returned once the client context was canceled, as expected
case <-time.After(5 * time.Second):
t.Fatal("handler did not return after client disconnect")
}
}
func TestHandleChatCompletions_InvalidRequestDoesNotConsumeQuota(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 1)
for i := 0; i < 3; i++ {
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[]}`), "user-1"))
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
// the single allowed slot is still free, so this reaches the (dead) upstream
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1"))
if rec.Code != http.StatusBadGateway {
t.Fatalf("expected 502, got %d", rec.Code)
}
}
func TestHandleChatCompletions_UpstreamErrors_AreNotRelayed(t *testing.T) {
tests := []struct {
upstream int
want int
}{
{http.StatusUnauthorized, http.StatusBadGateway},
{http.StatusForbidden, http.StatusBadGateway},
{http.StatusInternalServerError, http.StatusBadGateway},
{http.StatusTooManyRequests, http.StatusTooManyRequests},
}
for _, tt := range tests {
t.Run(http.StatusText(tt.upstream), func(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.upstream)
_, _ = w.Write([]byte(`{"error":"secret provider account detail"}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1"))
if rec.Code != tt.want {
t.Fatalf("expected %d, got %d", tt.want, rec.Code)
}
if strings.Contains(rec.Body.String(), "secret provider account detail") {
t.Fatal("upstream error body must not be relayed to the client")
}
})
}
}
+1 -1
View File
@@ -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" desc:"The database name the configured store should use." 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."`
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"`
@@ -270,10 +270,22 @@ func DefaultPolicies() []config.Policy {
Endpoint: "/graph/v1.0/invitations",
Service: "com.owncloud.web.invitations",
},
{
Endpoint: "/graph/v1beta1/extensions/org.libregraph/llm/",
Service: "com.owncloud.web.llm",
},
{
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",
+31
View File
@@ -165,3 +165,34 @@ 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)
}
}
}
+1 -1
View File
@@ -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" desc:"The database name the configured store should use." 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."`
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"`
+10 -10
View File
@@ -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" 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"`
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"`
}
+20 -20
View File
@@ -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" 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"`
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"`
}
// 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" 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"`
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"`
}
// S3Driver is the storage driver configuration when using 's3' storage driver
+29 -30
View File
@@ -1338,48 +1338,47 @@ class CliContext implements Context {
}
/**
* Finds the most recently written blob in the storage-users blobstore.
* Scoped to the users storage root to avoid picking blobs from metadata storage.
* 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.
*
* @return string absolute path to a real blob file
*/
private function findNewestBlobPath(): string {
$storageRoot = $this->featureContext->getStorageUsersRoot();
// Async postprocessing may not have moved the blob to its final
// location yet — poll until the directory appears or we give up.
$blobDirs = [];
$newestPath = null;
$retried = 0;
do {
$blobDirs = \glob($storageRoot . '/spaces/*/*/blobs', GLOB_ONLYDIR) ?: [];
if (!empty($blobDirs)) {
$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) {
break;
}
$retried++;
echo "Blobstore directories not found under $storageRoot, retrying ($retried)...\n";
\usleep(500 * 1000);
echo "Committed blob not found under $storageRoot, retrying ($retried)...\n";
\usleep(STANDARD_SLEEP_TIME_MICROSEC * 50);
} while ($retried < STANDARD_RETRY_COUNT);
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");
Assert::assertNotNull($newestPath, "No committed 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 waits for "2" seconds
And the administrator has waited until the file "today.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
@@ -49,6 +49,7 @@ 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
+2
View File
@@ -74,6 +74,7 @@ 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
@@ -86,6 +87,7 @@ 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
+4 -7
View File
@@ -137,13 +137,10 @@
- name: IDM_CREATE_DEMO_USERS
value: "false"
{{- end -}}
{{- 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
{{- 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. */}}
{{/* 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
@@ -1,161 +0,0 @@
{{- 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 -}}
@@ -1,28 +0,0 @@
{{- 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 -}}
+31 -2
View File
@@ -18,6 +18,8 @@ features:
enabled: false
vault:
enabled: false
mfa:
enabled: false
emailNotifications:
enabled: false
smtp:
@@ -49,21 +51,45 @@ 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: false
secureViewEnabled: true
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
@@ -75,6 +101,7 @@ 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
@@ -84,6 +111,8 @@ features:
disableChat: true
ingress:
enabled: false
roles:
availableUnifiedRoles: []
http:
cors:
@@ -149,7 +178,7 @@ services:
enabled: true
accessModes:
- ReadWriteOnce
storageusers-vault:
storageusersvault:
persistence:
enabled: false
ocm:
+5 -1
View File
@@ -50,7 +50,8 @@ 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 addresses are returned unchanged. IPv4 mapped IPv6 addresses use
// their dotted IPv4 form.
// - 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
@@ -94,6 +95,9 @@ 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
View File
@@ -83,16 +83,16 @@ func (l *Conn) Add(addRequest *AddRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
if packet.Children[1].Tag == ApplicationAddResponse {
err := GetLDAPError(packet)
if err != nil {
if protocolOp.Tag == ApplicationAddResponse {
if err := GetLDAPError(packet); err != nil {
return err
}
} else {
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
}
return nil
}
+125 -68
View File
@@ -6,15 +6,15 @@ import (
"crypto/rand"
"encoding/binary"
"encoding/hex"
enchex "encoding/hex"
"errors"
"fmt"
"io/ioutil"
"io"
"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,15 +77,26 @@ 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),
}
if len(packet.Children) == 3 {
for _, child := range packet.Children[2].Children {
controls, ok, err := packetChildIfPresent(packet, 2)
if err != nil {
return nil, err
}
if ok {
for _, child := range controls.Children {
decodedChild, decodeErr := DecodeControl(child)
if decodeErr != nil {
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
}
result.Controls = append(result.Controls, decodedChild)
}
@@ -196,26 +207,35 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
Controls: make([]Control, 0),
}
var params map[string]string
if len(packet.Children) == 2 {
if len(packet.Children[1].Children) == 4 {
child := packet.Children[1].Children[0]
if child.Tag != ber.TagEnumerated {
_, 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 {
return result, GetLDAPError(packet)
}
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)
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)
}
}
}
}
@@ -257,30 +277,45 @@ func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*Diges
return nil, fmt.Errorf("read packet: %s", err)
}
if len(packet.Children) == 2 {
response := packet.Children[1]
if response == nil {
_, hasControls, err := packetChildIfPresent(packet, 2)
if err != nil {
return nil, err
}
if !hasControls {
response, rerr := packetChild(packet, 1)
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 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)
}
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)
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)
}
}
}
} else {
return result, GetLDAPError(packet)
}
}
}
@@ -373,7 +408,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
if err != nil {
return "", err
}
cnonce := enchex.EncodeToString(rb)
cnonce := hex.EncodeToString(rb)
x := username + ":" + params["realm"] + ":" + password
y := md5Hash([]byte(x))
@@ -384,8 +419,8 @@ func computeResponse(params map[string]string, uri, username, password string) (
}
a2 := bytes.NewBuffer([]byte("AUTHENTICATE"))
a2.WriteString(":" + uri)
ha1 := enchex.EncodeToString(md5Hash(a1.Bytes()))
ha2 := enchex.EncodeToString(md5Hash(a2.Bytes()))
ha1 := hex.EncodeToString(md5Hash(a1.Bytes()))
ha2 := hex.EncodeToString(md5Hash(a2.Bytes()))
kd := ha1
kd += ":" + params["nonce"]
@@ -393,7 +428,7 @@ func computeResponse(params map[string]string, uri, username, password string) (
kd += ":" + cnonce
kd += ":" + qop
kd += ":" + ha2
resp := enchex.EncodeToString(md5Hash([]byte(kd)))
resp := hex.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),
@@ -502,8 +537,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 {
case req.Negotiator == nil:
switch req.Negotiator {
case nil:
negMessage, err = ntlmssp.NewNegotiateMessage(req.Domain, "")
if err != nil {
return fmt.Errorf("create NTLM negotiate message: %s", err)
@@ -596,15 +631,29 @@ func (l *Conn) NTLMChallengeBind(ntlmBindRequest *NTLMBindRequest) (*NTLMBindRes
var ntlmsspChallenge []byte
// now find the NTLM Response Message
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")) {
_, 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 {
return result, GetLDAPError(packet)
}
l.Debug.Printf("%d: found ntlmssp challenge", msgCtx.id)
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)
}
}
}
if ntlmsspChallenge != nil {
@@ -615,11 +664,12 @@ 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.ProcessChallengeWithHash(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash)
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Hash, &ntlmssp.AuthenticateMessageOptions{
PasswordHashed: true,
})
case ntlmBindRequest.Negotiator == nil && (ntlmBindRequest.Password != "" || ntlmBindRequest.AllowEmptyPassword):
// generate a response message to the challenge with the given Username/Password if password is provided
_, _, domainNeeded := ntlmssp.GetDomain(ntlmBindRequest.Username)
responseMessage, err = ntlmssp.ProcessChallenge(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, domainNeeded)
responseMessage, err = ntlmssp.NewAuthenticateMessage(ntlmsspChallenge, ntlmBindRequest.Username, ntlmBindRequest.Password, nil)
default:
hash := ntlmBindRequest.Hash
if len(hash) == 0 {
@@ -739,7 +789,7 @@ func (l *Conn) GSSAPIBindRequest(client GSSAPIClient, req *GSSAPIBindRequest) er
return l.GSSAPIBindRequestWithAPOptions(client, req, []int{})
}
// GSSAPIBindRequest performs the GSSAPI SASL bind using the provided GSSAPI client.
// GSSAPIBindRequestWithAPOptions performs the GSSAPI SASL bind using the provided GSSAPI client and AP options.
func (l *Conn) GSSAPIBindRequestWithAPOptions(client GSSAPIClient, req *GSSAPIBindRequest, APOptions []int) error {
//nolint:errcheck
defer client.DeleteSecContext()
@@ -819,33 +869,40 @@ func (l *Conn) saslBindTokenExchange(reqControls []Control, reqToken []byte) ([]
// packet is an envelope
// child 0 is message id
// child 1 is protocolOp
if len(packet.Children) != 2 {
if _, err := packetChildCount(packet, 2, 2, "bind response"); err != nil {
return nil, fmt.Errorf("bad bind response")
}
protocolOp := packet.Children[1]
protocolOp, err := packetChild(packet, 1)
if err != nil {
return nil, fmt.Errorf("bad bind response")
}
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 := protocolOp.Children[0]
if resultCode.Tag != ber.TagEnumerated {
resultCode, rcErr := packetChild(protocolOp, 0)
if rcErr != nil || resultCode.Tag != ber.TagEnumerated {
break RESP
}
switch resultCode.Value.(int64) {
code, rcErr := packetInt64(resultCode)
if rcErr != nil {
break RESP
}
switch code {
case 14: // Sasl bind in progress
if len(protocolOp.Children) < 3 {
referral, ok, refErr := packetChildIfPresent(protocolOp, 3)
if refErr != nil || !ok {
break RESP
}
referral := protocolOp.Children[3]
switch referral.Description {
case "Referral":
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor {
if referral.ClassType != ber.ClassContext || referral.Tag != ber.TagObjectDescriptor || referral.Data == nil {
break RESP
}
return ioutil.ReadAll(referral.Data)
return io.ReadAll(referral.Data)
}
// Optional:
//if len(protocolOp.Children) == 4 {
+5 -4
View File
@@ -46,10 +46,11 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
return false, err
}
if len(packet.Children) < 2 {
return false, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return false, err
}
if packet.Children[1].Tag == ApplicationCompareResponse {
if protocolOp.Tag == ApplicationCompareResponse {
err := GetLDAPError(packet)
switch {
@@ -61,5 +62,5 @@ func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
return false, err
}
}
return false, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag)
return false, fmt.Errorf("unexpected Response: %d", protocolOp.Tag)
}
+12 -5
View File
@@ -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,6 +463,13 @@ 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 {
@@ -481,7 +488,6 @@ 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,
@@ -659,8 +665,9 @@ func (l *Conn) reader() {
if err := addLDAPDescriptions(packet); err != nil {
l.Debug.Printf("descriptions error: %s", err)
}
if len(packet.Children) == 0 {
l.Debug.Printf("Received bad ldap packet")
messageID, err := packetInt64At(packet, 0)
if err != nil {
l.Debug.Printf("Received bad ldap packet: %s", err)
continue
}
l.messageMutex.Lock()
@@ -670,7 +677,7 @@ func (l *Conn) reader() {
l.messageMutex.Unlock()
message := &messagePacket{
Op: MessageResponse,
MessageID: packet.Children[0].Value.(int64),
MessageID: messageID,
Packet: packet,
}
if !l.sendProcessMessage(message) {
+297 -174
View File
@@ -557,65 +557,68 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
value *ber.Packet
)
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")
children, err := packetChildCount(packet, 1, 3, "control")
if err != nil {
return nil, 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)
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)
}
ControlType = ct
} else if typeChild.Data != nil {
ControlType = typeChild.Data.String()
} else {
return nil, malformedf("not found where to get the control type")
}
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")
}
// 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]
}
switch len(children) {
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)
// criticality and value present
criticality, err := packetChild(packet, 1)
if err != nil {
return nil, err
}
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.Description = "Criticality"
crit, err := packetBool(criticality)
if err != nil {
return nil, fmt.Errorf("criticality is not a bool: %T: %w", criticality.Value, err)
}
Criticality = crit
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")
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
}
}
switch ControlType {
@@ -623,74 +626,113 @@ func DecodeControl(packet *ber.Packet) (Control, error) {
return NewControlManageDsaIT(Criticality), nil
case ControlTypePaging:
if value == nil {
return nil, fmt.Errorf("paging control value is missing")
return nil, malformedf("paging control value is missing")
}
value.Description += " (Paging)"
c := new(ControlPaging)
if value.Value != nil {
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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)
}
value.Data.Truncate(0)
value.Value = nil
value.AppendChild(valueChildren)
}
if len(value.Children) == 0 {
return nil, fmt.Errorf("paging control value is empty")
first, err := packetChild(value, 0)
if err != nil {
return nil, err
}
value = value.Children[0]
value = first
value.Description = "Search Control Value"
if len(value.Children) < 2 {
return nil, fmt.Errorf("paging control value has %d children, expected 2", len(value.Children))
sizeChild, err := packetChild(value, 0)
if err != nil {
return nil, 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)
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)
}
c.PagingSize = uint32(pagingSize)
c.Cookie = value.Children[1].Data.Bytes()
value.Children[1].Value = c.Cookie
cookie, err := packetData(cookieChild)
if err != nil {
return nil, err
}
c.Cookie = cookie
cookieChild.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 {
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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)
}
value.Data.Truncate(0)
value.Value = nil
value.AppendChild(valueChildren)
}
sequence := value.Children[0]
sequence, err := packetChild(value, 0)
if err != nil {
return nil, err
}
for _, child := range sequence.Children {
if child.Tag == 0 {
if child == nil {
continue
}
switch child.Tag {
case 0:
// Warning
warningPacket := child.Children[0]
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
warningPacket, err := packetChild(child, 0)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
return nil, err
}
if warningPacket.Tag == 0 {
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:
// timeBeforeExpiration
c.Expire = val
warningPacket.Value = c.Expire
} else if warningPacket.Tag == 1 {
case 1:
// graceAuthNsRemaining
c.Grace = val
warningPacket.Value = c.Grace
}
} else if child.Tag == 1 {
case 1:
// Error
bs := child.Data.Bytes()
bs, err := packetData(child)
if err != nil {
return nil, err
}
if len(bs) != 1 || bs[0] > 8 {
return nil, fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
return nil, malformedf("invalid PasswordPolicyResponse enum value")
}
val := int8(bs[0])
c.Error = val
@@ -711,7 +753,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: %s", err)
return nil, fmt.Errorf("failed to parse value as int: %w", err)
}
c.Expire = expire
value.Value = c.Expire
@@ -726,31 +768,58 @@ 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)"
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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 NewControlSyncState(valueChildren)
case ControlTypeSyncDone:
if value == nil {
return nil, malformedf("sync done control value is missing")
}
value.Description += " (Sync Done)"
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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 NewControlSyncDone(valueChildren)
case ControlTypeSyncInfo:
if value == nil {
return nil, malformedf("sync info control value is missing")
}
value.Description += " (Sync Info)"
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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 NewControlSyncInfo(valueChildren)
default:
@@ -763,10 +832,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, ok := value.Value.(string); ok {
if s, err := packetString(value); err == nil {
c.ControlValue = s
} else if value.Data != nil {
c.ControlValue = value.Data.String()
} else if data, err := packetData(value); err == nil {
c.ControlValue = string(data)
}
}
return c, nil
@@ -860,30 +929,64 @@ 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 {
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("failed to decode data bytes: %s", err)
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)
}
value.Data.Truncate(0)
value.Value = nil
value.AppendChild(valueChildren)
}
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, 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.Description = "DirSync Control Value"
child.Children[0].Description = "Flags"
child.Children[1].Description = "MaxAttrCount"
child.Children[2].Description = "Cookie"
flagsChild.Description = "Flags"
maxAttrChild.Description = "MaxAttrCount"
cookieChild.Description = "Cookie"
cookie := child.Children[2].Data.Bytes()
child.Children[2].Value = 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
}
return &ControlDirSync{
Criticality: true,
Flags: child.Children[0].Value.(int64),
MaxAttrCount: child.Children[1].Value.(int64),
Flags: flags,
MaxAttrCount: maxAttrCount,
Cookie: cookie,
}, nil
}
@@ -959,39 +1062,59 @@ func (c *ControlServerSideSorting) GetControlType() string {
}
func NewControlServerSideSorting(value *ber.Packet) (*ControlServerSideSorting, error) {
val, err := ber.DecodePacketErr(value.Data.Bytes())
if value == nil {
return nil, malformedf("server side sorting control value is missing")
}
data, err := packetData(value)
if err != nil {
return nil, fmt.Errorf("decode packet err: %s", err)
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)
}
if len(val.Children) == 0 {
return nil, fmt.Errorf("no sequence value in packet")
if _, err := packetChildCount(val, 1, -1, "sort key list"); err != nil {
return nil, fmt.Errorf("no sequence value in packet: %w", err)
}
var sortKeys []*SortKey
for i, sequence := range val.Children {
if len(sequence.Children) < 1 || len(sequence.Children) > 3 {
if sequence == nil {
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, ok := child.Value.(string); ok {
if attrType, err := packetString(child); err == nil {
sortKey.AttributeType = attrType
}
case child.ClassType == ber.ClassContext && child.Tag == 0:
sortKey.MatchingRule = child.Data.String()
b, err := packetData(child)
if err != nil {
return nil, err
}
sortKey.MatchingRule = string(b)
case child.ClassType == ber.ClassContext && child.Tag == 1:
b := child.Data.Bytes()
b, err := packetData(child)
if err != nil {
return nil, err
}
sortKey.Reverse = len(b) > 0 && b[0] != 0
}
}
@@ -1098,7 +1221,7 @@ func (c ControlServerSideSortingCode) Valid() error {
func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSortingResult, error) {
control := new(ControlServerSideSortingResult)
if pkt == nil || len(pkt.Children) == 0 {
if _, err := packetChildCount(pkt, 1, -1, "server side sorting result"); err != nil {
// 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.
//
@@ -1106,7 +1229,11 @@ func NewControlServerSideSortingResult(pkt *ber.Packet) (*ControlServerSideSorti
return control, nil
}
codeInt, err := ber.ParseInt64(pkt.Children[0].Data.Bytes())
data, err := packetDataAt(pkt, 0)
if err != nil {
return nil, err
}
codeInt, err := ber.ParseInt64(data)
if err != nil {
return nil, err
}
@@ -1129,7 +1256,7 @@ type ControlServerSideSortingResult struct {
// AttributeType string
}
func (control *ControlServerSideSortingResult) GetControlType() string {
func (c *ControlServerSideSortingResult) GetControlType() string {
return ControlTypeServerSideSortingResult
}
@@ -1151,7 +1278,7 @@ func (c *ControlServerSideSortingResult) String() string {
)
}
// Mode for ControlTypeSyncRequest
// ControlSyncRequestMode is the mode for ControlTypeSyncRequest
type ControlSyncRequestMode int64
const (
@@ -1225,7 +1352,7 @@ func (c *ControlSyncRequest) String() string {
)
}
// State for ControlSyncState
// ControlSyncStateState is the state for ControlSyncState
type ControlSyncStateState int64
const (
@@ -1248,24 +1375,26 @@ func NewControlSyncState(pkt *ber.Packet) (*ControlSyncState, error) {
state ControlSyncStateState
entryUUID uuid.UUID
cookie []byte
err error
)
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
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
}
return &ControlSyncState{
Criticality: false,
@@ -1305,19 +1434,30 @@ 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 (
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)
var refreshDeletes bool
cookie, flag, _ := parseSyncMembers(pkt.Children)
if flag != nil {
refreshDeletes = *flag
}
return &ControlSyncDone{
Criticality: false,
@@ -1348,7 +1488,7 @@ func (c *ControlSyncDone) String() string {
)
}
// Tag For ControlSyncInfo
// ControlSyncInfoValue is the tag for ControlSyncInfo
type ControlSyncInfoValue uint64
const (
@@ -1430,13 +1570,12 @@ 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.Identifier.Tag) {
switch ControlSyncInfoValue(pkt.Tag) {
case SyncInfoNewcookie:
c.Value = SyncInfoNewcookie
c.NewCookie = &ControlSyncInfoNewCookie{
@@ -1444,14 +1583,9 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
}
case SyncInfoRefreshDelete:
c.Value = SyncInfoRefreshDelete
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)
cookie, flag, _ := parseSyncMembers(pkt.Children)
if flag != nil {
refreshDone = *flag
}
c.RefreshDelete = &ControlSyncInfoRefreshDelete{
Cookie: cookie,
@@ -1459,14 +1593,9 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
}
case SyncInfoRefreshPresent:
c.Value = SyncInfoRefreshPresent
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)
cookie, flag, _ := parseSyncMembers(pkt.Children)
if flag != nil {
refreshDone = *flag
}
c.RefreshPresent = &ControlSyncInfoRefreshPresent{
Cookie: cookie,
@@ -1474,19 +1603,13 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
}
case SyncInfoSyncIdSet:
c.Value = SyncInfoSyncIdSet
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 {
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 {
u, err := uuid.FromBytes(child.ByteValue)
if err != nil {
return nil, fmt.Errorf("failed to decode uuid: %w", err)
@@ -1500,7 +1623,7 @@ func NewControlSyncInfo(pkt *ber.Packet) (*ControlSyncInfo, error) {
SyncUUIDs: syncUUIDs,
}
default:
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Identifier.Tag)
return nil, fmt.Errorf("unknown sync info value: %d", pkt.Tag)
}
return c, nil
}
+1 -1
View File
@@ -14,7 +14,7 @@ func (debug *debugging) Enable(b bool) {
}
// Printf writes debug output.
func (debug debugging) Printf(format string, args ...interface{}) {
func (debug debugging) Printf(format string, args ...any) {
if debug {
logger.Printf(format, args...)
}
+6 -6
View File
@@ -52,16 +52,16 @@ func (l *Conn) Del(delRequest *DelRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
if packet.Children[1].Tag == ApplicationDelResponse {
err := GetLDAPError(packet)
if err != nil {
if protocolOp.Tag == ApplicationDelResponse {
if err := GetLDAPError(packet); err != nil {
return err
}
} else {
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
}
return nil
+73 -25
View File
@@ -90,6 +90,7 @@ const (
ErrorUnexpectedMessage = 204
ErrorUnexpectedResponse = 205
ErrorEmptyPassword = 206
ErrorMalformedPacket = 207
)
// LDAPResultCodeMap contains string descriptions for LDAP error codes
@@ -175,6 +176,7 @@ 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
@@ -195,47 +197,93 @@ 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 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 _, 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 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 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}
}
resultCode := uint16(response.Children[0].Value.(int64))
if resultCode == 0 { // No error
return nil
}
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(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}
}
return &Error{
ResultCode: resultCode,
MatchedDN: response.Children[1].Value.(string),
Err: fmt.Errorf("%v", response.Children[2].Value),
Packet: packet,
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(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: 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
+38 -12
View File
@@ -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(er.Value)
pkt.AppendChild(encodeExtendedRequestValue(er.Value))
}
envelope.AppendChild(pkt)
if len(er.Controls) > 0 {
@@ -41,6 +41,16 @@ 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
@@ -72,16 +82,24 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
if err != nil {
return nil, err
}
if err = GetLDAPError(packet); err != nil {
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 {
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),
)
extResp, err := packetChild(packet, 1)
if err != nil {
return nil, err
}
if _, err := packetChildCount(extResp, 3, -1, "extended response"); err != nil {
return nil, err
}
response := &ExtendedResponse{
@@ -99,17 +117,25 @@ func (l *Conn) Extended(er *ExtendedRequest) (*ExtendedResponse, error) {
}
switch child.Tag {
case ber.TagEnumerated:
response.Name = child.Data.String()
name, err := packetData(child)
if err != nil {
return nil, err
}
response.Name = string(name)
case ber.TagEmbeddedPDV:
response.Value = child
}
}
if len(packet.Children) == 3 {
for _, child := range packet.Children[2].Children {
controlsChild, ok, err := packetChildIfPresent(packet, 2)
if err != nil {
return nil, err
}
if ok {
for _, child := range controlsChild.Children {
decodedChild, decodeErr := DecodeControl(child)
if decodeErr != nil {
return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
return nil, fmt.Errorf("failed to decode child control: %w", decodeErr)
}
response.Controls = append(response.Controls, decodedChild)
}
+18 -3
View File
@@ -208,9 +208,12 @@ 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
}
@@ -235,8 +238,17 @@ 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, err
return packet, newPos, nil
case '&':
packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterAnd, nil, FilterMap[FilterAnd])
newPos, err = compileFilterSet(filter, pos+currentWidth, packet)
@@ -249,8 +261,11 @@ 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, err
return packet, newPos, nil
default:
const (
stateReadingAttr = 0
+198 -68
View File
@@ -2,7 +2,6 @@ package ldap
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
@@ -101,10 +100,18 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
}
}()
packet.Description = "LDAP Response"
packet.Children[0].Description = "Message ID"
messageID, err := packetChild(packet, 0)
if err != nil {
return err
}
messageID.Description = "Message ID"
application := uint8(packet.Children[1].Tag)
packet.Children[1].Description = ApplicationMap[application]
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
application := uint8(protocolOp.Tag)
protocolOp.Description = ApplicationMap[application]
switch application {
case ApplicationBindRequest:
@@ -116,18 +123,46 @@ func addLDAPDescriptions(packet *ber.Packet) (err error) {
case ApplicationSearchRequest:
err = addRequestDescriptions(packet)
case ApplicationSearchResultEntry:
packet.Children[1].Children[0].Description = "Object Name"
packet.Children[1].Children[1].Description = "Attributes"
for _, child := range packet.Children[1].Children[1].Children {
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
}
child.Description = "Attribute"
child.Children[0].Description = "Attribute Name"
child.Children[1].Description = "Attribute Values"
for _, grandchild := range child.Children[1].Children {
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
}
grandchild.Description = "Attribute Value"
}
}
if len(packet.Children) == 3 {
err = addControlDescriptions(packet.Children[2])
controls, ok, err := packetChildIfPresent(packet, 2)
if err != nil {
return err
}
if ok {
if err = addControlDescriptions(controls); err != nil {
return err
}
}
case ApplicationSearchResultDone:
err = addDefaultLDAPResponseDescriptions(packet)
@@ -160,42 +195,55 @@ 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")
case 1:
// just type, no criticality or value
controlType = child.Children[0].Value.(string)
child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
controlChildren, err := packetChildCount(child, 1, 3, "control packet")
if err != nil {
return err
}
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:
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"
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"
} else {
child.Children[1].Description = "Control Value"
value = child.Children[1]
second.Description = "Control Value"
value = second
}
case 3:
// criticality and value present
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")
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
}
if value == nil {
@@ -205,53 +253,99 @@ func addControlDescriptions(packet *ber.Packet) error {
case ControlTypePaging:
value.Description += " (Paging)"
if value.Value != nil {
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return fmt.Errorf("failed to decode data bytes: %s", err)
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)
}
value.Data.Truncate(0)
value.Value = nil
valueChildren.Children[1].Value = valueChildren.Children[1].Data.Bytes()
cookieChild, err := packetChild(valueChildren, 1)
if err != nil {
return err
}
cookie, err := packetData(cookieChild)
if err != nil {
return err
}
cookieChild.Value = cookie
value.AppendChild(valueChildren)
}
value.Children[0].Description = "Real Search Control Value"
value.Children[0].Children[0].Description = "Paging Size"
value.Children[0].Children[1].Description = "Cookie"
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"
case ControlTypeBeheraPasswordPolicy:
value.Description += " (Password Policy - Behera Draft)"
if value.Value != nil {
valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
data, err := packetData(value)
if err != nil {
return fmt.Errorf("failed to decode data bytes: %s", err)
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)
}
value.Data.Truncate(0)
value.Value = nil
value.AppendChild(valueChildren)
}
sequence := value.Children[0]
sequence, err := packetChild(value, 0)
if err != nil {
return err
}
for _, child := range sequence.Children {
if child.Tag == 0 {
if child == nil {
continue
}
switch child.Tag {
case 0:
// Warning
warningPacket := child.Children[0]
val, err := ber.ParseInt64(warningPacket.Data.Bytes())
warningPacket, err := packetChild(child, 0)
if err != nil {
return fmt.Errorf("failed to decode data bytes: %s", err)
return err
}
if warningPacket.Tag == 0 {
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:
// timeBeforeExpiration
value.Description += " (TimeBeforeExpiration)"
warningPacket.Value = val
} else if warningPacket.Tag == 1 {
case 1:
// graceAuthNsRemaining
value.Description += " (GraceAuthNsRemaining)"
warningPacket.Value = val
}
} else if child.Tag == 1 {
case 1:
// Error
bs := child.Data.Bytes()
bs, err := packetData(child)
if err != nil {
return err
}
if len(bs) != 1 || bs[0] > 8 {
return fmt.Errorf("failed to decode data bytes: %s", "invalid PasswordPolicyResponse enum value")
return malformedf("invalid PasswordPolicyResponse enum value")
}
val := int8(bs[0])
child.Description = "Error"
@@ -265,10 +359,22 @@ func addControlDescriptions(packet *ber.Packet) error {
func addRequestDescriptions(packet *ber.Packet) error {
packet.Description = "LDAP Request"
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])
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)
}
return nil
}
@@ -283,28 +389,52 @@ func addDefaultLDAPResponseDescriptions(packet *ber.Packet) error {
description = "Error Message"
}
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"
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
if len(packet.Children) == 3 {
return addControlDescriptions(packet.Children[2])
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)
}
return nil
}
// DebugBinaryFile reads and prints packets from the given filename
func DebugBinaryFile(fileName string) error {
file, err := ioutil.ReadFile(fileName)
file, err := os.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: %s", err)
return fmt.Errorf("failed to decode packet: %w", err)
}
if err := addLDAPDescriptions(packet); err != nil {
return err
+6 -6
View File
@@ -89,16 +89,16 @@ func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
if packet.Children[1].Tag == ApplicationModifyDNResponse {
err := GetLDAPError(packet)
if err != nil {
if protocolOp.Tag == ApplicationModifyDNResponse {
if err := GetLDAPError(packet); err != nil {
return err
}
} else {
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
}
return nil
+18 -13
View File
@@ -121,16 +121,16 @@ func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
return err
}
if len(packet.Children) < 2 {
return fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return err
}
if packet.Children[1].Tag == ApplicationModifyResponse {
err := GetLDAPError(packet)
if err != nil {
if protocolOp.Tag == ApplicationModifyResponse {
if err := GetLDAPError(packet); err != nil {
return err
}
} else {
return fmt.Errorf("ldap: unexpected response: %d", packet.Children[1].Tag)
return fmt.Errorf("ldap: unexpected response: %d", protocolOp.Tag)
}
return nil
@@ -162,19 +162,22 @@ func (l *Conn) ModifyWithResult(modifyRequest *ModifyRequest) (*ModifyResult, er
return nil, err
}
if len(packet.Children) < 2 {
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
protocolOp, err := packetChild(packet, 1)
if err != nil {
return nil, err
}
switch packet.Children[1].Tag {
case ApplicationModifyResponse:
if protocolOp.Tag == ApplicationModifyResponse {
if err = GetLDAPError(packet); err != nil {
result.Referral = getReferral(err, packet)
return result, err
}
if len(packet.Children) == 3 {
for _, child := range packet.Children[2].Children {
controls, ok, err := packetChildIfPresent(packet, 2)
if err != nil {
return nil, err
}
if ok {
for _, child := range controls.Children {
decodedChild, err := DecodeControl(child)
if err != nil {
return nil, errors.New("failed to decode child control: " + err.Error())
@@ -182,6 +185,8 @@ 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
View File
@@ -0,0 +1,180 @@
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)
}
+29 -10
View File
@@ -93,29 +93,48 @@ func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*Pa
result := &PasswordModifyResult{}
if len(packet.Children) < 2 {
return nil, fmt.Errorf("ldap: malformed response: expected at least 2 children, got %d", len(packet.Children))
extendedResponse, err := packetChild(packet, 1)
if err != nil {
return nil, err
}
if packet.Children[1].Tag == ApplicationExtendedResponse {
if extendedResponse.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", packet.Children[1].Tag))
return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", extendedResponse.Tag))
}
extendedResponse := packet.Children[1]
for _, child := range extendedResponse.Children {
if child == nil {
continue
}
if child.Tag == ber.TagEmbeddedPDV {
passwordModifyResponseValue, err := ber.DecodePacketErr(child.Data.Bytes())
data, err := packetData(child)
if err != nil {
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %s", err)
return nil, fmt.Errorf("ldap: failed to decode PasswordModifyResponseValue: %w", err)
}
if len(passwordModifyResponseValue.Children) == 1 {
if passwordModifyResponseValue.Children[0].Tag == ber.TagEOC {
result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
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)
}
}
}
+13 -8
View File
@@ -76,7 +76,8 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
return ""
}
if len(packet.Children) < 2 {
protocolOp, perr := packetChild(packet, 1)
if perr != nil {
return ""
}
@@ -87,13 +88,17 @@ func getReferral(err error, packet *ber.Packet) (referral string) {
//
// Related Issues:
// - https://github.com/authelia/authelia/issues/4199 (downstream)
if len(packet.Children[1].Children) == 0 || (packet.Children[1].TagType != ber.TypeConstructed || packet.Children[1].ClassType != ber.ClassApplication) {
if protocolOp.TagType != ber.TypeConstructed || protocolOp.ClassType != ber.ClassApplication {
return ""
}
if _, err := packetChildCount(protocolOp, 1, -1, "referral"); err != nil {
return ""
}
var ok bool
for _, child := range packet.Children[1].Children {
for _, child := range protocolOp.Children {
if child == nil {
continue
}
// 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.
@@ -105,11 +110,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.
if len(child.Children) == 0 {
uriChild, err := packetChild(child, 0)
if err != nil {
continue
}
if referral, ok = child.Children[0].Value.(string); ok {
if referral, err := packetString(uriChild); err == nil {
return referral
}
}
+92 -33
View File
@@ -140,60 +140,48 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
ber.PrintPacket(packet)
}
switch packet.Children[1].Tag {
protocolOp, err := packetChild(packet, 1)
if err != nil {
r.send(ctx, &SearchSingleResult{Error: err})
return
}
switch protocolOp.Tag {
case ApplicationSearchResultEntry:
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])
result, err := decodeSearchResultEntry(packet)
if err != nil {
werr := fmt.Errorf("failed to decode search result entry: %w", err)
result.Error = werr
r.send(ctx, result)
r.send(ctx, &SearchSingleResult{Error: err})
return
}
result.Controls = append(result.Controls, decoded)
if !r.send(ctx, result) {
return
}
case ApplicationSearchResultDone:
if err := GetLDAPError(packet); err != nil {
result, err := decodeSearchResultDone(packet)
if err != nil {
r.send(ctx, &SearchSingleResult{Error: err})
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)
if result != nil {
if !r.send(ctx, result) {
return
}
r.send(ctx, result)
}
foundSearchSingleResultDone = true
case ApplicationSearchResultReference:
ref := packet.Children[1].Children[0].Value.(string)
ref, err := packetStringAt(protocolOp, 0)
if err != nil {
r.send(ctx, &SearchSingleResult{Error: err})
return
}
if !r.send(ctx, &SearchSingleResult{Referral: ref}) {
return
}
case ApplicationIntermediateResponse:
decoded, err := DecodeControl(packet.Children[1])
decoded, err := DecodeControl(protocolOp)
if err != nil {
werr := fmt.Errorf("failed to decode intermediate response: %w", err)
r.send(ctx, &SearchSingleResult{Error: werr})
@@ -206,7 +194,7 @@ func (r *searchResponse) start(ctx context.Context, searchRequest *SearchRequest
}
default:
err := fmt.Errorf("unknown tag: %d", packet.Children[1].Tag)
err := fmt.Errorf("unknown tag: %d", protocolOp.Tag)
r.send(ctx, &SearchSingleResult{Error: err})
return
}
@@ -216,6 +204,77 @@ 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 {
+101 -25
View File
@@ -245,7 +245,7 @@ func readTag(f reflect.StructField) (string, bool) {
// if err := result.Unmarshal(&user); err != nil {
// // ...
// }
func (e *Entry) Unmarshal(i interface{}) (err error) {
func (e *Entry) Unmarshal(i any) (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 interface{}) (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 interface{},
func (e *Entry) UnmarshalFunc(i any,
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.Ptr {
if vo := reflect.ValueOf(i).Kind(); vo != reflect.Pointer {
return fmt.Errorf("ldap: cannot use %s, expected pointer to a struct", vo)
}
@@ -377,6 +377,22 @@ 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
@@ -398,6 +414,8 @@ 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
@@ -583,7 +601,12 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
return result, err
}
switch packet.Children[1].Tag {
protocolOp, err := packetChild(packet, 1)
if err != nil {
return result, err
}
switch protocolOp.Tag {
case 4:
if searchRequest.EnforceSizeLimit &&
searchRequest.SizeLimit > 0 &&
@@ -591,32 +614,59 @@ func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
return result, ErrSizeLimitExceeded
}
attr := make([]*ber.Packet, 0)
if len(packet.Children[1].Children) > 1 {
attr = packet.Children[1].Children[1].Children
// 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
}
entry := &Entry{
DN: packet.Children[1].Children[0].Value.(string),
Attributes: unpackAttributes(attr),
DN: dn,
Attributes: attributes,
}
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
}
if len(packet.Children) == 3 {
for _, child := range packet.Children[2].Children {
controlsChild, ok, err := packetChildIfPresent(packet, 2)
if err != nil {
return result, err
}
if ok {
for _, child := range controlsChild.Children {
decodedChild, err := DecodeControl(child)
if err != nil {
return result, fmt.Errorf("failed to decode child control: %s", err)
return result, fmt.Errorf("failed to decode child control: %w", err)
}
result.Controls = append(result.Controls, decodedChild)
}
}
return result, nil
case 19:
result.Referrals = append(result.Referrals, packet.Children[1].Children[0].Value.(string))
ref, err := packetStringAt(protocolOp, 0)
if err != nil {
return result, err
}
result.Referrals = append(result.Referrals, ref)
}
}
}
@@ -653,26 +703,52 @@ 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 {
entries := make([]*EntryAttribute, len(children))
for i, child := range children {
length := len(child.Children[1].Children)
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
entry := &EntryAttribute{
Name: child.Children[0].Value.(string),
Name: name,
// pre-allocate the slice since we can determine
// the number of attributes at this point
Values: make([]string, length),
ByteValues: make([][]byte, length),
Values: make([]string, len(values)),
ByteValues: make([][]byte, len(values)),
}
for i, value := range child.Children[1].Children {
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)
}
entry.ByteValues[i] = value.ByteValue
entry.Values[i] = value.Value.(string)
entry.Values[i] = v
}
entries[i] = entry
entries = append(entries, entry)
}
return entries
return entries, nil
}
// DirSync does a Search with dirSync Control.
@@ -717,7 +793,7 @@ func (l *Conn) DirSync(
return searchResult, nil
}
// DirSyncDirSyncAsync performs a search request and returns all search results
// DirSyncAsync 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,
+30 -5
View File
@@ -95,6 +95,11 @@ 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
@@ -284,7 +289,9 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
minIndex := max(pos-windowSize, 0)
offset = 0
if d.chain < 100 {
// The gain estimate below needs the tables that deflateLazy only
// generates when d.chain > 100, so the conditions must match.
if d.chain <= 100 {
for i := prevHead; tries > 0; tries-- {
if wEnd == win[i+length] {
n := matchLen(win[i:i+minMatchLook], wPos)
@@ -312,21 +319,25 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of
}
// Minimum gain to accept a match.
cGain := 4
cGain := int32(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 := d.h.bitLengthRaw(wPos[:n]) - int(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int(lengthExtraBits[lengthCodes[(n-3)&255]])
newGain := litBits[n] - litBits[0] - int32(offsetExtraBits[offsetCode(uint32(pos-i))]) - baseCost - int32(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
@@ -344,7 +355,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(d.state.hashPrev[i&windowMask]) - d.state.hashOffset
i = int(hashPrev[i&windowMask]) - hashOffset
if i < minIndex {
break
}
@@ -428,6 +439,20 @@ 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)
+94 -128
View File
@@ -32,14 +32,12 @@ const (
// bufferFlushSize indicates the buffer size
// after which bytes are flushed to the writer.
// Should preferably be a multiple of 6, since
// we accumulate 6 bytes between writes to the buffer.
// 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.
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,
@@ -55,9 +53,6 @@ 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,
@@ -67,8 +62,24 @@ 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 */
@@ -85,7 +96,7 @@ func init() {
for i := range offsetCombined[:] {
// Don't use extended window values...
if offsetExtraBits[i] == 0 || offsetBase[i] > 0x006000 {
if offsetBase[i] > 0x006000 {
continue
}
offsetCombined[i] = uint32(offsetExtraBits[i]) | (offsetBase[i] << 8)
@@ -115,10 +126,14 @@ type huffmanBitWriter struct {
lastHeader int
// Set between 0 (reused block can be up to 2x the size)
logNewTablePenalty uint
bytes [256 + 8]byte
literalFreq [lengthCodesStart + 32]uint16
offsetFreq [32]uint16
codegenFreq [codegenCodeCount]uint16
// 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
// codegen must have an extra space for the final symbol.
codegen [literalCount + offsetCodeCount + 1]uint8
@@ -842,124 +857,75 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode)
lengths := leCodes[lengthCodesStart:]
lengths = lengths[:32]
// Go 1.16 LOVES having these on stack.
// Keeping these on the stack instead of in w is significantly faster.
bits, nbits, nbytes := w.bits, w.nbits, w.nbytes
for _, t := range tokens {
// 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]
if t < 256 {
//w.writeCode(lits[t.literal()])
c := lits[t]
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
// 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()
}
}
continue
}
// 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
}
}
}
// 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
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 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)
}
// 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
}
le.Store64(w.bytes[:], nbytes, bits)
nbytes += nbits >> 3
bits >>= nbits & 56
nbits &= 7
if nbytes >= bufferFlushSize {
if w.err != nil {
nbytes = 0
return
}
_, w.err = w.writer.Write(w.bytes[:nbytes])
nbytes = 0
}
}
// Restore...
@@ -1094,8 +1060,8 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
if debugDeflate {
count -= int(nbytes)*8 + int(nbits)
}
// Unroll, write 3 codes/loop.
// Fastest number of unrolls.
// Write 3 codes per iteration. The three codes are combined first,
// independently of the accumulator, and merged with a single shift.
for len(input) > 3 {
// We must have at least 48 bits free.
if nbits >= 8 {
@@ -1116,13 +1082,13 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) {
_, w.err = w.writer.Write(w.bytes[:nbytes])
nbytes = 0
}
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()
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
input = input[3:]
}
+102 -36
View File
@@ -38,6 +38,9 @@ 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 {
@@ -139,14 +142,6 @@ 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
@@ -309,27 +304,93 @@ 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
func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) {
code := uint16(0)
// 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.
for n, bits := range bitCount {
code <<= 1
if n == 0 || bits == 0 {
continue
}
// 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++
for _, node := range list[len(list)-int(bits):] {
codes[node.literal] = hcode(n)
}
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.
@@ -362,12 +423,14 @@ func (h *huffmanEncoder) generate(freq []uint16, maxBits int32) {
}
return
}
sortByFreq(list)
// list is in order of increasing literal value, so a stable sort
// by frequency orders it by (frequency, literal).
h.sortByFreq(list)
// Get the number of literals for each bit count
bitCount := h.bitCounts(list, maxBits)
// And do the assignment
h.assignEncodingAndSize(bitCount, list)
h.assignEncodingAndSize(bitCount, list, codes)
}
// atLeastOne clamps the result between 1 and 15.
@@ -394,24 +457,27 @@ func histogram(b []byte, h []uint16) {
}
func histogramSplit(b []byte, h []uint16) {
// Tested, and slightly faster than 2-way.
// Writing to separate arrays and combining is also slightly slower.
h = h[:256]
// 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
for len(b)&3 != 0 {
h[b[0]]++
h0[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 {
v0 := &h[t]
v1 := &h[y[i]]
v2 := &h[z[i]]
v3 := &h[w[i]]
*v0++
*v1++
*v2++
*v3++
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]
}
}
+15 -15
View File
@@ -120,7 +120,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -148,7 +148,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -216,7 +216,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -371,7 +371,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -399,7 +399,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -467,7 +467,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -638,7 +638,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
f.err = noEOF(err)
return
}
}
@@ -674,7 +674,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
f.err = noEOF(err)
return
}
}
@@ -757,7 +757,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
f.err = noEOF(err)
return
}
}
@@ -918,7 +918,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -946,7 +946,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -1014,7 +1014,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -1169,7 +1169,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits n>0:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -1197,7 +1197,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<5:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
@@ -1265,7 +1265,7 @@ readLiteral:
if debugDecode {
fmt.Println("morebits f.nb<nb:", err)
}
f.err = err
f.err = noEOF(err)
return
}
f.roffset++
+6 -7
View File
@@ -12,18 +12,17 @@ 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) {
left := len(a)
for left >= 8 {
diff := le.Load64(a, n) ^ le.Load64(b, n)
// 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)
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
+11 -7
View File
@@ -215,7 +215,11 @@ func mFastLog2(val float32) float32 {
ux &= -0x7f800001
ux += 127 << 23
uval := math.Float32frombits(uint32(ux))
log2 += ((-0.34484843)*uval+2.02466578)*uval - 0.67487759
p := float32(-0.34484843*uval) + 2.02466578
q := float32(p*uval) - 0.67487759
log2 += q
return log2
}
@@ -232,7 +236,8 @@ func (t *tokens) EstimatedBits() int {
for _, v := range t.litHist[:] {
if v > 0 {
n := float32(v)
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
shannon += w
}
}
// Just add 15 for EOB
@@ -240,7 +245,8 @@ func (t *tokens) EstimatedBits() int {
for i, v := range t.extraHist[1 : literalCount-256] {
if v > 0 {
n := float32(v)
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
shannon += w
bits += int(lengthExtraBits[i&31]) * int(v)
nMatches += int(v)
}
@@ -251,7 +257,8 @@ func (t *tokens) EstimatedBits() int {
for i, v := range t.offHist[:offsetCodeCount] {
if v > 0 {
n := float32(v)
shannon += atLeastOne(-mFastLog2(n*invTotal)) * n
w := float32(atLeastOne(-mFastLog2(n*invTotal)) * n)
shannon += w
bits += int(offsetExtraBits[i&31]) * int(v)
}
}
@@ -358,9 +365,6 @@ 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
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
"math/bits"
"github.com/klauspost/compress/internal/le"
)
@@ -210,6 +211,68 @@ 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.
+87 -8
View File
@@ -8,36 +8,99 @@ import (
)
// decompress4x_main_loop_amd64 is an x86 assembler implementation
// of Decompress4X when tablelog > 8.
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
// stream between bit container reloads.
//
//go:noescape
func decompress4x_main_loop_amd64(ctx *decompress4xContext)
// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation
// of Decompress4X when tablelog <= 8 which decodes 4 entries
// per loop.
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
// per stream between bit container reloads.
//
//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.
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
// between bit container reloads.
//
//go:noescape
func decompress1x_main_loop_amd64(ctx *decompress1xContext)
// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation
// of Decompress1X when tablelog > 8.
// 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.
//
//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) {
decompress4x_main_loop_amd64(ctx)
if cpuinfo.HasBMI2() {
decompress4x_main_loop_bmi2(ctx)
} else {
decompress4x_main_loop_amd64(ctx)
}
}
func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
decompress4x_8b_main_loop_amd64(ctx)
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)
}
}
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
@@ -47,3 +110,19 @@ 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)
}
}
File diff suppressed because it is too large. Load diff
+39 -4
View File
@@ -6,24 +6,47 @@
package huff0
// decompress4x_main_loop_arm64 is an arm64 assembler implementation
// of Decompress4X when tablelog > 8.
// of Decompress4X when tablelog > 8, decoding fastSymbols symbols per
// stream between bit container reloads.
//
//go:noescape
func decompress4x_main_loop_arm64(ctx *decompress4xContext)
// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation
// of Decompress4X when tablelog <= 8 which decodes 4 entries
// per loop.
// of Decompress4X when tablelog <= 8, decoding fast8bSymbols symbols
// per stream between bit container reloads.
//
//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.
// of Decompress1X when tablelog > 8, decoding fastSymbols symbols
// between bit container reloads.
//
//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)
}
@@ -32,6 +55,18 @@ 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)
}
File diff suppressed because it is too large. Load diff
+79 -19
View File
@@ -14,6 +14,10 @@ import (
// fallback8BitSize is the size where using Go version is faster.
const fallback8BitSize = 800
// decompress4xContext is the argument block of the Decompress4X asm loops.
// Go fills every field but decoded and inner; the asm advances ip, and on
// return leaves each bit reader in the form bitReaderShifted.restoreFromAsm
// expects.
type decompress4xContext struct {
pbr *[4]bitReaderShifted
peekBits uint8
@@ -21,9 +25,20 @@ type decompress4xContext struct {
dstEvery int
tbl *dEntrySingle
decoded int
limit *byte
limit *byte // stream 0's output pointer must stay below this
ilowest *byte // start of the input block; no read goes below it
ip [4]*byte // each stream's 8-byte input window, advanced by the asm
inner *byte // scratch for the asm: the current inner-loop limit
}
// Symbols decoded per stream between reloads by the 4X asm loops; must
// match the constants of the same names in _generate/gen.go.
const (
fastSymbols = 5 // tablelog 9..11
fast8bSymbols = 7 // tablelog 5..8
fast4bSymbols = 14 // tablelog <= 4
)
// Decompress4X will decompress a 4X encoded stream.
// The length of the supplied input must match the end of a block exactly.
// The *capacity* of the dst slice must match the destination size of
@@ -72,23 +87,55 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
var decoded int
if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) {
nSyms := fastSymbols
if d.actualTableLog <= 4 {
nSyms = fast4bSymbols
} else if use8BitTables {
nSyms = fast8bSymbols
}
// The asm writes nSyms bytes per stream per iteration and only re-checks
// its bounds between batches of iterations (the batch size is derived
// from limit in _generate/gen.go), so stream 0 must stop early enough
// that stream 3 (which may be up to 3 bytes shorter than dstEvery)
// never writes past the end of out. Every stream needs a full 8-byte
// window ahead of its read pointer to enter the loop.
if limit := dstEvery - nSyms - 2; limit > 0 && br[0].canUseAsm() && br[1].canUseAsm() && br[2].canUseAsm() && br[3].canUseAsm() {
for i := range br {
br[i].prepareForAsm()
}
ctx := decompress4xContext{
pbr: &br,
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
out: &out[0],
dstEvery: dstEvery,
tbl: &single[0],
limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last.
limit: &out[limit],
// The 6-byte jump table sits below stream 0 inside src, so the
// lowest window may reach into it; restoreFromAsm accounts for
// bytes below a stream's start. Bounding by src rather than by
// stream 0 keeps the asm running about six bytes longer, which
// matters for streams with very short codes.
ilowest: &src[0],
}
if use8BitTables {
for i := range br {
ctx.ip[i] = &br[i].in[br[i].off]
}
switch nSyms {
case fast4bSymbols:
decompress4x_4b_main_loop_asm(&ctx)
case fast8bSymbols:
decompress4x_8b_main_loop_asm(&ctx)
} else {
default:
decompress4x_main_loop_asm(&ctx)
}
decoded = ctx.decoded
out = out[decoded/4:]
for i := range br {
if err := br[i].restoreFromAsm(); err != nil {
return nil, err
}
}
}
// Decode remaining.
@@ -128,18 +175,20 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
return dst, nil
}
// decompress1xContext is the argument block of the Decompress1X asm loops.
// Go fills every field but decoded; the asm advances ip, and on return
// leaves the bit reader in the form bitReaderShifted.restoreFromAsm expects.
type decompress1xContext struct {
pbr *bitReaderShifted
peekBits uint8
out *byte
outCap int
outCap int // no write reaches out[outCap]
tbl *dEntrySingle
decoded int
ilowest *byte // start of the stream; no read goes below it
ip *byte // the 8-byte input window, advanced by the asm
}
// Error reported by asm implementations
const error_max_decoded_size_exeeded = -1
// Decompress1X will decompress a 1X encoded stream.
// The cap of the output buffer will be the maximum decompressed size.
// The length of the supplied input must match the end of a block exactly.
@@ -158,25 +207,36 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
const tlSize = 1 << tableLogMax
const tlMask = tlSize - 1
if maxDecodedSize >= 4 {
// The asm decodes whole batches of symbols and only re-checks its
// bounds between them, so it needs at least one batch of room (the
// output bound rounds nSyms up to 16, see _generate/gen.go) and a full
// 8-byte window ahead of the read pointer to enter the loop. It also
// needs at most 7 bits consumed on entry so that a batch cannot run
// the container dry, which prepareForAsm establishes.
decoded := 0
if maxDecodedSize >= 16 && br.canUseAsm() {
br.prepareForAsm()
ctx := decompress1xContext{
pbr: &br,
out: &dst[0],
outCap: maxDecodedSize,
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
tbl: &d.dt.single[0],
ilowest: &src[0],
ip: &br.in[br.off],
}
decompress1x_main_loop_asm(&ctx)
if ctx.decoded == error_max_decoded_size_exeeded {
return nil, ErrMaxDecodedSizeExceeded
if d.actualTableLog <= 4 {
decompress1x_4b_main_loop_asm(&ctx)
} else if d.actualTableLog <= 8 {
decompress1x_8b_main_loop_asm(&ctx)
} else {
decompress1x_main_loop_asm(&ctx)
}
dst = dst[:ctx.decoded]
decoded = ctx.decoded
}
dst = dst[:decoded]
// br < 8, so uint8 is fine
bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead
bitsLeft := br.remaining()
for bitsLeft > 0 {
br.fill()
if len(dst) >= maxDecodedSize {
@@ -186,7 +246,7 @@ func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask]
nBits := uint8(v.entry)
br.advance(nBits)
bitsLeft -= nBits
bitsLeft -= uint(nBits)
dst = append(dst, uint8(v.entry>>8))
}
return dst, br.close()
+2 -2
View File
@@ -151,7 +151,7 @@ func (i *Index) reduce() {
i.estBlockUncomp += i.estBlockUncomp * int64(removeN)
}
func (i *Index) appendTo(b []byte, uncompTotal, compTotal int64) []byte {
func (i *Index) appendTo(b []byte, compTotal, uncompTotal int64) []byte {
i.reduce()
var tmp [binary.MaxVarintLen64]byte
@@ -425,7 +425,7 @@ func IndexStream(r io.Reader) ([]byte, error) {
_, err := io.ReadFull(r, buf[:4])
if err != nil {
if err == io.EOF {
return i.appendTo(nil, i.TotalUncompressed, i.TotalCompressed), nil
return i.appendTo(nil, i.TotalCompressed, i.TotalUncompressed), nil
}
return nil, err
}
+1 -1
View File
@@ -809,7 +809,7 @@ func (w *Writer) closeIndex(idx bool) ([]byte, error) {
if w.pad <= 1 {
compSize = w.written
}
index = w.index.appendTo(w.ibuf[:0], w.uncompWritten, compSize)
index = w.index.appendTo(w.ibuf[:0], compSize, w.uncompWritten)
// Count as written for padding.
if w.appendIndex {
w.written += int64(len(index))
+3
View File
@@ -240,9 +240,11 @@ func (b *blockDec) decodeBuf(hist *history) error {
b.dst[i] = v
}
hist.appendKeep(b.dst)
hist.decoders.consumeSyncLen(len(b.dst))
return nil
case blockTypeRaw:
hist.appendKeep(b.data)
hist.decoders.consumeSyncLen(len(b.data))
return nil
case blockTypeCompressed:
saved := b.dst
@@ -487,6 +489,7 @@ func (b *blockDec) decodeCompressed(hist *history) error {
}
if hist.decoders.nSeqs == 0 {
b.dst = append(b.dst, hist.decoders.literals...)
hist.decoders.consumeSyncLen(len(hist.decoders.literals))
return nil
}
before := len(hist.decoders.out)
+81 -44
View File
@@ -7,8 +7,11 @@ package zstd
import (
"context"
"encoding/binary"
"errors"
"io"
"maps"
"sync"
"sync/atomic"
"github.com/klauspost/compress/zstd/internal/xxhash"
)
@@ -20,7 +23,8 @@ import (
// A decoder can safely be re-used even if the previous stream failed.
// To release the resources, you must call the Close() function on a decoder.
type Decoder struct {
o decoderOptions
// publishedOptions contains the current immutable decoder options.
publishedOptions atomic.Pointer[decoderOptions]
// Unreferenced decoders, ready for use.
decoders chan *blockDec
@@ -84,9 +88,10 @@ var (
func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {
initPredefined()
var d Decoder
d.o.setDefault()
for _, o := range opts {
err := o(&d.o)
var o decoderOptions
o.setDefault()
for _, opt := range opts {
err := opt(&o)
if err != nil {
return nil, err
}
@@ -99,17 +104,19 @@ func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) {
}
// Initialize dict map if needed.
if d.o.dicts == nil {
d.o.dicts = make(map[uint32]*dict)
if o.dicts == nil {
o.dicts = make(map[uint32]*dict)
}
// Create decoders
d.decoders = make(chan *blockDec, d.o.concurrent)
for i := 0; i < d.o.concurrent; i++ {
dec := newBlockDec(d.o.lowMem)
dec.localFrame = newFrameDec(d.o)
d.decoders = make(chan *blockDec, o.concurrent)
for i := 0; i < o.concurrent; i++ {
dec := newBlockDec(o.lowMem)
dec.localFrame = newFrameDec(o)
dec.localFrame.o.dicts = nil
d.decoders <- dec
}
d.publishedOptions.Store(&o)
if r == nil {
return &d, nil
@@ -171,6 +178,9 @@ func (d *Decoder) Reset(r io.Reader) error {
d.drainOutput()
d.syncStream.br.r = nil
if d.frame != nil {
d.frame.o.dicts = nil
}
if r == nil {
d.current.err = ErrDecoderNilInput
if len(d.current.b) > 0 {
@@ -180,8 +190,10 @@ func (d *Decoder) Reset(r io.Reader) error {
return nil
}
o := *d.publishedOptions.Load()
// If bytes buffer and < 5MB, do sync decoding anyway.
if bb, ok := r.(byter); ok && bb.Len() < d.o.decodeBufsBelow && !d.o.limitToCap {
if bb, ok := r.(byter); ok && bb.Len() < o.decodeBufsBelow && !o.limitToCap {
bb2 := bb
if debugDecoder {
println("*bytes.Buffer detected, doing sync decode, len:", bb.Len())
@@ -193,18 +205,30 @@ func (d *Decoder) Reset(r io.Reader) error {
}
dst, err := d.DecodeAll(b, dst)
if err == nil {
err = io.EOF
if !errors.Is(err, ErrDecoderSizeExceeded) {
if err == nil {
err = io.EOF
}
// Save output buffer
d.syncStream.dstBuf = dst
d.current.b = dst
d.current.err = err
d.current.flushed = true
if debugDecoder {
println("sync decode to", len(dst), "bytes, err:", err)
}
return nil
}
// Save output buffer
d.syncStream.dstBuf = dst
d.current.b = dst
d.current.err = err
d.current.flushed = true
// The output does not fit WithDecoderMaxMemory, which caps the total
// decoded size when decoding in memory. A Reader follows the
// streaming contract, where the option caps the window instead, so
// decode this input as a stream after all; the shortcut has not
// consumed the reader. Drop the oversized buffer rather than keep it
// for reuse.
if debugDecoder {
println("sync decode to", len(dst), "bytes, err:", err)
println("sync decode exceeded max memory after", len(dst), "bytes; streaming instead")
}
return nil
d.syncStream.dstBuf = nil
}
// Remove current block.
d.stashDecoder()
@@ -217,14 +241,16 @@ func (d *Decoder) Reset(r io.Reader) error {
// Ensure no-one else is still running...
d.streamWg.Wait()
if d.frame == nil {
d.frame = newFrameDec(d.o)
d.frame = newFrameDec(o)
} else {
d.frame.setOptions(o)
}
if d.o.concurrent == 1 {
if o.concurrent == 1 {
return d.startSyncDecoder(r)
}
d.current.output = make(chan decodeOutput, d.o.concurrent)
d.current.output = make(chan decodeOutput, o.concurrent)
ctx, cancel := context.WithCancel(context.Background())
d.current.cancel = cancel
d.streamWg.Add(1)
@@ -238,13 +264,21 @@ func (d *Decoder) Reset(r io.Reader) error {
// Options are applied on top of the existing options.
// Some options cannot be changed on reset and will return an error.
func (d *Decoder) ResetWithOptions(r io.Reader, opts ...DOption) error {
d.o.resetOpt = true
defer func() { d.o.resetOpt = false }()
if d.current.err == ErrDecoderClosed {
return d.current.err
}
next := *d.publishedOptions.Load()
next.dicts = maps.Clone(next.dicts)
next.resetOpt = true
for _, o := range opts {
if err := o(&d.o); err != nil {
if err := o(&next); err != nil {
next.resetOpt = false
d.publishedOptions.Store(&next)
return err
}
}
next.resetOpt = false
d.publishedOptions.Store(&next)
return d.Reset(r)
}
@@ -324,6 +358,8 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
// Grab a block decoder and frame decoder.
block := <-d.decoders
frame := block.localFrame
o := *d.publishedOptions.Load()
frame.setOptions(o)
initialSize := len(dst)
defer func() {
if debugDecoder {
@@ -335,6 +371,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
frame.history.decoders.br.in = nil
frame.history.decoders.br.cursor = 0
}
frame.o.dicts = nil
d.decoders <- block
}()
frame.bBuf = input
@@ -354,20 +391,20 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
if err = d.setDict(frame); err != nil {
return nil, err
}
if frame.WindowSize > d.o.maxWindowSize {
if frame.WindowSize > frame.o.maxWindowSize {
if debugDecoder {
println("window size exceeded:", frame.WindowSize, ">", d.o.maxWindowSize)
println("window size exceeded:", frame.WindowSize, ">", frame.o.maxWindowSize)
}
return dst, ErrWindowSizeExceeded
}
if frame.FrameContentSize != fcsUnknown {
if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)-initialSize) {
if frame.FrameContentSize > frame.o.maxDecodedSize-uint64(len(dst)-initialSize) {
if debugDecoder {
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", d.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst))
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> mcs:", frame.o.maxDecodedSize-uint64(len(dst)-initialSize), "len:", len(dst))
}
return dst, ErrDecoderSizeExceeded
}
if d.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) {
if frame.o.limitToCap && frame.FrameContentSize > uint64(cap(dst)-len(dst)) {
if debugDecoder {
println("decoder size exceeded; fcs:", frame.FrameContentSize, "> (cap-len)", cap(dst)-len(dst))
}
@@ -380,14 +417,14 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
}
}
if cap(dst) == 0 && !d.o.limitToCap {
if cap(dst) == 0 && !frame.o.limitToCap {
// Allocate len(input) * 2 by default if nothing is provided
// and we didn't get frame content size.
size := min(
// Cap to 1 MB.
len(input)*2, 1<<20)
if uint64(size) > d.o.maxDecodedSize {
size = int(d.o.maxDecodedSize)
if uint64(size) > frame.o.maxDecodedSize {
size = int(frame.o.maxDecodedSize)
}
dst = make([]byte, 0, size)
}
@@ -396,7 +433,7 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) {
if err != nil {
return dst, err
}
if uint64(len(dst)-initialSize) > d.o.maxDecodedSize {
if uint64(len(dst)-initialSize) > frame.o.maxDecodedSize {
return dst, ErrDecoderSizeExceeded
}
if len(frame.bBuf) == 0 {
@@ -459,7 +496,7 @@ func (d *Decoder) nextBlock(blocking bool) (ok bool) {
println("got", len(d.current.b), "bytes, error:", d.current.err, "data crc:", tmp)
}
if d.o.ignoreChecksum {
if d.frame.o.ignoreChecksum {
return true
}
@@ -497,7 +534,7 @@ func (d *Decoder) nextBlockSync() (ok bool) {
if d.current.err != nil {
return false
}
if d.frame.WindowSize > d.o.maxDecodedSize || d.frame.WindowSize > d.o.maxWindowSize {
if d.frame.WindowSize > d.frame.o.maxDecodedSize || d.frame.WindowSize > d.frame.o.maxWindowSize {
d.current.err = ErrDecoderSizeExceeded
return false
}
@@ -546,11 +583,11 @@ func (d *Decoder) nextBlockSync() (ok bool) {
// Update/Check CRC
if d.frame.HasCheckSum {
if !d.o.ignoreChecksum {
if !d.frame.o.ignoreChecksum {
d.frame.crc.Write(d.current.b)
}
if d.current.d.Last {
if !d.o.ignoreChecksum {
if !d.frame.o.ignoreChecksum {
d.current.err = d.frame.checkCRC()
} else {
d.current.err = d.frame.consumeCRC()
@@ -656,8 +693,8 @@ func (d *Decoder) startStreamDecoder(ctx context.Context, r io.Reader, output ch
defer d.streamWg.Done()
br := readerWrapper{r: r}
var seqDecode = make(chan *blockDec, d.o.concurrent)
var seqExecute = make(chan *blockDec, d.o.concurrent)
var seqDecode = make(chan *blockDec, d.frame.o.concurrent)
var seqExecute = make(chan *blockDec, d.frame.o.concurrent)
// Async 1: Decode sequences...
go func() {
@@ -858,9 +895,9 @@ decodeStream:
if err == nil {
err = d.setDict(frame)
}
if err == nil && d.frame.WindowSize > d.o.maxWindowSize {
if err == nil && d.frame.WindowSize > d.frame.o.maxWindowSize {
if debugDecoder {
println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.o.maxWindowSize)
println("decoder size exceeded, fws:", d.frame.WindowSize, "> mws:", d.frame.o.maxWindowSize)
}
err = ErrDecoderSizeExceeded
@@ -940,7 +977,7 @@ decodeStream:
}
func (d *Decoder) setDict(frame *frameDec) (err error) {
dict, ok := d.o.dicts[frame.DictionaryID]
dict, ok := frame.o.dicts[frame.DictionaryID]
if ok {
if debugDecoder {
println("setting dict", frame.DictionaryID)
+7 -4
View File
@@ -49,13 +49,16 @@ const (
)
func newFrameDec(o decoderOptions) *frameDec {
d := frameDec{}
d.setOptions(o)
return &d
}
func (d *frameDec) setOptions(o decoderOptions) {
if o.maxWindowSize > o.maxDecodedSize {
o.maxWindowSize = o.maxDecodedSize
}
d := frameDec{
o: o,
}
return &d
d.o = o
}
// reset will read the frame header and prepare for block decoding.
+4 -6
View File
@@ -47,12 +47,10 @@ init_main_loop_condition:
// Spread symbols
// Calculate table step
MOVD R0, R8
LSR $0x01, R8, R8
MOVD R0, R9
LSR $0x03, R9, R9
ADD R9, R8, R8
ADD $3, R8, R8
LSR $0x01, R0, R8
LSR $0x03, R0, R9
ADD R9, R8, R8
ADD $3, R8, R8
// Fill add bits values
SUB $1, R0, R9
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff. Show more