diff --git a/.forgejo/actions/create-docker-manifest/action.yml b/.forgejo/actions/create-docker-manifest/action.yml index a04df94d7..a5151f9fa 100644 --- a/.forgejo/actions/create-docker-manifest/action.yml +++ b/.forgejo/actions/create-docker-manifest/action.yml @@ -44,7 +44,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/prepare-docker-build/action.yml b/.forgejo/actions/prepare-docker-build/action.yml index 81d168e3f..baef6eb9f 100644 --- a/.forgejo/actions/prepare-docker-build/action.yml +++ b/.forgejo/actions/prepare-docker-build/action.yml @@ -79,7 +79,7 @@ runs: - name: Login to builtin registry if: ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' }} - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 with: registry: ${{ env.BUILTIN_REGISTRY }} username: ${{ inputs.registry_user }} diff --git a/.forgejo/actions/sccache/action.yml b/.forgejo/actions/sccache/action.yml index f84b4410e..3e0fbd540 100644 --- a/.forgejo/actions/sccache/action.yml +++ b/.forgejo/actions/sccache/action.yml @@ -7,7 +7,7 @@ runs: using: composite steps: - name: Install sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: Configure sccache uses: https://github.com/actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: diff --git a/.forgejo/actions/setup-llvm-with-apt/action.yml b/.forgejo/actions/setup-llvm-with-apt/action.yml index a24c9a8b3..4deec4493 100644 --- a/.forgejo/actions/setup-llvm-with-apt/action.yml +++ b/.forgejo/actions/setup-llvm-with-apt/action.yml @@ -29,7 +29,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Configure cross-compilation architecture if: inputs.dpkg-arch != '' diff --git a/.forgejo/actions/setup-rust/action.yml b/.forgejo/actions/setup-rust/action.yml index 70b9f2892..a6d3988a5 100644 --- a/.forgejo/actions/setup-rust/action.yml +++ b/.forgejo/actions/setup-rust/action.yml @@ -39,7 +39,7 @@ runs: steps: - name: Detect runner OS id: runner-os - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Configure Cargo environment shell: bash @@ -147,7 +147,7 @@ runs: run: echo "::group::📦 Restoring build cache" - name: Setup sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: End build cache restore group shell: bash diff --git a/.forgejo/actions/timelord/action.yml b/.forgejo/actions/timelord/action.yml index b03254be0..ab1746a57 100644 --- a/.forgejo/actions/timelord/action.yml +++ b/.forgejo/actions/timelord/action.yml @@ -71,7 +71,7 @@ runs: - name: Install timelord-cli and git-warp-time if: steps.check-binaries.outputs.need-install == 'true' - uses: https://github.com/taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2 + uses: https://github.com/taiki-e/install-action@ab49d3c64680143e184118bed66a46419fc15519 # v2 with: tool: git-warp-time,timelord-cli@3.0.1 diff --git a/.forgejo/workflows/auto-labeler.yml b/.forgejo/workflows/auto-labeler.yml index 71b59eb19..af345b215 100644 --- a/.forgejo/workflows/auto-labeler.yml +++ b/.forgejo/workflows/auto-labeler.yml @@ -4,11 +4,6 @@ on: pull_request_target: types: [opened, reopened] -permissions: - contents: read - pull-requests: write - issues: write - jobs: auto-label: name: Apply labels based on changed files diff --git a/.forgejo/workflows/build-debian.yml b/.forgejo/workflows/build-debian.yml index 8e3094cff..15440b653 100644 --- a/.forgejo/workflows/build-debian.yml +++ b/.forgejo/workflows/build-debian.yml @@ -60,7 +60,7 @@ jobs: cargo-debian-${{ steps.debian-version.outputs.distribution }}-${{ matrix.arch }}- - name: Setup sccache - uses: https://git.tomfos.tr/tom/sccache-action@v1 + uses: https://forgejo.ellis.link/continuwuation/sccache-action@b5ae5b4541ed5fb0f616e3cb616bf213fefa1c40 # v1 - name: Configure sccache environment run: | diff --git a/.forgejo/workflows/build-nix.yml b/.forgejo/workflows/build-nix.yml index ee16f0d25..6370e8ec7 100644 --- a/.forgejo/workflows/build-nix.yml +++ b/.forgejo/workflows/build-nix.yml @@ -54,8 +54,6 @@ jobs: runs-on: ubuntu-latest needs: - build - permissions: - contents: write if: startsWith(github.ref, 'refs/tags/') steps: - name: Download binary artifacts @@ -65,7 +63,7 @@ jobs: path: binaries merge-multiple: true - name: Create Release and Upload - uses: https://github.com/softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + uses: https://github.com/softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: draft: true files: binaries/* diff --git a/.forgejo/workflows/check-changelog.yml b/.forgejo/workflows/check-changelog.yml index eb4ecb66a..c67fc9de2 100644 --- a/.forgejo/workflows/check-changelog.yml +++ b/.forgejo/workflows/check-changelog.yml @@ -4,11 +4,6 @@ on: pull_request_target: types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled] -permissions: - contents: read - pull-requests: write - issues: write - jobs: check-changelog: name: Check changelog is added diff --git a/.forgejo/workflows/documentation.yml b/.forgejo/workflows/documentation.yml index d6113a210..57cfb3de7 100644 --- a/.forgejo/workflows/documentation.yml +++ b/.forgejo/workflows/documentation.yml @@ -28,13 +28,13 @@ jobs: - name: Detect runner environment id: runner-env - uses: https://git.tomfos.tr/actions/detect-versions@v1 + uses: https://forgejo.ellis.link/continuwuation/detect-versions@d39555789fed25b8eb8e086d9f199c514dfa311e # v1 - name: Setup Node.js if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20' uses: https://github.com/actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version: 24 + node-version: 26 - name: Cache npm dependencies uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 @@ -49,6 +49,8 @@ jobs: run: npm ci - name: Build Rspress documentation + env: + SITE_PATH: ${{ github.ref != 'refs/heads/main' && format('/pr/{0}/', '${{ forgejo.event.number }}') || '/' }} run: npm run docs:build - name: Install Wrangler @@ -62,10 +64,16 @@ jobs: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}" - - name: Deploy to Cloudflare Pages (Preview) - if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != '' - uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4 + - name: Deploy to Grebedoc (Preview) + if: github.ref != 'refs/heads/main' + uses: actions/git-pages@v2 with: - accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} - command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}" + site: https://preview.continuwuity.org + path: "pr/${{ forgejo.event.number }}" + server: grebedoc.dev + token: ${{ forgejo.token }} + source: doc_build/ + strict: true + pretty-urls: true + expires: 14 + comment: ${{ forgejo.sha }} diff --git a/.forgejo/workflows/prek-checks.yml b/.forgejo/workflows/prek-checks.yml index 6c00a7e35..64f3f623e 100644 --- a/.forgejo/workflows/prek-checks.yml +++ b/.forgejo/workflows/prek-checks.yml @@ -7,10 +7,6 @@ on: - main workflow_dispatch: -permissions: - contents: read - pull-requests: read - jobs: fast-checks: name: Pre-commit & Formatting diff --git a/.forgejo/workflows/release-image.yml b/.forgejo/workflows/release-image.yml index 6673755d2..2c669ab8b 100644 --- a/.forgejo/workflows/release-image.yml +++ b/.forgejo/workflows/release-image.yml @@ -31,11 +31,6 @@ jobs: build-release: name: "Build ${{ matrix.slug }} (release)" runs-on: dind - permissions: - contents: read - packages: write - attestations: write - id-token: write strategy: matrix: include: @@ -84,6 +79,7 @@ jobs: outputs: | ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }} type=local,dest=/tmp/binaries + pull: true # Base images were becoming out of date env: SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }} - name: Upload Docker artifacts @@ -117,11 +113,6 @@ jobs: name: "Build ${{ matrix.slug }} (max-perf)" runs-on: dind needs: build-release - permissions: - contents: read - packages: write - attestations: write - id-token: write strategy: matrix: include: @@ -172,6 +163,7 @@ jobs: outputs: | ${{ env.BUILTIN_REGISTRY_ENABLED == 'true' && format('type=image,"name={0}",push-by-digest=true,name-canonical=true,push=true', env.IMAGE_PATH) || format('type=image,"name={0}",push=false', env.IMAGE_PATH) }} type=local,dest=/tmp/binaries + pull: true # Base images were becoming out of date env: SOURCE_DATE_EPOCH: ${{ env.TIMESTAMP }} - name: Upload max-perf Docker artifacts @@ -207,8 +199,6 @@ jobs: needs: - build-release - build-maxperf - permissions: - contents: write if: startsWith(github.ref, 'refs/tags/') steps: - name: Download binary artifacts @@ -218,7 +208,7 @@ jobs: path: binaries merge-multiple: true - name: Create Release and Upload - uses: https://github.com/softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + uses: https://github.com/softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3 with: draft: true files: binaries/* diff --git a/.forgejo/workflows/renovate.yml b/.forgejo/workflows/renovate.yml index d9e688b05..b2ba0212b 100644 --- a/.forgejo/workflows/renovate.yml +++ b/.forgejo/workflows/renovate.yml @@ -43,7 +43,7 @@ jobs: name: Renovate runs-on: ubuntu-latest container: - image: ghcr.io/renovatebot/renovate:44.151.2@sha256:29b3bf193f855c6f4b7027395a9c66c3417ad8bb6f30458090e1c2363d04eef7 + image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e options: --tmpfs /tmp:exec steps: - name: Checkout diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 74805ccd4..8c42d4f7b 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -7,6 +7,7 @@ f419c64aca300a338096b4e0db4c73ace54f23d0 5998a0d883d31b866f7c8c46433a8857eae51a89 # trailing whitespace and newlines 46c193e74b2ce86c48ce802333a0aabce37fd6e9 -# rustfmt update that rewrapped tons of comments +# rustfmt updates that rewrapped tons of comments 9fbabe221051e6956a05d8824142092ede68971e b0c0905472b882ff0cc79232e73d307fd0b5035b +9c27441acf2e65f85c106ccff5c6b6c37030ddca diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index f4fdf4d4f..d28e9584d 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,4 @@ +open_collective: continuwuity github: [JadedBlueEyes, timedoutuk, gingershaped] custom: - https://timedout.uk/donate.html diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1e74825c4..76c5ef022 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,7 +24,7 @@ repos: - id: check-added-large-files - repo: https://github.com/crate-ci/typos - rev: v1.51.1 + rev: v1.52.2 hooks: - id: typos - id: typos @@ -32,7 +32,7 @@ repos: stages: [ commit-msg ] - repo: https://github.com/crate-ci/committed - rev: v1.1.11 + rev: v1.1.12 hooks: - id: committed diff --git a/CHANGELOG.md b/CHANGELOG.md index 53645d5df..05fe334da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,154 @@ +# Continuwuity v26.11.0-alpha.2 (2026-11-14) + +## Features + +- Added opt-in OpenTelemetry metrics, exported over OTLP or scraped by Prometheus from `/_continuwuity/metrics`, and a Grafana dashboard. Contributed by @eleboucher. (prometheus-metrics) +- Add support for using custom DNS servers instead of using /etc/resolv.conf. Contributed by @s1lv3r. ([#2056](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2056)) +- Continuwuity now supports configuring additional trusted audience values for deployments using OIDC with an IDP that sends them. Contributed by @ginger ([#2226](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2226)) +- "!admin users list" now hides deactivated users by default, but can display them with the optional "--show-deactivated" flag. "--hide-suspended" and "--hide-locked" have been added as well, which stop suspended and locked users from being displayed respectively. Contributed by @Clubs. ([#2292](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2292)) +- Added support for [MSC4494: Membership-based invite blocking](https://github.com/matrix-org/matrix-spec-proposals/pull/4494) ([#2297](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2297)) +- Appservices now receive typing indicators and read receipts. Contributed by @Jade ([#2327](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2327)) +- Added support for servers returning 410 gone to indicate they are no longer serving a Matrix server ([MSC4188](https://github.com/matrix-org/matrix-spec-proposals/pull/4188)). Contributed by @nex and @silversys ([#2355](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2355)) +- Changed the policy on unstable features, disabling most by default and making them configurable in a tidy little `experiments` configuration. See also: #1884. ([#2517](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2517)) +- Added support for [MSC4363](https://github.com/matrix-org/matrix-spec-proposals/pull/4363) (OAuth step-up authentication). Contributed by @ginger. +- Added support for [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), allowing room moderators to fetch the original content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. +- Added support for [MSC4484](https://github.com/matrix-org/matrix-spec-proposals/pull/4484). Clients which use the built-in Matrix server administration APIs will need to ask for the appropriate scope when signing in with OAuth. Contributed by @ginger. +- Check content-type header on federation responses, ignoring any that don't match (spec compliance) +- Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + + [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +- Profile banners are now treated as images when imported from OIDC claims, like avatars already were. +- Remove support for legacy, unauthenticated media, including the `allow_legacy_media` and `freeze_legacy_media` options. +- The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger + +## Bugfixes + +- Fixed `/get_missing_events` rejecting requests with more `earliest_events` than the `limit`. Contributed by @eleboucher. (get-missing-events-earliest-limit) +- Invitees are now added as room creators when creating a v12+ trusted private chat. Contributed by @ginger. ([#2162](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2162)) +- Fixed push gateway URLs containing the configured notification path outside of their suffix. Contributed by @eleboucher. ([#2261](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2261)) +- "!admin users change-email" now verifies a user exists before attempting to change their email. Contributed by @Clubs. ([#2298](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2298)) +- Fixed URL preview image MIME types and rejected failed downloads. Contributed by @eleboucher. ([#2308](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2308)) +- Correctly set RocksDB column options, including enabling block caches. Contributed by @Jade ([#2345](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2345)) +- Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade ([#2351](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2351)) +- Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. ([#2356](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2356)) +- The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. ([#2383](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2383)) +- Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. ([#2387](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2387)) +- Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. ([#2400](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2400)) +- Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. ([#2421](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2421)) +- Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. ([#2424](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2424)) +- Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. ([#2444](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2444)) +- Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. ([#2452](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2452)) +- Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. ([#2454](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2454)) +- Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys ([#2460](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2460)) +- Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). ([#2465](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2465)) +- Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade ([#2481](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2481)) +- Fix the DNS resolver failing to start without `/etc/resolv.conf` when `dns_servers` is configured. Contributed by @eleboucher. ([#2495](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2495)) +- Fixed OIDC logins failing after the identity provider rotates its signing keys. Contributed by @eleboucher. ([#2497](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2497)) +- Creating a room with valid but non-canonical JSON now returns `400 M_BAD_JSON` instead of panicking the worker and returning `500 M_UNKNOWN`. +- Fix account data updates sent at the same time leaving old copies behind, which every initial sync then returned. Existing copies are removed on startup. Contributed by @eleboucher. +- Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. +- Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. +- Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. +- Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. +- Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. +- For deployments using OIDC with `profile_key_import_mode` set to `on_login`, users' avatars will no longer be clobbered if they didn't change their avatar since their last login. +- Joining a local room the user is not allowed to join now returns `403 M_FORBIDDEN` instead of `500 M_UNKNOWN` when there are no other servers to try. +- Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. +- The userinfo endpoint is now accessible even if federation is disabled, allowing LiveKit to be used on servers with federation disabled without using the server name whitelist. +- `!admin token issue` can no longer issue registration tokens when `allow_registration` is false. Contributed by @Clubs. + +## Improved Documentation + +- Add the Authentication section to document available auth methods for Continuwuity. The "delegated authentication" guide has also been migrated to here. Contributed by @stratself. ([#2234](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2234)) +- Add a guide for push notifications, detailing how it works, push gateway specifics, troubleshooting common issues, and pointing to external guides for UnifiedPush backends. Contributed by @stratself ([#2244](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2244)) +- The deploying page now includes vital general information about installing Continuwuity: release tracks, update steps, and post-installation recommendations. Contributed by @stratself ([#2252](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2252)) +- Add some missing instructions on configuring Continuwuity on the RPM page. Users are encouraged to use the [generic deploying docs](https://continuwuity.org/deploying/generic) for the bulk of guidance anyhow. Contributed by @stratself ([#2275](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2275)) +- Better, more succinct [introduction page](https://continuwuity.org/introduction.html). Contributed by @stratself ([#2279](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2279)) +- Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. ([#2324](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2324)) +- Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra ([#2341](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2341)) +- Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. ([#2353](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2353)) +- The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. + +## Misc + +- Updated internal Sentry integration setup to the new pattern required by the SDK. #2423 +- Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. + + +# Continuwuity v26.11.0-alpha.1 (2026-11-10) + +## Features + +- Added opt-in OpenTelemetry metrics, exported over OTLP or scraped by Prometheus from `/_continuwuity/metrics`, and a Grafana dashboard. Contributed by @eleboucher. (prometheus-metrics) +- Add support for using custom DNS servers instead of using /etc/resolv.conf. Contributed by @s1lv3r. ([#2056](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2056)) +- Continuwuity now supports configuring additional trusted audience values for deployments using OIDC with an IDP that sends them. Contributed by @ginger ([#2226](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2226)) +- "!admin users list" now hides deactivated users by default, but can display them with the optional "--show-deactivated" flag. "--hide-suspended" and "--hide-locked" have been added as well, which stop suspended and locked users from being displayed respectively. Contributed by @Clubs. ([#2292](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2292)) +- Added support for [MSC4494: Membership-based invite blocking](https://github.com/matrix-org/matrix-spec-proposals/pull/4494) ([#2297](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2297)) +- Appservices now receive typing indicators and read receipts. Contributed by @Jade ([#2327](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2327)) +- Added support for [MSC4363](https://github.com/matrix-org/matrix-spec-proposals/pull/4363) (OAuth step-up authentication). Contributed by @ginger. +- Added support for [MSC4484](https://github.com/matrix-org/matrix-spec-proposals/pull/4484). Clients which use the built-in Matrix server administration APIs will need to ask for the appropriate scope when signing in with OAuth. Contributed by @ginger. +- Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + + [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +- Profile banners are now treated as images when imported from OIDC claims, like avatars already were. +- The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger + +## Bugfixes + +- Invitees are now added as room creators when creating a v12+ trusted private chat. Contributed by @ginger. ([#2162](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2162)) +- Fixed push gateway URLs containing the configured notification path outside of their suffix. Contributed by @eleboucher. ([#2261](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2261)) +- "!admin users change-email" now verifies a user exists before attempting to change their email. Contributed by @Clubs. ([#2298](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2298)) +- Fixed URL preview image MIME types and rejected failed downloads. Contributed by @eleboucher. ([#2308](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2308)) +- Correctly set RocksDB column options, including enabling block caches. Contributed by @Jade ([#2345](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2345)) +- Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade ([#2351](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2351)) +- Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. ([#2356](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2356)) +- The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. ([#2383](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2383)) +- Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. ([#2387](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2387)) +- Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. ([#2400](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2400)) +- Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. ([#2421](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2421)) +- Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. ([#2424](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2424)) +- Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. ([#2444](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2444)) +- Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. ([#2451](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2451)) +- The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. ([#2452](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2452)) +- Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. ([#2454](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2454)) +- Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys ([#2460](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2460)) +- Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). ([#2465](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2465)) +- Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade ([#2481](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2481)) +- Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. +- Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. +- Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. +- Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. +- Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. +- For deployments using OIDC with `profile_key_import_mode` set to `on_login`, users' avatars will no longer be clobbered if they didn't change their avatar since their last login. +- Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. +- The userinfo endpoint is now accessible even if federation is disabled, allowing LiveKit to be used on servers with federation disabled without using the server name whitelist. +- `!admin token issue` can no longer issue registration tokens when `allow_registration` is false. Contributed by @Clubs. + +## Improved Documentation + +- Add the Authentication section to document available auth methods for Continuwuity. The "delegated authentication" guide has also been migrated to here. Contributed by @stratself. ([#2234](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2234)) +- Add a guide for push notifications, detailing how it works, push gateway specifics, troubleshooting common issues, and pointing to external guides for UnifiedPush backends. Contributed by @stratself ([#2244](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2244)) +- The deploying page now includes vital general information about installing Continuwuity: release tracks, update steps, and post-installation recommendations. Contributed by @stratself ([#2252](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2252)) +- Add some missing instructions on configuring Continuwuity on the RPM page. Users are encouraged to use the [generic deploying docs](https://continuwuity.org/deploying/generic) for the bulk of guidance anyhow. Contributed by @stratself ([#2275](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2275)) +- Better, more succinct [introduction page](https://continuwuity.org/introduction.html). Contributed by @stratself ([#2279](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2279)) +- Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. ([#2324](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2324)) +- Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra ([#2341](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2341)) +- Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. ([#2353](https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2353)) +- The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. + +## Misc + +- Updated internal Sentry integration setup to the new pattern required by the SDK. #2423 +- Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. + + # Continuwuity v26.9.1 (2026-09-28) ## Features diff --git a/Cargo.lock b/Cargo.lock index a718f824f..750117b4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "addr2line" -version = "0.25.1" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" dependencies = [ "gimli", ] @@ -23,7 +23,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "generic-array", ] @@ -61,34 +61,19 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - [[package]] name = "alloc-no-stdlib" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" -[[package]] -name = "alloc-stdlib" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" -dependencies = [ - "alloc-no-stdlib 2.0.4", -] - [[package]] name = "alloc-stdlib" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ - "alloc-no-stdlib 3.0.0", + "alloc-no-stdlib", ] [[package]] @@ -108,22 +93,22 @@ dependencies = [ [[package]] name = "annotate-snippets" -version = "0.12.16" +version = "0.12.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1" +checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" dependencies = [ "anstyle", "memchr", - "unicode-width 0.2.2", + "unicode-width 0.2.3", ] [[package]] name = "ansi-width" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219e3ce6f2611d83b51ec2098a12702112c29e57203a6b0a0929b2cddb486608" +checksum = "90759a65f5178dbbd1b0eecc97b187996401bced0eb4a943d9ac6d7a6304d111" dependencies = [ - "unicode-width 0.1.14", + "unicode-width 0.2.3", ] [[package]] @@ -140,9 +125,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "db4c94f57a570fce5d381be3289b3f79aef6332d72948fe82ab5772e423ccf92" dependencies = [ "rustversion", ] @@ -208,7 +193,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -230,7 +215,7 @@ dependencies = [ "serde", "serde_derive", "unicode-ident", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -252,9 +237,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.46" +version = "0.4.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f10dafd0c8d2e51ae9a748805777613ed0bbe17bf586b76c8311f45c020a32f" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" dependencies = [ "compression-codecs", "compression-core", @@ -270,7 +255,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -296,9 +281,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.1" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -306,9 +291,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.45.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -446,14 +431,14 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.76" +version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" dependencies = [ "addr2line", "cfg-if", "libc", - "miniz_oxide 0.8.9", + "miniz_oxide 0.9.1", "object", "rustc-demangle", "windows-link", @@ -466,10 +451,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" [[package]] -name = "base64" -version = "0.21.7" +name = "base16ct" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" [[package]] name = "base64" @@ -500,28 +485,21 @@ dependencies = [ [[package]] name = "bindgen" -version = "0.72.1" +version = "0.73.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cexpr", "clang-sys", - "itertools 0.13.0", "proc-macro2", "quote", "regex", "rustc-hash", - "shlex 1.3.0", + "shlex", "syn 2.0.119", ] -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - [[package]] name = "bitflags" version = "2.13.2" @@ -566,44 +544,23 @@ dependencies = [ [[package]] name = "brotli" -version = "8.0.4" +version = "9.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81" dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", - "brotli-decompressor 5.0.3", -] - -[[package]] -name = "brotli" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b" -dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", - "brotli-decompressor 6.0.0", + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", ] [[package]] name = "brotli-decompressor" -version = "5.0.3" +version = "6.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +checksum = "97d9071e5b45944c5a9c06baf13a7a65ffa2c88c204015967852c90869692c05" dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", -] - -[[package]] -name = "brotli-decompressor" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46087801e40b785410c352bee60e9b6226312709cf52d5fff92776cdf5cf6490" -dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", + "alloc-no-stdlib", + "alloc-stdlib", ] [[package]] @@ -647,9 +604,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" -version = "1.12.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "bytesize" @@ -668,10 +625,16 @@ dependencies = [ ] [[package]] -name = "camino" -version = "1.2.5" +name = "cache_control" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb1307f12aa967b5a58416e87b3653360e0fd614a016b6e970db08fecbb1b80d" +checksum = "1bf2a5fb3207c12b5d208ebc145f967fea5cac41a021c37417ccc31ba40f39ee" + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" dependencies = [ "serde_core", ] @@ -708,19 +671,19 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" dependencies = [ "semver", "serde", - "toml 1.1.6+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", ] [[package]] name = "cc" -version = "1.4.6" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex 2.0.1", + "shlex", ] [[package]] @@ -734,9 +697,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -784,7 +747,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "inout", ] @@ -796,14 +759,14 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ "glob", "libc", - "libloading 0.8.9", + "libloading", ] [[package]] name = "clap" -version = "4.6.7" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" dependencies = [ "clap_builder", "clap_derive", @@ -821,21 +784,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.7" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "client-ip" @@ -869,9 +832,9 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -879,11 +842,11 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.41" +version = "0.4.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58a6d0db8759036a783bc7c3f7a07f8cef3bf9470eb1db3bc86e8bcd1c5d0fe8" +checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" dependencies = [ - "brotli 8.0.4", + "brotli", "compression-core", "flate2", "memchr", @@ -893,9 +856,9 @@ dependencies = [ [[package]] name = "compression-core" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" [[package]] name = "concurrent-queue" @@ -908,15 +871,11 @@ dependencies = [ [[package]] name = "conduwuit" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ - "aws-lc-rs", "clap", - "conduwuit_admin", - "conduwuit_api", "conduwuit_build_metadata", "conduwuit_core", - "conduwuit_database", "conduwuit_macros", "conduwuit_router", "conduwuit_service", @@ -924,8 +883,6 @@ dependencies = [ "const-str", "ctor", "dtor", - "hardened_malloc-rs", - "log", "opentelemetry", "opentelemetry-otlp", "opentelemetry-prometheus", @@ -933,13 +890,10 @@ dependencies = [ "opentelemetry_sdk", "parking_lot", "prometheus", - "reqwest 0.13.5", "rustls", "sentry", - "sentry-tower", "sentry-tracing", "tokio", - "tokio-metrics", "tracing", "tracing-flame", "tracing-journald", @@ -949,7 +903,7 @@ dependencies = [ [[package]] name = "conduwuit_admin" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "clap", "conduwuit_api", @@ -962,7 +916,6 @@ dependencies = [ "dtor", "futures", "lettre", - "log", "resolvematrix", "ruma", "serde-saphyr", @@ -974,7 +927,7 @@ dependencies = [ [[package]] name = "conduwuit_api" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "axum", "base64 0.23.1", @@ -993,8 +946,7 @@ dependencies = [ "hyper", "itertools 0.15.0", "lettre", - "log", - "rand 0.10.3", + "rand 0.10.4", "reqwest 0.13.5", "ruma", "ruminuwuity", @@ -1003,11 +955,12 @@ dependencies = [ "sha1 0.11.0", "tokio", "tracing", + "wildmatch", ] [[package]] name = "conduwuit_build_metadata" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "built", "cargo_metadata", @@ -1015,7 +968,7 @@ dependencies = [ [[package]] name = "conduwuit_core" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "argon2", "arrayvec", @@ -1037,17 +990,17 @@ dependencies = [ "either", "figment", "futures", - "hardened_malloc-rs", + "governor", "http", "http-body-util", "hyper-util", "ipaddress", "lettre", "libc", - "libloading 0.9.0", - "lock_api", - "log", + "libmimalloc-sys", + "lock_api 0.5.0", "maplit", + "mimalloc", "nix", "num-traits", "openidconnect", @@ -1057,7 +1010,7 @@ dependencies = [ "opentelemetry_sdk", "parking_lot", "prometheus", - "rand 0.10.3", + "rand 0.10.4", "regex", "reqwest 0.13.5", "resolvematrix", @@ -1067,7 +1020,7 @@ dependencies = [ "serde-saphyr", "serde_json", "serde_regex", - "sha2 0.11.0", + "sha2 0.11.1", "smallstr", "smallvec", "thiserror 2.0.21", @@ -1076,7 +1029,7 @@ dependencies = [ "tikv-jemallocator", "tokio", "tokio-metrics", - "toml 1.1.6+spec-1.1.0", + "toml 1.2.2+spec-1.1.0", "tracing", "tracing-core", "tracing-subscriber", @@ -1085,7 +1038,7 @@ dependencies = [ [[package]] name = "conduwuit_database" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "async-channel", "conduwuit_core", @@ -1094,7 +1047,6 @@ dependencies = [ "ctor", "dtor", "futures", - "log", "minicbor", "minicbor-serde", "rust-rocksdb", @@ -1106,17 +1058,17 @@ dependencies = [ [[package]] name = "conduwuit_macros" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "itertools 0.15.0", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "conduwuit_router" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "axum", "axum-server", @@ -1136,14 +1088,10 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", - "log", "opentelemetry-instrumentation-tower", "ruma", - "rustls", "sd-notify", - "sentry", "sentry-tower", - "sentry-tracing", "serde_json", "tokio", "tower", @@ -1153,7 +1101,7 @@ dependencies = [ [[package]] name = "conduwuit_service" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "assign", @@ -1179,22 +1127,26 @@ dependencies = [ "log", "loole", "lru-cache", + "mime", "nonzero_ext", "openidconnect", - "p256", - "rand 0.10.3", + "opentelemetry", + "p256 0.14.0", + "rand 0.10.4", "regex", + "reqwest 0.12.28", "reqwest 0.13.5", "resolvematrix", "ruma", "ruminuwuity", + "rustls", "rustyline-async", "sd-notify", "serde", "serde-saphyr", "serde_json", "serde_urlencoded", - "sha2 0.11.0", + "sha2 0.11.1", "termimad", "tokio", "tracing", @@ -1206,7 +1158,7 @@ dependencies = [ [[package]] name = "conduwuit_web" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "async-trait", @@ -1373,6 +1325,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1393,9 +1351,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" dependencies = [ "cfg-if", ] @@ -1408,9 +1366,9 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "crokey" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "074bc31bff1084f74e5a145ad5f6ac74469fa312159faa5144f0b1c4506b8d80" +checksum = "c41f5f8d5dba70b6f48daa17fee79ac7c3a13cc1b164f41d0de50c803e0266f2" dependencies = [ "crokey-proc_macros", "crossterm", @@ -1421,15 +1379,15 @@ dependencies = [ [[package]] name = "crokey-proc_macros" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b88c4ff2d5717616c3bb4a31d06b0b241ed811c7c0c41d077d77631bee7caad0" +checksum = "2ca5122126412913548025b1d5574181121bcf7a06f8b530f4be713ebd81d418" dependencies = [ "crossterm", "proc-macro2", "quote", "strict", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -1494,7 +1452,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "crossterm_winapi", "derive_more", "document-features", @@ -1529,10 +1487,26 @@ dependencies = [ ] [[package]] -name = "crypto-common" -version = "0.1.6" +name = "crypto-bigint" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", "rand_core 0.6.4", @@ -1545,14 +1519,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", ] [[package]] name = "ctor" -version = "1.0.13" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" dependencies = [ "link-section", "linktime-proc-macro", @@ -1569,28 +1545,19 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", + "subtle", ] [[package]] -name = "curve25519-dalek" -version = "4.1.3" +name = "cty" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "curve25519-dalek-derive", - "digest 0.10.7", - "fiat-crypto 0.2.9", - "rustc_version", - "subtle", - "zeroize", -] +checksum = "b365fabc795046672053e29c954733ec3b05e4be654ab130fe8f1f94d7051f35" [[package]] name = "curve25519-dalek" @@ -1602,7 +1569,7 @@ dependencies = [ "cpufeatures 0.3.1", "curve25519-dalek-derive", "digest 0.11.3", - "fiat-crypto 0.3.0", + "fiat-crypto", "rustc_version", "subtle", "zeroize", @@ -1668,7 +1635,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1690,7 +1657,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1715,37 +1682,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "defmt" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "defmt-parser" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "der" version = "0.7.10" @@ -1753,25 +1689,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "zeroize", ] [[package]] name = "der" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ "serde_core", ] @@ -1806,7 +1743,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "const-oid 0.9.6", - "crypto-common 0.1.6", + "crypto-common 0.1.7", "subtle", ] @@ -1828,7 +1765,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", ] @@ -1840,7 +1777,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1854,10 +1791,11 @@ dependencies = [ [[package]] name = "dtor" -version = "1.0.6" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd3f6c362b2bbd7063090886afd78978f5dbf1f11da7efcc40f81d32c943fac1" +checksum = "915e80ae7aca23bef767ded8e4a763d0c912c2faaa8bfec1e66d505ebaceb254" dependencies = [ + "link-section", "linktime-proc-macro", ] @@ -1881,12 +1819,27 @@ checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ "der 0.7.10", "digest 0.10.7", - "elliptic-curve", - "rfc6979", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", "signature 2.2.0", "spki 0.7.3", ] +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + [[package]] name = "ece-native" version = "0.5.0" @@ -1898,16 +1851,6 @@ dependencies = [ "sha2 0.10.9", ] -[[package]] -name = "ed25519" -version = "2.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" -dependencies = [ - "pkcs8 0.10.2", - "signature 2.2.0", -] - [[package]] name = "ed25519" version = "3.0.0" @@ -1918,30 +1861,16 @@ dependencies = [ "signature 3.0.0", ] -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek 4.1.3", - "ed25519 2.2.3", - "serde", - "sha2 0.10.9", - "subtle", - "zeroize", -] - [[package]] name = "ed25519-dalek" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0", - "ed25519 3.0.0", + "curve25519-dalek", + "ed25519", "serde", - "sha2 0.11.0", + "sha2 0.11.1", "signature 3.0.0", "subtle", "zeroize", @@ -1949,9 +1878,9 @@ dependencies = [ [[package]] name = "either" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" dependencies = [ "serde", ] @@ -1962,26 +1891,47 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", - "crypto-bigint", + "base16ct 0.2.0", + "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", + "ff 0.13.1", "generic-array", - "group", + "group 0.13.0", "hkdf 0.12.4", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", - "sec1", + "sec1 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", "subtle", "zeroize", ] [[package]] name = "email-encoding" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +checksum = "9f690ae2169f2ceb3f45b28b6fcd8fa16839f2f5c8818546774b9425f5f71004" dependencies = [ "base64 0.23.1", "memchr", @@ -1995,13 +1945,12 @@ checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" [[package]] name = "encoding_rs" -version = "0.8.41" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5ef0006ac9ab233c38522f5ae99cae3625151de8f706cacee1cba4b8e2832a" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", - "multiversion", "multiversion_no_op", "rustversion", "scopeguard", @@ -2019,9 +1968,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -2078,10 +2027,14 @@ dependencies = [ ] [[package]] -name = "fiat-crypto" -version = "0.2.9" +name = "ff" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] [[package]] name = "fiat-crypto" @@ -2105,9 +2058,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "findshlibs" @@ -2129,9 +2082,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide 0.9.1", @@ -2152,18 +2105,18 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] [[package]] name = "fs-err" -version = "3.3.1" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91aa448ca50d7e79433bdf3ee8d99215430d2ec02ade5aefab2a073a1822e8a" +checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29" dependencies = [ "autocfg", "tokio", @@ -2175,16 +2128,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" -[[package]] -name = "futf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" -dependencies = [ - "mac", - "new_debug_unreachable", -] - [[package]] name = "futures" version = "0.3.34" @@ -2241,7 +2184,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -2281,9 +2224,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.9" +version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", @@ -2351,9 +2294,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.32.3" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" [[package]] name = "glob" @@ -2382,9 +2325,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "1.3.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e20f99e46474f56bd905c56e817ebddcf377a611f94c53ac4649e4d3fa3c0cd0" +checksum = "9bd04d0d9c7079b416b458d2317aea4aa964c81938cb7c20f559758c4f422dc8" dependencies = [ "arraydeque", "smallvec", @@ -2396,16 +2339,27 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] [[package]] -name = "h2" -version = "0.4.19" +name = "group" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -2448,12 +2402,6 @@ dependencies = [ "tokio-util", ] -[[package]] -name = "hardened_malloc-rs" -version = "0.1.2+12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "647deb1583b14d160f85f3ff626f20b6edd366e3852c9843b06077388f794cb6" - [[package]] name = "hashbrown" version = "0.12.3" @@ -2492,9 +2440,9 @@ dependencies = [ [[package]] name = "headers" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" dependencies = [ "base64 0.22.1", "bytes", @@ -2548,7 +2496,7 @@ dependencies = [ "idna", "ipnet", "jni", - "rand 0.10.3", + "rand 0.10.4", "thiserror 2.0.21", "tinyvec", "tokio", @@ -2568,7 +2516,7 @@ dependencies = [ "jni", "once_cell", "prefix-trie", - "rand 0.10.3", + "rand 0.10.4", "ring", "serde", "thiserror 2.0.21", @@ -2594,7 +2542,7 @@ dependencies = [ "ndk-context", "once_cell", "parking_lot", - "rand 0.10.3", + "rand 0.10.4", "resolv-conf", "serde", "smallvec", @@ -2653,16 +2601,12 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.27.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" dependencies = [ "log", - "mac", "markup5ever", - "proc-macro2", - "quote", - "syn 2.0.119", ] [[package]] @@ -2731,14 +2675,16 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] name = "hyper" -version = "1.11.1" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -2758,18 +2704,18 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", "hyper-util", "rustls", + "rustls-native-certs", "tokio", "tokio-rustls", "tower-service", - "webpki-roots", ] [[package]] @@ -2833,9 +2779,9 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -2847,9 +2793,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -2860,9 +2806,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2874,15 +2820,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -2895,15 +2841,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -3009,9 +2955,9 @@ dependencies = [ [[package]] name = "ipaddress" -version = "0.2.11" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67a97d7409c3ade4304acbff6b33b915af4564c42bf6e383651ced09bd6a2bce" +checksum = "e0ae5a9c049476ef23026df39fe92a8d83c1d8b670b975f095cb4d5a3b13d43e" dependencies = [ "lazy_static", "libc", @@ -3043,24 +2989,6 @@ dependencies = [ "serde", ] -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.14.0" @@ -3087,11 +3015,10 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.37" +version = "0.2.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" +checksum = "fcefdcefac59ac8f8401852e3427d55610481fc41e6625c39bac62d2d771623a" dependencies = [ - "defmt", "jiff-core", "jiff-static", "jiff-tzdb-platform", @@ -3104,19 +3031,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "77a24020db0ee88d1c681d677681bd31f9f4ea189a455425223d52ce4f1508aa" dependencies = [ - "defmt", "log", ] [[package]] name = "jiff-static" -version = "0.2.37" +version = "0.2.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" +checksum = "203edf9b0ce4083ec8fbf4adc823eac89768ea994b4953fc0dab1b90083234dd" dependencies = [ "jiff-core", "proc-macro2", @@ -3126,9 +3052,9 @@ dependencies = [ [[package]] name = "jiff-tzdb" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" [[package]] name = "jiff-tzdb-platform" @@ -3200,9 +3126,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.105" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -3239,9 +3165,9 @@ dependencies = [ [[package]] name = "lazy-regex" -version = "3.6.1" +version = "3.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4994ba703f78b083e2f7946dac9251abd83fd43a0365f030e99b69be5b4b9ef9" +checksum = "f0a2cce8a22920a29fdcc8c9170aa5d29edd9fbcf8bea856e24c2cb1c2419f67" dependencies = [ "lazy-regex-proc_macros", "once_cell", @@ -3250,30 +3176,30 @@ dependencies = [ [[package]] name = "lazy-regex-proc_macros" -version = "3.6.1" +version = "3.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd97232314824e6dbef1918a871bb93f51070455e3715bf26e19a6d01aa977a0" +checksum = "6f1e4b1f1d8c71edb4ff2b2150ec4606445fd2ddf67ddc097655daf59286baa6" dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" dependencies = [ "spin", ] [[package]] name = "lettre" -version = "0.11.23" +version = "0.11.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +checksum = "f294f3d7cdb313e578acef7d7727d4e8d897e0fcd0d6d58c19959cec95073f19" dependencies = [ "async-trait", "base64 0.23.1", @@ -3301,9 +3227,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -3315,16 +3241,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "libloading" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" -dependencies = [ - "cfg-if", - "windows-link", -] - [[package]] name = "libm" version = "0.2.16" @@ -3332,10 +3248,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] -name = "libz-sys" -version = "1.1.29" +name = "libmimalloc-sys" +version = "0.1.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", + "cty", +] + +[[package]] +name = "libz-sys" +version = "1.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85" dependencies = [ "cc", "pkg-config", @@ -3344,9 +3270,9 @@ dependencies = [ [[package]] name = "link-section" -version = "0.19.3" +version = "0.19.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39c29a617ce3df32c08497bdc1ab6e2376e0b17948ac166a2fbe5977c5954cd9" +checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" [[package]] name = "linked-hash-map" @@ -3374,9 +3300,9 @@ checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -3388,16 +3314,25 @@ dependencies = [ ] [[package]] -name = "log" -version = "0.4.34" +name = "lock_api" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "loole" -version = "0.4.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a3932a13b27d6b2d37efec3e4047017d59a8c9f2283a29bde29151d22f00fe9" +checksum = "45a6f2ee852ef619dac448846d7a80fb56a08e842674202d1ffe509fc319165c" dependencies = [ "futures-core", "futures-sink", @@ -3428,12 +3363,6 @@ dependencies = [ "libc", ] -[[package]] -name = "mac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" - [[package]] name = "maplit" version = "1.0.2" @@ -3442,23 +3371,20 @@ checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" [[package]] name = "markup5ever" -version = "0.12.1" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" dependencies = [ "log", - "phf", - "phf_codegen", - "string_cache", - "string_cache_codegen", "tendril", + "web_atoms", ] [[package]] name = "markup5ever_rcdom" -version = "0.3.0" +version = "0.39.0+unofficial" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edaa21ab3701bfee5099ade5f7e1f84553fd19228cf332f13cd6e964bf59be18" +checksum = "3ac010f19d6c4af81eeb4018a39d7a115de9d285af45c126a4ac02e6fc5716b7" dependencies = [ "html5ever", "markup5ever", @@ -3494,7 +3420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "191dc109c485eb7ee3bcab18993237be2cb290a9475debd4205ecb5f20d1f1ea" dependencies = [ "axum", - "brotli 9.0.0", + "brotli", "flate2", "fs-err", "mime_guess", @@ -3505,10 +3431,19 @@ dependencies = [ ] [[package]] -name = "mime" -version = "0.3.17" +name = "mimalloc" +version = "0.1.52" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mime_guess" @@ -3522,15 +3457,15 @@ dependencies = [ [[package]] name = "minicbor" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c12b4033ffaa92fbf9df03df38d19324f52bad130dd223f811734a8006dd2d69" +checksum = "e7244eafd1e09e7c4e33043881997aa6ab6dffff3ed2cee3395a278980481d6e" [[package]] name = "minicbor-serde" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7abdec9761edcb452764c68564ae4b77ec62f6c1a361aa68f5de15fd788c679" +checksum = "b05ae1ca1d2c55196b389c8308119aa0e2aa8d31115f018dcc23ba3c5d350eb3" dependencies = [ "minicbor", "serde", @@ -3573,9 +3508,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "log", @@ -3610,27 +3545,6 @@ dependencies = [ "pxfm", ] -[[package]] -name = "multiversion" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ca4bea16ffc3f443cf7d866912118196bfef4c6a1556ca00f9f9b00bb43f7c" -dependencies = [ - "multiversion-macros", -] - -[[package]] -name = "multiversion-macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d416831a7317ef4b08bee00b69cbbb9c8763da7959a7026244d6266869f9c83" -dependencies = [ - "proc-macro2", - "quote", - "rustversion", - "syn 3.0.6", -] - [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -3655,7 +3569,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "cfg-if", "cfg_aliases", "libc", @@ -3828,9 +3742,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -3841,7 +3755,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-foundation", ] @@ -3862,7 +3776,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.13.2", + "bitflags", "dispatch2", "objc2", ] @@ -3873,7 +3787,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ - "bitflags 2.13.2", + "bitflags", "dispatch2", "objc2", "objc2-core-foundation", @@ -3906,7 +3820,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", "objc2-core-graphics", @@ -3924,7 +3838,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "libc", "objc2", @@ -3937,7 +3851,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", ] @@ -3948,7 +3862,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ - "bitflags 2.13.2", + "bitflags", "objc2", "objc2-core-foundation", "objc2-foundation", @@ -3960,7 +3874,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" dependencies = [ - "bitflags 2.13.2", + "bitflags", "block2", "objc2", "objc2-cloud-kit", @@ -3987,9 +3901,9 @@ dependencies = [ [[package]] name = "object" -version = "0.37.3" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" dependencies = [ "memchr", ] @@ -4012,20 +3926,21 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openidconnect" -version = "4.0.1" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c6709ba2ea764bbed26bce1adf3c10517113ddea6f2d4196e4851757ef2b2" +checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "dyn-clone", - "ed25519-dalek 2.2.0", + "ed25519-dalek", + "getrandom 0.4.3", "hmac 0.12.1", "http", - "itertools 0.10.5", + "itertools 0.14.0", "log", "oauth2", - "p256", + "p256 0.14.0", "p384", "rand 0.8.8", "rsa", @@ -4043,15 +3958,15 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "opentelemetry" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cdb0b1b267eb9db3331b434ed9ddab10d50e280a9adf9d13e5233e2002b61b5" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" dependencies = [ "futures-core", "futures-sink", @@ -4063,9 +3978,9 @@ dependencies = [ [[package]] name = "opentelemetry-http" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee2c3625b8aa04209f7e01e513bc8044da9687fa38a9eacf59628ca5f3b87300" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" dependencies = [ "async-trait", "bytes", @@ -4077,8 +3992,7 @@ dependencies = [ [[package]] name = "opentelemetry-instrumentation-tower" version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7006f3b1853d315462a7237c81eec3d7adfa5b70975a02b19e92d045bc22d7" +source = "git+https://github.com/open-telemetry/opentelemetry-rust-contrib?rev=6bbbc337aab0bcf10d7799c3e5b5ced75920491a#6bbbc337aab0bcf10d7799c3e5b5ced75920491a" dependencies = [ "axum", "http", @@ -4093,9 +4007,9 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "699a67345e21962a231955b9059a157e428b219fa5df8efe11f08346fb23a344" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" dependencies = [ "http", "httpdate", @@ -4113,9 +4027,9 @@ dependencies = [ [[package]] name = "opentelemetry-prometheus" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "274c2e3a2ad55524484500d5a78dffbfee23e4a1e4c3d3fcbd881b61b033e6df" +checksum = "b9b52a5722eb64d198d6b6f1189e6b75a3c5ddfd224f48ede00c4330e0f11c66" dependencies = [ "once_cell", "opentelemetry", @@ -4126,9 +4040,9 @@ dependencies = [ [[package]] name = "opentelemetry-proto" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25da1ac11a0aeccf38d7f77ee0348715adaf8340f65ad46c94a02c6b20e2f65d" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" dependencies = [ "opentelemetry", "opentelemetry_sdk", @@ -4139,15 +4053,15 @@ dependencies = [ [[package]] name = "opentelemetry-semantic-conventions" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d288b1e1bc3590052fbb8f0f635ef248dd9022cf1fbaeb6582b7ad6081a17b87" +checksum = "7a3cf639fefd3e852869114f9925b578da6dd8e99281a2089bb0e773ead46962" [[package]] name = "opentelemetry_sdk" -version = "0.33.0" +version = "0.33.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb39533d9d1c912123efd7d41d7e0c29d16917b60ce15b4c8d87cb1af7f67520" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" dependencies = [ "futures-channel", "futures-executor", @@ -4192,22 +4106,37 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", "sha2 0.10.9", ] [[package]] -name = "p384" -version = "0.13.1" +name = "p256" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2 0.10.9", + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "fiat-crypto", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", ] [[package]] @@ -4222,7 +4151,7 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api", + "lock_api 0.4.14", "parking_lot_core", ] @@ -4251,12 +4180,6 @@ dependencies = [ "phc", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "pear" version = "0.2.9" @@ -4289,6 +4212,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4318,18 +4250,19 @@ dependencies = [ [[package]] name = "phf" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ "phf_shared", + "serde", ] [[package]] name = "phf_codegen" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" dependencies = [ "phf_generator", "phf_shared", @@ -4337,19 +4270,19 @@ dependencies = [ [[package]] name = "phf_generator" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" dependencies = [ + "fastrand", "phf_shared", - "rand 0.8.8", ] [[package]] name = "phf_shared" -version = "0.11.3" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" dependencies = [ "siphasher", ] @@ -4407,8 +4340,8 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ - "der 0.8.2", - "spki 0.8.0", + "der 0.8.3", + "spki 0.8.1", ] [[package]] @@ -4423,7 +4356,7 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags 2.13.2", + "bitflags", "crc32fast", "fdeflate", "flate2", @@ -4468,9 +4401,9 @@ dependencies = [ [[package]] name = "powerfmt" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" [[package]] name = "ppv-lite86" @@ -4498,13 +4431,40 @@ dependencies = [ "num-traits", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.13.8", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.3", + "once_cell", + "primefield", + "serdect", + "wnaf", ] [[package]] @@ -4513,7 +4473,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.15+spec-1.1.0", + "toml_edit 0.25.19+spec-1.1.0", ] [[package]] @@ -4535,7 +4495,7 @@ dependencies = [ "proc-macro-error-attr3", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -4608,11 +4568,11 @@ dependencies = [ [[package]] name = "pulldown-cmark" -version = "0.13.4" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "memchr", "pulldown-cmark-escape", "unicase", @@ -4638,9 +4598,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -4659,15 +4619,15 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand 0.10.4", "rand_pcg", "ring", "rustc-hash", @@ -4682,9 +4642,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -4744,9 +4704,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ "chacha20", "getrandom 0.4.3", @@ -4812,7 +4772,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.2", + "bitflags", ] [[package]] @@ -4832,14 +4792,14 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "regex" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" dependencies = [ "aho-corasick", "memchr", @@ -4849,9 +4809,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.18" +version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" dependencies = [ "aho-corasick", "memchr", @@ -4860,9 +4820,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.11" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] name = "reqwest" @@ -4883,8 +4843,8 @@ dependencies = [ "log", "percent-encoding", "pin-project-lite", - "quinn", "rustls", + "rustls-native-certs", "rustls-pki-types", "serde", "serde_json", @@ -4899,7 +4859,6 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots", ] [[package]] @@ -4916,7 +4875,6 @@ dependencies = [ "h2", "h3", "h3-quinn", - "hickory-resolver", "http", "http-body", "http-body-util", @@ -4925,7 +4883,6 @@ dependencies = [ "hyper-util", "js-sys", "log", - "once_cell", "percent-encoding", "pin-project-lite", "quinn", @@ -4957,11 +4914,11 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "resolvematrix" -version = "1.3.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f072176a8b0cbe7c3df2281991ef00a09889d8ec789f2878e7fee43a3b978a6f" +checksum = "39a1efc3c55274528f8b1a916eb0edf5c40a8364b4899fbc1283a57c8d0024db" dependencies = [ - "futures", + "cache_control", "hickory-resolver", "num-traits", "parking_lot", @@ -4969,6 +4926,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "tokio-stream", "tracing", ] @@ -4982,6 +4940,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.10", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -5018,8 +4986,8 @@ dependencies = [ [[package]] name = "ruma" -version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.17.2" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "assign", "js_int", @@ -5037,8 +5005,8 @@ dependencies = [ [[package]] name = "ruma-appservice-api" -version = "0.17.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.17.1" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "http", "js_int", @@ -5050,8 +5018,8 @@ dependencies = [ [[package]] name = "ruma-client-api" -version = "0.25.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.25.2" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "assign", @@ -5072,8 +5040,8 @@ dependencies = [ [[package]] name = "ruma-common" -version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.20.2" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "base64 0.23.1", @@ -5086,7 +5054,7 @@ dependencies = [ "js_int", "konst", "percent-encoding", - "rand 0.10.3", + "rand 0.10.4", "regex", "ruma-identifiers-validation", "ruma-macros", @@ -5105,8 +5073,8 @@ dependencies = [ [[package]] name = "ruma-events" -version = "0.35.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.35.2" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "indexmap 2.14.2", @@ -5126,8 +5094,8 @@ dependencies = [ [[package]] name = "ruma-federation-api" -version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.16.1" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "bytes", "http", @@ -5136,7 +5104,7 @@ dependencies = [ "js_int", "memchr", "mime", - "rand 0.10.3", + "rand 0.10.4", "ruma-common", "ruma-events", "ruma-signatures", @@ -5148,8 +5116,8 @@ dependencies = [ [[package]] name = "ruma-identifiers-validation" -version = "0.12.1" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.14.0" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "thiserror 2.0.21", @@ -5157,8 +5125,8 @@ dependencies = [ [[package]] name = "ruma-macros" -version = "0.20.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.20.2" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "as_variant", "cfg-if", @@ -5167,14 +5135,14 @@ dependencies = [ "quote", "ruma-identifiers-validation", "serde", - "syn 3.0.6", - "toml 1.1.6+spec-1.1.0", + "syn 3.0.10", + "toml 1.2.2+spec-1.1.0", ] [[package]] name = "ruma-push-gateway-api" version = "0.16.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "ruma-common", @@ -5185,25 +5153,25 @@ dependencies = [ [[package]] name = "ruma-signatures" -version = "0.22.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +version = "0.22.1" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "base64 0.23.1", - "ed25519-dalek 3.0.0", + "ed25519-dalek", "memchr", "pkcs8 0.11.0", - "rand 0.10.3", + "rand 0.10.4", "ruma-common", "ruma-events", "serde_json", - "sha2 0.11.0", + "sha2 0.11.1", "thiserror 2.0.21", ] [[package]] name = "ruma-state-res" version = "0.18.0" -source = "git+https://github.com/ruma/ruma.git?rev=f5e5e1c885f598036fd4326c566e9d1928027d5d#f5e5e1c885f598036fd4326c566e9d1928027d5d" +source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7" dependencies = [ "js_int", "ruma-common", @@ -5217,7 +5185,7 @@ dependencies = [ [[package]] name = "ruminuwuity" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "assign", "http", @@ -5229,8 +5197,8 @@ dependencies = [ [[package]] name = "rust-librocksdb-sys" -version = "0.45.1+11.1.1" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +version = "0.49.0+11.12.0" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b" dependencies = [ "bindgen", "bzip2-sys", @@ -5240,14 +5208,15 @@ dependencies = [ "libz-sys", "lz4-sys", "pkg-config", + "rustflags", "tikv-jemalloc-sys", "zstd-sys", ] [[package]] name = "rust-rocksdb" -version = "0.49.1" -source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +version = "0.54.0" +source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b" dependencies = [ "libc", "parking_lot", @@ -5276,12 +5245,18 @@ dependencies = [ ] [[package]] -name = "rustix" -version = "1.1.4" +name = "rustflags" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.13.2", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -5290,9 +5265,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", @@ -5306,9 +5281,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -5328,9 +5303,9 @@ dependencies = [ [[package]] name = "rustls-platform-verifier" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation 0.10.1", "core-foundation-sys", @@ -5349,15 +5324,15 @@ dependencies = [ [[package]] name = "rustls-platform-verifier-android" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -5411,9 +5386,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -5432,9 +5407,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -5463,7 +5438,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", + "base16ct 0.2.0", "der 0.7.10", "generic-array", "pkcs8 0.10.2", @@ -5471,13 +5446,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.3", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.2", + "bitflags", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -5506,9 +5495,9 @@ dependencies = [ [[package]] name = "sentry" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d631477761f57c76148456e55e80e9a479ff3fa4c65b2b4a0c3acf1167fd4638" +checksum = "d7bc7fb14982f395d53924f4feebd48c6cc136399c49ac2160dcf2b260e74b75" dependencies = [ "cfg_aliases", "httpdate", @@ -5526,9 +5515,9 @@ dependencies = [ [[package]] name = "sentry-backtrace" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "448b0981fbde6cdc9eb087ba3dc01035a253fef9a0d9e79aaf198fc26acb2e64" +checksum = "f68328b53eb7defc20f993ed7cd1f4ce10d06feecefdf914db062ce2523e4b77" dependencies = [ "backtrace", "regex", @@ -5537,9 +5526,9 @@ dependencies = [ [[package]] name = "sentry-contexts" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5e909d02170ba6d1dc5ebd05bef7999280f5d960e3eaee5d1a18d88d41b334" +checksum = "1d57fb52d1e5d76cc5a7415428004699d9e6d498859a7acc8e05becc57dad81f" dependencies = [ "hostname", "libc", @@ -5551,22 +5540,21 @@ dependencies = [ [[package]] name = "sentry-core" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecf0b1a4a4e9ec88395b52e6fa4868b95564c1fa96b26a0606f5f6288a0f7149" +checksum = "8367f7f31654b35453e20c8aca06e0ecf5a4d4793e33be139c1581e475a94e6a" dependencies = [ - "rand 0.9.5", + "rand 0.10.4", "sentry-types", - "serde", "serde_json", "url", ] [[package]] name = "sentry-debug-images" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81d7749c57fc78ed52134889e8121da874065bc40da788d5798cce0f8c19f15" +checksum = "386f4ce2364e58f2ca811f388a0427fa13784bbe7aee85f302e901ef4b00fab9" dependencies = [ "findshlibs", "sentry-core", @@ -5574,20 +5562,20 @@ dependencies = [ [[package]] name = "sentry-log" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ffc7737b6d4f1cb3707284703c7364e9f5f056118abc523dd52e732f13cbe1" +checksum = "c938358d54c65a79fea165a447ae0eabc5717f23ba482ceee279c5645f0ccad3" dependencies = [ - "bitflags 2.13.2", + "bitflags", "log", "sentry-core", ] [[package]] name = "sentry-panic" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7d93d6ecb55d2251c5fc084c55c03a2bc68904918d76117e602c999e92f00f" +checksum = "2ab095af8f107e893941f857d8e204f5d25404247c34af131c7d199e3021679f" dependencies = [ "sentry-backtrace", "sentry-core", @@ -5595,9 +5583,9 @@ dependencies = [ [[package]] name = "sentry-tower" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a64a8a0a33239c65f95ff719fcb56655f398f4e4e74a01af8daca725cf7c2b5f" +checksum = "18f29b19179ae36e6318c71f6ee18d1e0db8bbe8e7b7f213c2aba9e721b650fb" dependencies = [ "http", "pin-project", @@ -5609,11 +5597,11 @@ dependencies = [ [[package]] name = "sentry-tracing" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58d26379236c4ef97eaf081bca3c7bf0ef6f06b3aa881eca2ee8e8dbc923e5b8" +checksum = "a7cae82b121a812e69a1cfaaacb800112f5f261f362fbf5a08e13d1c11ef349e" dependencies = [ - "bitflags 2.13.2", + "bitflags", "sentry-backtrace", "sentry-core", "tracing-core", @@ -5622,13 +5610,13 @@ dependencies = [ [[package]] name = "sentry-types" -version = "0.48.5" +version = "0.49.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2239099d47e76857b0825a182ecdb90159add7aa1097b60247c6e7ca6bf49c6a" +checksum = "03da7c1f79d001b4f18e277f8207470efb262fb94c761baa195873d2ace8eb8a" dependencies = [ "debugid", "hex", - "rand 0.9.5", + "rand 0.10.4", "serde", "serde_json", "thiserror 2.0.21", @@ -5649,9 +5637,9 @@ dependencies = [ [[package]] name = "serde-saphyr" -version = "1.3.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8050abb251097357e24aff63ba2c52a6309ecb7d23a5474023df960a02694d8" +checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", "base64 0.23.1", @@ -5691,7 +5679,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -5709,9 +5697,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -5761,9 +5749,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -5782,9 +5770,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" dependencies = [ "base64 0.23.1", "bs58", @@ -5794,7 +5782,7 @@ dependencies = [ "indexmap 2.14.2", "jiff", "schemars 0.9.0", - "schemars 1.2.2", + "schemars 1.2.3", "serde_core", "serde_json", "serde_with_macros", @@ -5803,14 +5791,24 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.23.0" +version = "3.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", ] [[package]] @@ -5848,9 +5846,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -5879,12 +5877,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - [[package]] name = "shlex" version = "2.0.1" @@ -5937,6 +5929,10 @@ name = "signature" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] [[package]] name = "simd-adler32" @@ -5962,9 +5958,9 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "slab" @@ -5984,9 +5980,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.1" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "serde", ] @@ -6009,11 +6005,11 @@ checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" [[package]] name = "spinning_top" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d96d2d1d716fb500937168cc09353ffdc7a012be8475ac7308e1bdf0e3923300" +checksum = "9cf02766a1eb909bc7653557c66b384e44edc3ad979e6257c6173c65ea51bc7d" dependencies = [ - "lock_api", + "lock_api 0.4.14", ] [[package]] @@ -6028,12 +6024,12 @@ dependencies = [ [[package]] name = "spki" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" dependencies = [ "base64ct", - "der 0.8.2", + "der 0.8.3", ] [[package]] @@ -6050,9 +6046,9 @@ checksum = "f42444fea5b87a39db4218d9422087e66a85d0e7a0963a439b07bcdf91804006" [[package]] name = "string_cache" -version = "0.8.9" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" dependencies = [ "new_debug_unreachable", "parking_lot", @@ -6063,9 +6059,9 @@ dependencies = [ [[package]] name = "string_cache_codegen" -version = "0.5.4" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" dependencies = [ "phf_generator", "phf_shared", @@ -6098,9 +6094,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -6118,13 +6114,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -6133,7 +6129,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags 2.13.2", + "bitflags", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -6156,20 +6152,18 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" [[package]] name = "tendril" -version = "0.4.3" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" dependencies = [ - "futf", - "mac", - "utf-8", + "new_debug_unreachable", ] [[package]] name = "termimad" -version = "0.35.4" +version = "0.35.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2374179aac8b77011a1aefe2f44d0c34eb680c9b4bd1c369a88991262c60c85a" +checksum = "092b11fb38404fa873f019f8e5f300fa5787f381b7a58b923546d94b5a9065fd" dependencies = [ "coolor", "crokey", @@ -6228,7 +6222,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -6242,18 +6236,17 @@ dependencies = [ [[package]] name = "tikv-jemalloc-ctl" -version = "0.6.1" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "libc", - "paste", "tikv-jemalloc-sys", ] [[package]] name = "tikv-jemalloc-sys" -version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "cc", "libc", @@ -6261,8 +6254,8 @@ dependencies = [ [[package]] name = "tikv-jemallocator" -version = "0.6.1" -source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +version = "0.7.0" +source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92" dependencies = [ "libc", "tikv-jemalloc-sys", @@ -6300,9 +6293,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -6316,9 +6309,9 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -6339,7 +6332,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -6356,9 +6349,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.5" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -6377,9 +6370,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -6403,17 +6396,17 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.2.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" dependencies = [ "indexmap 2.14.2", "serde_core", - "serde_spanned 1.1.1", - "toml_datetime 1.1.1+spec-1.1.0", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", "toml_writer", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -6427,9 +6420,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -6450,23 +6443,23 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.15+spec-1.1.0" +version = "0.25.19+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" dependencies = [ "indexmap 2.14.2", - "toml_datetime 1.1.1+spec-1.1.0", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.6+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" dependencies = [ - "winnow 1.0.4", + "winnow 1.0.5", ] [[package]] @@ -6477,15 +6470,15 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tonic" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" dependencies = [ "async-trait", "axum", @@ -6504,6 +6497,7 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-stream", + "tokio-util", "tower", "tower-layer", "tower-service", @@ -6512,9 +6506,9 @@ dependencies = [ [[package]] name = "tonic-prost" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" +checksum = "eba464054e2226f182a34489b8b079bf4c6e3e7ab5fd7fc30e024f24aa92a484" dependencies = [ "bytes", "prost", @@ -6523,9 +6517,9 @@ dependencies = [ [[package]] name = "tonic-types" -version = "0.14.6" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" +checksum = "ccbb6c31deb8e99dcdf87df19c5289b7838a600da74a8224baa671e52fe7c5ad" dependencies = [ "prost", "prost-types", @@ -6574,7 +6568,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags", "bytes", "futures-core", "futures-util", @@ -6597,7 +6591,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" dependencies = [ "async-compression", - "bitflags 2.13.2", + "bitflags", "bytes", "futures-core", "futures-util", @@ -6622,9 +6616,9 @@ checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" [[package]] name = "tower-sec-fetch" -version = "0.1.2" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff1e78d241de2527d3ef67e49d65d8cb08468c644c3aafac7a988c4accd76547" +checksum = "88a13d0fc16129bf9e98fb869f369e867090afab7730d91ab4f68084bd037093" dependencies = [ "futures", "http", @@ -6814,15 +6808,15 @@ dependencies = [ [[package]] name = "unicase" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" @@ -6838,9 +6832,9 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "universal-hash" @@ -6848,7 +6842,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "crypto-common 0.1.6", + "crypto-common 0.1.7", "subtle", ] @@ -6860,9 +6854,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -6878,22 +6872,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" [[package]] -name = "utf-8" -version = "0.7.6" +name = "utf8_iter" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] [[package]] -name = "utf8_iter" -version = "1.0.4" +name = "utf_types" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.26.1" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -6959,9 +6956,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -6983,12 +6980,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -6996,19 +6992,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.78" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -7016,22 +7013,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.128" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -7059,15 +7056,15 @@ dependencies = [ "ece-native", "hkdf 0.13.0", "http", - "p256", - "sha2 0.11.0", + "p256 0.13.2", + "sha2 0.11.1", ] [[package]] name = "web-sys" -version = "0.3.105" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -7084,10 +7081,22 @@ dependencies = [ ] [[package]] -name = "webpage" -version = "2.0.1" +name = "web_atoms" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70862efc041d46e6bbaa82bb9c34ae0596d090e86cbd14bd9e93b36ee6802eac" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" +dependencies = [ + "phf", + "phf_codegen", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "webpage" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5547a459b8cab203b5bf7d1f97855b3d6ae706da7c93773328614309432c9e4c" dependencies = [ "html5ever", "markup5ever_rcdom", @@ -7097,18 +7106,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webpki-roots" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] @@ -7127,9 +7127,9 @@ checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" [[package]] name = "wildmatch" -version = "2.6.1" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29333c3ea1ba8b17211763463ff24ee84e41c78224c16b001cd907e663a38c68" +checksum = "f18219fbd41a807dec044965d4106bb4fdb1d3a4b70aac4e5510aacc80a9f140" [[package]] name = "winapi" @@ -7325,9 +7325,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] @@ -7338,6 +7338,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" @@ -7346,18 +7358,17 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xml5ever" -version = "0.18.1" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bbb26405d8e919bc1547a5aa9abc95cbfa438f04844f5fdd9dc7596b748bf69" +checksum = "5ab627f34ff61b80d756180d556f9c68801d836d271b3b8c094504ceca69d221" dependencies = [ "log", - "mac", "markup5ever", ] [[package]] name = "xtask" -version = "26.9.1" +version = "26.11.0-alpha.2" dependencies = [ "askama", "cargo_metadata", @@ -7373,9 +7384,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -7384,30 +7395,30 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", "synstructure", ] [[package]] name = "zerocopy" -version = "0.8.57" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.57" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -7425,21 +7436,21 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" @@ -7454,9 +7465,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -7465,20 +7476,20 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "zlib-rs" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" [[package]] name = "zmij" @@ -7488,27 +7499,27 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" -version = "0.14.0" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "8.0.0" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.0+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/Cargo.toml b/Cargo.toml index fc1b2ef88..4732335cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,17 +12,17 @@ license = "Apache-2.0" # See also `rust-toolchain.toml` readme = "README.md" repository = "https://forgejo.ellis.link/continuwuation/continuwuity" -version = "26.9.1" +version = "26.11.0-alpha.2" [workspace.metadata.crane] name = "conduwuit" [workspace.dependencies.arrayvec] -version = "0.7.6" +version = "0.7.8" features = ["serde"] [workspace.dependencies.smallvec] -version = "1.14.0" +version = "1.16.5" features = [ "const_generics", "const_new", @@ -39,10 +39,10 @@ features = ["ffi", "std", "union"] version = "1.1.0" [workspace.dependencies.ctor] -version = "1.0.6" +version = "1.0.13" [workspace.dependencies.dtor] -version = "1.0.0" +version = "1.0.6" [workspace.dependencies.cargo_toml] version = "1.0" @@ -50,7 +50,7 @@ default-features = false features = ["features"] [workspace.dependencies.toml] -version = "1.1.2" +version = "1.2.1" default-features = false features = ["parse", "serde"] @@ -58,7 +58,7 @@ features = ["parse", "serde"] version = "0.6.0" [workspace.dependencies.base64] -version = "0.23.0" +version = "0.23.1" default-features = false # used for TURN server authentication @@ -71,39 +71,40 @@ version = "0.5.0" default-features = false [workspace.dependencies.p256] -version = "0.13.2" +version = "0.14.0" default-features = false features = ["ecdsa", "std"] # used for checking if an IP is in specific subnets / CIDR ranges easier [workspace.dependencies.ipaddress] -version = "0.2.0" +version = "0.2.11" [workspace.dependencies.rand] -version = "0.10.1" +version = "0.10.3" # Used for the http request / response body type for Ruma endpoints used with reqwest [workspace.dependencies.bytes] -version = "1.10.1" +version = "1.12.1" [workspace.dependencies.http-body-util] -version = "0.1.3" +version = "0.1.5" [workspace.dependencies.http] -version = "1.3.1" +version = "1.5.0" # parses the HTTP-date form of Retry-After [workspace.dependencies.httpdate] version = "1.0.3" [workspace.dependencies.regex] -version = "1.11.1" +version = "1.13.1" [workspace.dependencies.axum] -version = "0.8.8" +version = "0.8.9" default-features = false features = [ "form", + "query", "http1", "http2", "json", @@ -113,7 +114,7 @@ features = [ ] [workspace.dependencies.axum-extra] -version = "0.12.0" +version = "0.12.6" default-features = false features = ["typed-header", "tracing", "cookie"] @@ -132,12 +133,12 @@ default-features = false version = "0.2" [workspace.dependencies.tower] -version = "0.5.2" +version = "0.5.3" default-features = false features = ["util"] [workspace.dependencies.tower-http] -version = "0.7.0" +version = "0.7.1" default-features = false features = [ "add-extension", @@ -151,38 +152,46 @@ features = [ ] [workspace.dependencies.rustls] -version = "0.23.25" +version = "0.23.46" default-features = false [workspace.dependencies.reqwest] -version = "0.13.2" +version = "0.13.5" default-features = false features = [ "rustls-no-provider", "socks", - "hickory-dns", "http2", "stream", "form", ] +# Needed for as long as openidconnect is on an outdated reqwest +[workspace.dependencies.reqwest_0_12] +package = "reqwest" +version = "0.12" +default-features = false +features = [ + "rustls-tls-native-roots-no-provider", +] + [workspace.dependencies.serde] -version = "1.0.219" +version = "1.0.229" default-features = false features = ["rc"] [workspace.dependencies.serde_json] -version = "1.0.140" +version = "1.0.154" default-features = false features = ["raw_value"] # Used for appservice registration files [workspace.dependencies.serde-saphyr] -version = "1.0.0" +version = "2.1.1" # Used to load forbidden room/user regex from config [workspace.dependencies.serde_regex] -version = "1.1.0" +version = "1.2.0" # Used for password hashing [workspace.dependencies.argon2] @@ -192,7 +201,7 @@ default-features = false # Used to generate thumbnails for images [workspace.dependencies.image] -version = "0.25.5" +version = "0.25.10" default-features = false features = [ "jpeg", @@ -203,29 +212,29 @@ features = [ # logging [workspace.dependencies.log] -version = "0.4.27" +version = "0.4.35" default-features = false [workspace.dependencies.tracing] -version = "0.1.41" +version = "0.1.44" default-features = false [workspace.dependencies.tracing-subscriber] -version = "0.3.20" +version = "0.3.23" default-features = false features = ["env-filter", "std", "tracing", "tracing-log", "ansi", "fmt"] [workspace.dependencies.tracing-journald] -version = "0.3.1" +version = "0.3.2" [workspace.dependencies.tracing-core] -version = "0.1.34" +version = "0.1.36" default-features = false # for URL previews [workspace.dependencies.webpage] -version = "2.0.1" +version = "2.1.0" default-features = false # used for conduwuit's CLI and admin room command parsing [workspace.dependencies.clap] -version = "4.5.35" +version = "4.6.7" default-features = false features = [ "derive", @@ -238,12 +247,12 @@ features = [ ] [workspace.dependencies.futures] -version = "0.3.31" +version = "0.3.34" default-features = false features = ["std", "async-await"] [workspace.dependencies.tokio] -version = "1.44.2" +version = "1.54.1" default-features = false features = [ "fs", @@ -258,25 +267,25 @@ features = [ ] [workspace.dependencies.tokio-metrics] -version = "0.5.0" +version = "0.5.2" -[workspace.dependencies.libloading] -version = "0.9.0" +[workspace.dependencies.wildmatch] +version = "2.7.0" # Validating urls in config, was already a transitive dependency [workspace.dependencies.url] -version = "2.5.4" +version = "2.5.8" default-features = false features = ["serde"] # standard date and time tools [workspace.dependencies.chrono] -version = "0.4.38" +version = "0.4.45" features = ["alloc", "std"] default-features = false [workspace.dependencies.hyper] -version = "1.6.0" +version = "1.12.0" default-features = false features = [ "server", @@ -295,7 +304,7 @@ features = [ # to support multiple variations of setting a config option [workspace.dependencies.either] -version = "1.15.0" +version = "1.19.0" default-features = false features = ["serde"] @@ -306,7 +315,7 @@ default-features = false features = ["env", "toml"] [workspace.dependencies.hickory-resolver] -version = "0.26.0" +version = "0.26.3" default-features = false features = [ "serde", @@ -316,7 +325,7 @@ features = [ # Used for conduwuit::Error type [workspace.dependencies.thiserror] -version = "2.0.12" +version = "2.0.21" default-features = false # Used to make working with iterators easier, was already a transitive depdendency @@ -330,14 +339,14 @@ version = "2.1.1" # used for MPSC channels [workspace.dependencies.loole] -version = "0.4.0" +version = "0.6.0" # used for MPMC channels [workspace.dependencies.async-channel] version = "2.5.0" [workspace.dependencies.async-trait] -version = "0.1.88" +version = "0.1.92" [workspace.dependencies.lru-cache] version = "0.1.2" @@ -348,7 +357,7 @@ version = "1.1.1" # Used for matrix spec type definitions and helpers [workspace.dependencies.ruma] git = "https://github.com/ruma/ruma.git" -rev = "f5e5e1c885f598036fd4326c566e9d1928027d5d" +rev = "472a23ef86bc0bb40a22d856fc0af539eb9d71b7" features = [ "appservice-api-c", "client-api", @@ -383,17 +392,19 @@ features = [ "unstable-msc4406", "unstable-msc4439", "unstable-msc4354", + "unstable-msc4388", "unstable-msc4480", "unstable-msc4466", "unstable-msc4494", "unstable-msc4484", "unstable-msc4540", + "unstable-msc4560", "unstable-extensible-events", ] [workspace.dependencies.rust-rocksdb] git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1" -rev = "0a25ff92f7c09b55eec496b9c192c7d5136ab2b8" +rev = "85ded20348e3dab902c239967075795e9c6d101b" default-features = false features = [ "multi-threaded-cf", @@ -404,7 +415,7 @@ features = [ ] [workspace.dependencies.sha2] -version = "0.11.0" +version = "0.11.1" default-features = false [workspace.dependencies.sha1] @@ -412,19 +423,22 @@ version = "0.11.0" default-features = false [workspace.dependencies.openidconnect] -version = "4.0.1" +version = "4.1.0" +default-features = false +features = ["reqwest"] # optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring [workspace.dependencies.opentelemetry] -version = "0.33.0" +version = "0.33.1" [workspace.dependencies.opentelemetry-instrumentation-tower] -version = "0.19.0" +git = "https://github.com/open-telemetry/opentelemetry-rust-contrib" +rev = "6bbbc337aab0bcf10d7799c3e5b5ced75920491a" default-features = false features = ["axum"] [workspace.dependencies.opentelemetry-semantic-conventions] -version = "0.33.0" +version = "0.33.1" features = ["semconv_experimental"] [workspace.dependencies.tracing-flame] @@ -434,25 +448,25 @@ version = "0.2.0" version = "0.34.0" [workspace.dependencies.opentelemetry_sdk] -version = "0.33.0" +version = "0.33.1" features = ["rt-tokio"] [workspace.dependencies.opentelemetry-prometheus] -version = "0.33.0" +version = "0.33.1" [workspace.dependencies.prometheus] version = "0.14.0" default-features = false [workspace.dependencies.opentelemetry-otlp] -version = "0.33.0" +version = "0.33.1" features = ["http", "grpc-tonic", "trace", "logs", "metrics"] # optional sentry metrics for crash/panic reporting [workspace.dependencies.sentry] -version = "0.48.0" +version = "0.49.5" default-features = false features = [ "backtrace", @@ -467,14 +481,14 @@ features = [ ] [workspace.dependencies.sentry-tracing] -version = "0.48.0" +version = "0.49.5" [workspace.dependencies.sentry-tower] -version = "0.48.0" +version = "0.49.5" # jemalloc usage [workspace.dependencies.tikv-jemalloc-sys] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = [ "background_threads_runtime_support", @@ -482,7 +496,7 @@ features = [ ] [workspace.dependencies.tikv-jemallocator] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = [ "background_threads_runtime_support", @@ -490,7 +504,7 @@ features = [ ] [workspace.dependencies.tikv-jemalloc-ctl] git = "https://forgejo.ellis.link/continuwuation/jemallocator" -rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554" +rev = "46e7821917b06636cdb5b203d312799970eaea92" default-features = false features = ["use_std"] @@ -498,7 +512,7 @@ features = ["use_std"] version = "0.5" [workspace.dependencies.nix] -version = "0.31.0" +version = "0.31.3" default-features = false features = ["resource"] @@ -506,21 +520,12 @@ features = ["resource"] version = "0.5.0" default-features = false -[workspace.dependencies.hardened_malloc-rs] -version = "0.1.2" -default-features = false -features = [ - "static", - "gcc", - "light", -] - [workspace.dependencies.rustyline-async] version = "0.4.9" default-features = false [workspace.dependencies.termimad] -version = "0.35.0" +version = "0.35.5" default-features = false [workspace.dependencies.checked_ops] @@ -543,10 +548,10 @@ features = ["hardware-lock-elision", "deadlock_detection"] # TODO: Check if dead # Use this when extending with_lock::WithLock to parking_lot [workspace.dependencies.lock_api] -version = "0.4.13" +version = "0.5.0" [workspace.dependencies.bytesize] -version = "2.0" +version = "2.7" [workspace.dependencies.core_affinity] version = "0.8.3" @@ -558,11 +563,11 @@ version = "0.2" version = "0.2" [workspace.dependencies.minicbor] -version = "2.1.1" +version = "2.3.1" features = ["std"] [workspace.dependencies.minicbor-serde] -version = "0.7.0" +version = "0.7.2" features = ["std"] [workspace.dependencies.maplit] @@ -572,10 +577,10 @@ version = "1.0.2" version = "1.0.1" [workspace.dependencies.askama] -version = "0.16.0" +version = "0.16.1" [workspace.dependencies.lettre] -version = "0.11.19" +version = "0.11.23" default-features = false features = ["smtp-transport", "pool", "hostname", "builder", "rustls", "rustls-native-certs", "tokio1", "rustls-no-provider", "tokio1-rustls", "tracing", "serde"] @@ -584,15 +589,27 @@ version = "0.10.4" default-features = false features = ["std"] +[workspace.dependencies.mime] +version = "0.3.18" + [workspace.dependencies.nonzero_ext] version = "0.3.0" [workspace.dependencies.resolvematrix] -version = "1.3.0" +version = "1.5.0" +features = ["unstable-msc4188"] [workspace.dependencies.serde_urlencoded] version = "0.7.1" +[workspace.dependencies.mimalloc] +version = "0.1.52" +features = ["extended"] + +[workspace.dependencies.libmimalloc-sys] +version = "0.1.49" +features = ["extended"] + # # Patches # @@ -736,74 +753,23 @@ inherits = "release" # Developer profile # -# To enable hot-reloading: -# 1. Uncomment all of the rustflags here. -# 2. Uncomment crate-type=dylib in src/*/Cargo.toml -# -# opt-level, mir-opt-level, validate-mir are not known to interfere with reloading -# and can be raised if build times are tolerable. - [profile.dev] debug = "full" opt-level = 0 panic = "unwind" debug-assertions = true incremental = true -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=false', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,-z,keep-text-section-prefix', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.conduwuit_core] inherits = "dev" [profile.dev.package.conduwuit] inherits = "dev" -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zexport-executable-symbols=true', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,--export-dynamic', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.'*'] inherits = "dev" debug = 'limited' codegen-units = 1 opt-level = 'z' -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=true', -# '-Zplt=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,-z,lazy', -# '-Clink-arg=-Wl,-z,nodelete', -#] # primarily used for CI [profile.test] @@ -1008,4 +974,7 @@ collapsible_if = "allow" cognitive_complexity = "allow" [workspace.metadata.cargo-shear] -ignored = ["const-str", "ctor", "dtor"] +# All of these crates provide macros that are used across the codebase +# and that every crate depends on. cargo-shear can't tell this because +# it doesn't expand macros. +ignored = ["const-str", "ctor", "dtor", "tracing"] diff --git a/SECURITY.md b/SECURITY.md index b386a571f..913992235 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,12 +23,15 @@ to encourage users to stay up-to-date with the latest release, and we have no co We appreciate the efforts of security researchers and the community in identifying and reporting vulnerabilities. To ensure that potential vulnerabilities are addressed properly, please follow these guidelines: -1. **Contact members of the team directly** over E2EE private message. +1. **Contact _all_ members of the team** over E2EE private message on Matrix. + Add each contact to the same encrypted room. **Do not message maintainers individually**. + If you cannot reach us from matrix.org, please try [another server][sl] (e.g. continuwuity.rocks). - [@jade:ellis.link](https://matrix.to/#/@jade:ellis.link) - [@nex:nexy7574.co.uk](https://matrix.to/#/@nex:nexy7574.co.uk) - [@ginger:gingershaped.computer](https://matrix.to/#/@ginger:gingershaped.computer) 2. **Email the security team** at [security@continuwuity.org](mailto:security@continuwuity.org). This is not E2EE, so - don't include sensitive details. + don't include sensitive details. Do not ask where to send sensitive details either; that + information is included in this security policy. We may not respond to emails that do this. 3. **Do not disclose the vulnerability publicly** until a fix has been pushed to the main branch. 4. **Provide detailed information** about the vulnerability, including: - A clear description of the issue @@ -42,6 +45,8 @@ ensure that potential vulnerabilities are addressed properly, please follow thes If you have any doubts about a potential security vulnerability, contact us via private channels first! We'd prefer that you bother us, instead of having a vulnerability disclosed without a fix. +[sl]: https://servers.joinmatrix.org + ### Terms for credit Before reporting a vulnerability, please remember that we are a small team maintaining a large codebase depended upon by @@ -105,4 +110,4 @@ When security vulnerabilities are identified: --- -This security policy was last updated on May 25, 2025. +This security policy was last updated on November 17th, 2026. diff --git a/bin/complement b/bin/complement index f1ac017d1..0d5a56e98 100755 --- a/bin/complement +++ b/bin/complement @@ -52,8 +52,10 @@ else fi # The base docker image to use for complement tests -# You can build the default with `docker build -t continuwuity:complement -f ./docker/complement.Dockerfile .` -# after running `cargo build`. Only the debug binary is used. +# On Linux, you can build the default with `docker build -t continuwuity:complement -f ./docker/complement.Dockerfile .` +# after running `cargo build -p conduwuit --features openreg`. +# On non-Linux platforms (or to use a container build), build `docker/Dockerfile` with debuginfo and openreg `--build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg` +# and then run `docker build -t continuwuity:complement --target container -f ./docker/complement.Dockerfile .`. COMPLEMENT_BASE_IMAGE="${COMPLEMENT_BASE_IMAGE:-continuwuity:complement}" # Complement tests that are skipped due to flakiness/reliability issues or we don't implement such features and won't for a long time @@ -83,6 +85,13 @@ for command in docker go jq; do fi done +if [ -z "${DOCKER_HOST:-}" ]; then + DOCKER_HOST="$(docker context inspect --format '{{.Endpoints.docker.Host}}' 2>/dev/null || true)" + if [ -n "$DOCKER_HOST" ]; then + export DOCKER_HOST + fi +fi + if [ -n "$IMAGE_ARCHIVE" ]; then if [ ! -f "$IMAGE_ARCHIVE" ]; then echo "Docker image archive not found: $IMAGE_ARCHIVE" @@ -99,7 +108,12 @@ fi if ! docker image inspect "$COMPLEMENT_BASE_IMAGE" > /dev/null 2>&1; then echo "Complement base image not found: $COMPLEMENT_BASE_IMAGE" - echo "Build it with: cargo build -p conduwuit && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." + if [ "$(uname -s)" != "Linux" ]; then + echo "Build it with: docker buildx build --load -t continuwuity:latest-openreg --build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg -f docker/Dockerfile . && docker build -t $COMPLEMENT_BASE_IMAGE --target container -f docker/complement.Dockerfile ." + else + echo "Build it with: cargo build -p conduwuit --features openreg && docker build -t $COMPLEMENT_BASE_IMAGE -f docker/complement.Dockerfile ." + echo "Or from a container build: docker buildx build --load -t continuwuity:latest-openreg --build-arg RUST_PROFILE=dev --build-arg CARGO_FEATURES=default,openreg -f docker/Dockerfile . && docker build -t $COMPLEMENT_BASE_IMAGE --target container -f docker/complement.Dockerfile ." + fi exit 1 fi diff --git a/changelog.d/+01d550e6.feature.md b/changelog.d/+01d550e6.feature.md new file mode 100644 index 000000000..bb9a865ac --- /dev/null +++ b/changelog.d/+01d550e6.feature.md @@ -0,0 +1,3 @@ +Implemented unstable support for [MSC4560] (Stripped state requests over federation). Contributed by @ginger. + +[MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 diff --git a/changelog.d/+4a4ebd67.misc.md b/changelog.d/+4a4ebd67.misc.md new file mode 100644 index 000000000..f36da4938 --- /dev/null +++ b/changelog.d/+4a4ebd67.misc.md @@ -0,0 +1 @@ +Upgraded rocksdb from 11.1.1 to 11.12.0 and jemalloc to 5.4.0. diff --git a/changelog.d/+74cd7995.feature.md b/changelog.d/+74cd7995.feature.md new file mode 100644 index 000000000..da20c50ae --- /dev/null +++ b/changelog.d/+74cd7995.feature.md @@ -0,0 +1 @@ +Check content-type header on federation responses, ignoring any that don't match (spec compliance) diff --git a/changelog.d/+8da3c370.feature.md b/changelog.d/+8da3c370.feature.md new file mode 100644 index 000000000..b561f4e97 --- /dev/null +++ b/changelog.d/+8da3c370.feature.md @@ -0,0 +1 @@ +The first-run version of the web UI now includes a link to the registration page. Contributed by @ginger diff --git a/changelog.d/+account-data-replaced-entries.bugfix.md b/changelog.d/+account-data-replaced-entries.bugfix.md new file mode 100644 index 000000000..c3751d5a9 --- /dev/null +++ b/changelog.d/+account-data-replaced-entries.bugfix.md @@ -0,0 +1 @@ +Fix account data updates sent at the same time leaving old copies behind, which every initial sync then returned. Existing copies are removed on startup. Contributed by @eleboucher. diff --git a/changelog.d/+b5e913f8.bugfix.md b/changelog.d/+b5e913f8.bugfix.md new file mode 100644 index 000000000..cea4cfece --- /dev/null +++ b/changelog.d/+b5e913f8.bugfix.md @@ -0,0 +1 @@ +Room summary visibility checks are no longer incorrectly applied for remote rooms. Contributed by @ginger. diff --git a/changelog.d/+create-room-bad-json.bugfix.md b/changelog.d/+create-room-bad-json.bugfix.md new file mode 100644 index 000000000..7bba2bd13 --- /dev/null +++ b/changelog.d/+create-room-bad-json.bugfix.md @@ -0,0 +1 @@ +Creating a room with valid but non-canonical JSON now returns `400 M_BAD_JSON` instead of panicking the worker and returning `500 M_UNKNOWN`. diff --git a/changelog.d/+device-list-count-race.bugfix.md b/changelog.d/+device-list-count-race.bugfix.md new file mode 100644 index 000000000..ef40e7e07 --- /dev/null +++ b/changelog.d/+device-list-count-race.bugfix.md @@ -0,0 +1 @@ +Fix new devices sometimes never reaching other users' device lists. Contributed by @eleboucher. diff --git a/changelog.d/+f05dfc14.doc.md b/changelog.d/+f05dfc14.doc.md new file mode 100644 index 000000000..542314fb9 --- /dev/null +++ b/changelog.d/+f05dfc14.doc.md @@ -0,0 +1 @@ +The documentation now refers to the Continuwuity Docker service as `continuwuity` instead of `homeserver`. diff --git a/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md b/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md new file mode 100644 index 000000000..76c5a059f --- /dev/null +++ b/changelog.d/+gap-fill-outlier-missing-prevs.bugfix.md @@ -0,0 +1 @@ +Fix gap filling skipping outlier events that are missing their previous events. Contributed by @eleboucher. diff --git a/changelog.d/+local-join-forbidden.bugfix.md b/changelog.d/+local-join-forbidden.bugfix.md new file mode 100644 index 000000000..3e5b62d94 --- /dev/null +++ b/changelog.d/+local-join-forbidden.bugfix.md @@ -0,0 +1 @@ +Joining a local room the user is not allowed to join now returns `403 M_FORBIDDEN` instead of `500 M_UNKNOWN` when there are no other servers to try. diff --git a/changelog.d/+msc2815-unredacted-content.feature.md b/changelog.d/+msc2815-unredacted-content.feature.md new file mode 100644 index 000000000..f38ba7d91 --- /dev/null +++ b/changelog.d/+msc2815-unredacted-content.feature.md @@ -0,0 +1 @@ +Added support for [MSC2815](https://github.com/matrix-org/matrix-spec-proposals/pull/2815), allowing room moderators to fetch the original content of redacted events, behind the `allow_moderators_to_view_redacted_content` config option. Contributed by @eleboucher. diff --git a/changelog.d/+remove-legacy-media.feature.md b/changelog.d/+remove-legacy-media.feature.md new file mode 100644 index 000000000..59ed76bc0 --- /dev/null +++ b/changelog.d/+remove-legacy-media.feature.md @@ -0,0 +1 @@ +Remove support for legacy, unauthenticated media, including the `allow_legacy_media` and `freeze_legacy_media` options. diff --git a/changelog.d/+state-before-forks.bugfix.md b/changelog.d/+state-before-forks.bugfix.md new file mode 100644 index 000000000..70e3eadd7 --- /dev/null +++ b/changelog.d/+state-before-forks.bugfix.md @@ -0,0 +1 @@ +Fix incoming federation events losing state changes when predecessors share the same state-before snapshot. Contributed by @eleboucher. diff --git a/changelog.d/+state-res-auth-order.bugfix.md b/changelog.d/+state-res-auth-order.bugfix.md new file mode 100644 index 000000000..cbb961545 --- /dev/null +++ b/changelog.d/+state-res-auth-order.bugfix.md @@ -0,0 +1 @@ +Fix state resolution applying events out of order, which could undo room joins. Contributed by @eleboucher. diff --git a/changelog.d/+sync-v3-filter.bugfix.md b/changelog.d/+sync-v3-filter.bugfix.md new file mode 100644 index 000000000..14d6d1d2a --- /dev/null +++ b/changelog.d/+sync-v3-filter.bugfix.md @@ -0,0 +1 @@ +Legacy `/sync` now honours the `room.rooms`, `room.not_rooms`, `account_data.types` and `account_data.not_types` filter fields instead of returning every room and all account data. Contributed by @eleboucher. diff --git a/changelog.d/+timestamp-to-event.feature.md b/changelog.d/+timestamp-to-event.feature.md new file mode 100644 index 000000000..c1f903968 --- /dev/null +++ b/changelog.d/+timestamp-to-event.feature.md @@ -0,0 +1 @@ +Added the `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` endpoint as per MSC3030, letting clients find the event closest to a given timestamp. Contributed by @eleboucher. diff --git a/changelog.d/+to-device-count-race.bugfix.md b/changelog.d/+to-device-count-race.bugfix.md new file mode 100644 index 000000000..57b847f00 --- /dev/null +++ b/changelog.d/+to-device-count-race.bugfix.md @@ -0,0 +1 @@ +Fix to-device messages, including room keys, sometimes being lost before delivery. Contributed by @eleboucher. diff --git a/changelog.d/2324.doc..md b/changelog.d/2324.doc..md new file mode 100644 index 000000000..3d767b04b --- /dev/null +++ b/changelog.d/2324.doc..md @@ -0,0 +1 @@ +Add a section on [troubleshooting Docker issues](https://continuwuity.org/troubleshooting#docker-issues). Contributed by @stratself. diff --git a/changelog.d/2341.doc.md b/changelog.d/2341.doc.md new file mode 100644 index 000000000..16438a402 --- /dev/null +++ b/changelog.d/2341.doc.md @@ -0,0 +1 @@ +Instructions for Authelia added to the [OIDC guide](https://continuwuity.org/authentication/oidc.html). Contributed by @fhoekstra diff --git a/changelog.d/2351.bugfix.md b/changelog.d/2351.bugfix.md new file mode 100644 index 000000000..873310447 --- /dev/null +++ b/changelog.d/2351.bugfix.md @@ -0,0 +1 @@ +Fix some possible deadlocks/freezes and reduce lock contention (improving performance). Contributed by @Jade diff --git a/changelog.d/2353.doc.md b/changelog.d/2353.doc.md new file mode 100644 index 000000000..38722d0bc --- /dev/null +++ b/changelog.d/2353.doc.md @@ -0,0 +1 @@ +Docker compose examples now use bind mounts by default, instead of Docker volumes, as they are easier to work with esp. for backup/restore. Contributed by @stratself. diff --git a/changelog.d/2354.bugfix.md b/changelog.d/2354.bugfix.md new file mode 100644 index 000000000..45670f1bb --- /dev/null +++ b/changelog.d/2354.bugfix.md @@ -0,0 +1 @@ +Fixed Prometheus accounting for in-flight requests, federation PDU lag, latency buckets, and thumbnail sizes. Contributed by @eleboucher. diff --git a/changelog.d/2355.feature.md b/changelog.d/2355.feature.md new file mode 100644 index 000000000..f76ef7211 --- /dev/null +++ b/changelog.d/2355.feature.md @@ -0,0 +1 @@ +Added support for servers returning 410 gone to indicate they are no longer serving a Matrix server (MSC4188). Contributed by @nex and @silversys diff --git a/changelog.d/2356.bugfix.md b/changelog.d/2356.bugfix.md new file mode 100644 index 000000000..2836d94f2 --- /dev/null +++ b/changelog.d/2356.bugfix.md @@ -0,0 +1 @@ +Once again fixed how room extremities are handled, fixing a problem that made continuwuity gradually make rooms needlessly complex, which also caused more frequent state resets. diff --git a/changelog.d/2361.bugfix.md b/changelog.d/2361.bugfix.md new file mode 100644 index 000000000..a0bc00bfc --- /dev/null +++ b/changelog.d/2361.bugfix.md @@ -0,0 +1 @@ +Requests waiting on `/_matrix/client/v3/sync` can now be interrupted by the server shutdown, unblocking the 30-second shutdown delay imposed on a quiet server. diff --git a/changelog.d/2383.bugfix.md b/changelog.d/2383.bugfix.md new file mode 100644 index 000000000..5a551ede9 --- /dev/null +++ b/changelog.d/2383.bugfix.md @@ -0,0 +1 @@ +The OAuth identity reset page is no longer linked from the account management UI to reduce confusion. Contributed by @ginger. diff --git a/changelog.d/2387.bugfix.md b/changelog.d/2387.bugfix.md new file mode 100644 index 000000000..7c82bdffd --- /dev/null +++ b/changelog.d/2387.bugfix.md @@ -0,0 +1 @@ +Fixed a worker panic when knocking on a room over federation. Contributed by @eleboucher. diff --git a/changelog.d/2400.bugfix.md b/changelog.d/2400.bugfix.md new file mode 100644 index 000000000..406586732 --- /dev/null +++ b/changelog.d/2400.bugfix.md @@ -0,0 +1 @@ +Perform more validation on events received during atomic gapfill from remote servers, fixing a panic if bad data was persisted by another server and later lazily fetched by us. diff --git a/changelog.d/2415.bugfix b/changelog.d/2415.bugfix new file mode 100644 index 000000000..75fbffad8 --- /dev/null +++ b/changelog.d/2415.bugfix @@ -0,0 +1 @@ +Fix remote server key signature verification when extra fields exist. Contributed by @hexchen diff --git a/changelog.d/2421.bugfix.md b/changelog.d/2421.bugfix.md new file mode 100644 index 000000000..f5c1e842d --- /dev/null +++ b/changelog.d/2421.bugfix.md @@ -0,0 +1 @@ +Redirect URIs in OAuth clients' metadata are now properly validated to be on a subdomain of the OAuth issuer URL domain. Contributed by @ginger. diff --git a/changelog.d/2423.misc.md b/changelog.d/2423.misc.md new file mode 100644 index 000000000..bb1cb186c --- /dev/null +++ b/changelog.d/2423.misc.md @@ -0,0 +1 @@ +Updated internal Sentry integration setup to the new pattern required by the SDK. diff --git a/changelog.d/2424.bugfix.md b/changelog.d/2424.bugfix.md new file mode 100644 index 000000000..be4e5be70 --- /dev/null +++ b/changelog.d/2424.bugfix.md @@ -0,0 +1 @@ +Fix v12 rooms created by the same user in the same millisecond ending up as the same room. Contributed by @eleboucher. diff --git a/changelog.d/2429.feature.md b/changelog.d/2429.feature.md new file mode 100644 index 000000000..a2b595fb5 --- /dev/null +++ b/changelog.d/2429.feature.md @@ -0,0 +1 @@ +Added support for MSC4388, allowing compatible Matrix clients to log in to Continuwuity by scanning a QR code on an already logged-in client. Contributed by @ginger. diff --git a/changelog.d/2444.bugfix.md b/changelog.d/2444.bugfix.md new file mode 100644 index 000000000..27d87e4d0 --- /dev/null +++ b/changelog.d/2444.bugfix.md @@ -0,0 +1 @@ +Client-server API endpoints are now properly ratelimited for unauthenticated requests. Contributed by @ginger. diff --git a/changelog.d/2448.bugfix.md b/changelog.d/2448.bugfix.md new file mode 100644 index 000000000..557e68c4a --- /dev/null +++ b/changelog.d/2448.bugfix.md @@ -0,0 +1 @@ +URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex. diff --git a/changelog.d/2451.bugfix.1.md b/changelog.d/2451.bugfix.1.md new file mode 100644 index 000000000..c102c6bd5 --- /dev/null +++ b/changelog.d/2451.bugfix.1.md @@ -0,0 +1 @@ +Setting a profile key longer than 255 bytes now returns 400 `M_KEY_TOO_LARGE` as required by the spec, instead of 413 `M_TOO_LARGE`. diff --git a/changelog.d/2451.bugfix.2.md b/changelog.d/2451.bugfix.2.md new file mode 100644 index 000000000..49cf46a52 --- /dev/null +++ b/changelog.d/2451.bugfix.2.md @@ -0,0 +1 @@ +Setting profile data that would make the profile exceed 64 KiB now returns 400 `M_PROFILE_TOO_LARGE` as required by the spec, instead of a 500 error. diff --git a/changelog.d/2451.bugfix.3.md b/changelog.d/2451.bugfix.3.md new file mode 100644 index 000000000..f75d21824 --- /dev/null +++ b/changelog.d/2451.bugfix.3.md @@ -0,0 +1 @@ +Appservices masquerading as a device that does not exist now receive 400 `M_UNKNOWN_DEVICE` as required by the spec, instead of 403 `M_FORBIDDEN`. diff --git a/changelog.d/2451.bugfix.4.md b/changelog.d/2451.bugfix.4.md new file mode 100644 index 000000000..10f6a4da1 --- /dev/null +++ b/changelog.d/2451.bugfix.4.md @@ -0,0 +1 @@ +Setting `m.fully_read` via the account data endpoints now returns 405 `M_BAD_JSON` as required by the spec, instead of 400. diff --git a/changelog.d/2452.bugfix.md b/changelog.d/2452.bugfix.md new file mode 100644 index 000000000..451d8a020 --- /dev/null +++ b/changelog.d/2452.bugfix.md @@ -0,0 +1 @@ +The `m.forget_forced_upon_leave` capability now reflects the `forget_forced_upon_leave` config option instead of always being advertised as enabled. diff --git a/changelog.d/2454.bugfix.md b/changelog.d/2454.bugfix.md new file mode 100644 index 000000000..6dfd7b5df --- /dev/null +++ b/changelog.d/2454.bugfix.md @@ -0,0 +1 @@ +Fixed push notifications for membership events setting `user_is_target` based on the sender rather than the user being notified. diff --git a/changelog.d/2460.bugfix.md b/changelog.d/2460.bugfix.md new file mode 100644 index 000000000..fc8955510 --- /dev/null +++ b/changelog.d/2460.bugfix.md @@ -0,0 +1 @@ +Ensure HTTP clients actually follow the `dns_servers` config option. Contributed by @silversys diff --git a/changelog.d/2462.bugfix.md b/changelog.d/2462.bugfix.md new file mode 100644 index 000000000..8ae8ab125 --- /dev/null +++ b/changelog.d/2462.bugfix.md @@ -0,0 +1 @@ +`/_matrix/client/v3/sync` no longer waits 30 seconds if the `timeout` parameter is omitted or set to zero, correctly reflecting the specification's rule that such requests should return immediately, even if they are empty. diff --git a/changelog.d/2465.bugfix.md b/changelog.d/2465.bugfix.md new file mode 100644 index 000000000..685f054ab --- /dev/null +++ b/changelog.d/2465.bugfix.md @@ -0,0 +1 @@ +Reworked event relations to follow the spec more closely. Pagination of `/relations` now returns the correct pages and `next_batch` tokens, recursive relations are returned in the right order without duplicates, and bundled `m.reference` aggregations now include every reference. Contributed by @Henry-Hiles (QuadRadical). diff --git a/changelog.d/2481.bugfix.md b/changelog.d/2481.bugfix.md new file mode 100644 index 000000000..f0da8f388 --- /dev/null +++ b/changelog.d/2481.bugfix.md @@ -0,0 +1 @@ +Read receipts are now more spec compliant, will work better in threads and are less likely to end up causing loops with other software. Contributed by @Jade diff --git a/changelog.d/2495.bugfix.md b/changelog.d/2495.bugfix.md new file mode 100644 index 000000000..178437bc9 --- /dev/null +++ b/changelog.d/2495.bugfix.md @@ -0,0 +1 @@ +Fix the DNS resolver failing to start without `/etc/resolv.conf` when `dns_servers` is configured. Contributed by @eleboucher. diff --git a/changelog.d/2497.bugfix.md b/changelog.d/2497.bugfix.md new file mode 100644 index 000000000..11412dbfc --- /dev/null +++ b/changelog.d/2497.bugfix.md @@ -0,0 +1 @@ +Fixed OIDC logins failing after the identity provider rotates its signing keys. Contributed by @eleboucher. diff --git a/changelog.d/2517.feature.md b/changelog.d/2517.feature.md new file mode 100644 index 000000000..ab8a89b1c --- /dev/null +++ b/changelog.d/2517.feature.md @@ -0,0 +1 @@ +Changed the policy on unstable features, disabling most by default and making them configurable in a tidy little `experiments` configuration. See also: #1884. diff --git a/changelog.d/2533.bugfix.md b/changelog.d/2533.bugfix.md new file mode 100644 index 000000000..39b0092fb --- /dev/null +++ b/changelog.d/2533.bugfix.md @@ -0,0 +1 @@ +Fixed the experiments implementation in #2517 not properly disabling some functionality when associated experiments weren't enabled. diff --git a/changelog.d/2542.bugfix.md b/changelog.d/2542.bugfix.md new file mode 100644 index 000000000..fa6324d5e --- /dev/null +++ b/changelog.d/2542.bugfix.md @@ -0,0 +1 @@ +The sticky events feature flag is correctly advertised in `/_matrix/client/versions` again after it was accidentally removed in #2517. diff --git a/changelog.d/2556.misc.md b/changelog.d/2556.misc.md new file mode 100644 index 000000000..8840924f8 --- /dev/null +++ b/changelog.d/2556.misc.md @@ -0,0 +1 @@ +The former configuration alias `allow_check_for_updates` is now explicitly deprecated in favor of `allow_announcements_check`. Additionally, `request_ip_source` is now deprecated in favor of `accepted_ip_sources`. diff --git a/changelog.d/2561.bugfix.md b/changelog.d/2561.bugfix.md new file mode 100644 index 000000000..783bb173a --- /dev/null +++ b/changelog.d/2561.bugfix.md @@ -0,0 +1 @@ +A message is now sent to the admin room when a user logs in for the first time through an OIDC provider, if admin room notices are enabled. Contributed by @ginger. diff --git a/changelog.d/2564.feature.md b/changelog.d/2564.feature.md new file mode 100644 index 000000000..ad2f99eb2 --- /dev/null +++ b/changelog.d/2564.feature.md @@ -0,0 +1 @@ +Dropped support for `hardened_malloc` and add support for `mimalloc` instead. Contributed by @nex and @jade. diff --git a/changelog.d/2565.bugfix.md b/changelog.d/2565.bugfix.md new file mode 100644 index 000000000..e47a8dc25 --- /dev/null +++ b/changelog.d/2565.bugfix.md @@ -0,0 +1 @@ +Fix soundness and correctness issues in the jemalloc interface, improving performance. Contributed by @Jade diff --git a/changelog.d/get-missing-events-earliest-limit.bugfix.md b/changelog.d/get-missing-events-earliest-limit.bugfix.md new file mode 100644 index 000000000..2e5d51f8c --- /dev/null +++ b/changelog.d/get-missing-events-earliest-limit.bugfix.md @@ -0,0 +1 @@ +Fixed `/get_missing_events` rejecting requests with more `earliest_events` than the `limit`. Contributed by @eleboucher. diff --git a/changelog.d/sender-supervision.bugfix.md b/changelog.d/sender-supervision.bugfix.md new file mode 100644 index 000000000..bbd9bce83 --- /dev/null +++ b/changelog.d/sender-supervision.bugfix.md @@ -0,0 +1 @@ +Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher. diff --git a/complement/complement.config.toml b/complement/complement.config.toml index dc7e66d6c..2f2172f05 100644 --- a/complement/complement.config.toml +++ b/complement/complement.config.toml @@ -31,7 +31,6 @@ rocksdb_log_level = "info" rocksdb_max_log_files = 1 rocksdb_recovery_mode = 0 rocksdb_paranoid_file_checks = true -allow_legacy_media = true startup_netburst = true startup_netburst_keep = -1 allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure = true diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 9f79f7f76..52217e96e 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -412,7 +412,7 @@ # env: CONTINUWUITY_IP_LOOKUP_STRATEGY #ip_lookup_strategy = 5 -# The preferred source to use for getting the real client IP. +# DEPRECATED: The preferred source to use for getting the real client IP. # # Takes any of the following options: # @@ -431,9 +431,10 @@ # to set this header" check; if the header selected is present, it is # used. # -# Ignored if `accepted_ip_sources` is set. +# Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is +# the preferred alternative. # -# If not set set, `direct` is used. Additionally, `direct` is used +# If not set, `direct` is used. Additionally, `direct` is used # as a fallback if the chosen header is not found. # # env: CONTINUWUITY_REQUEST_IP_SOURCE @@ -685,6 +686,13 @@ # env: CONTINUWUITY_SENDER_SHUTDOWN_TIMEOUT #sender_shutdown_timeout = 5 +# Maximum number of requests per minute that unauthenticated clients +# may make to ratelimited client-server API routes. This ratelimit is +# global across all endpoints for each IP. +# +# env: CONTINUWUITY_UNAUTHENTICATED_REQUEST_RATELIMIT +#unauthenticated_request_ratelimit = 30 + # Enables registration. If set to false, no users can register on this # server. # @@ -805,15 +813,32 @@ # env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE #forget_forced_upon_leave = false -# Set this to true to require authentication on the normally -# unauthenticated profile retrieval endpoints (GET) -# "/_matrix/client/v3/profile/{userId}". +# Set this to true to require authentication when looking up user profiles +# through this server. # -# This can prevent profile scraping. +# By default this is false, allowing tools such as matrix.to to access +# profiles of users on this server and on other servers. +# Setting this to true will block those tools, and may block automated +# crawlers from scraping users' profiles, although it will not block +# other homeservers from accessing users' profiles. # # env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS #require_auth_for_profile_requests = false +# Set this to true to require authentication to create a rendezvous +# session. Rendezvous sessions are used for QR code login. +# +# For QR code login, the device that shows the QR code is the one that +# creates the rendezvous session. Therefore, this must be false to let +# a logged-out device show a QR code. +# +# By default this is false to allow logged-out desktop devices (which may +# not have a camera) to show a QR code. Setting this to true will +# require logged-out devices to scan the QR code instead. +# +# env: CONTINUWUITY_REQUIRE_AUTH_FOR_RENDEZVOUS +#require_auth_for_rendezvous = false + # Set this to true to allow your server's public room directory to be # federated. Set this to false to protect against /publicRooms spiders, # but will forbid external users from viewing your server's public room @@ -1647,13 +1672,6 @@ # env: CONTINUWUITY_ALLOW_INCOMING_TYPING #allow_incoming_typing = true -# Allow the use of unstable persistent "sticky events" ([MSC4354]) -# -# MSC4354: https://c10y.cc/MSC4354 -# -# env: CONTINUWUITY_ALLOW_STICKY_EVENTS -#allow_sticky_events = false - # Maximum time federation user can indicate typing. # # env: CONTINUWUITY_TYPING_FEDERATION_TIMEOUT_S @@ -1704,29 +1722,6 @@ # env: CONTINUWUITY_BROTLI_COMPRESSION #brotli_compression = false -# Enable the legacy unauthenticated Matrix media repository endpoints. -# These endpoints consist of: -# - /_matrix/media/*/config -# - /_matrix/media/*/upload -# - /_matrix/media/*/preview_url -# - /_matrix/media/*/download/* -# - /_matrix/media/*/thumbnail/* -# -# The authenticated equivalent endpoints are always enabled. -# -# Defaults to false, as unauthenticated media has been sunsetted. -# -# env: CONTINUWUITY_ALLOW_LEGACY_MEDIA -#allow_legacy_media = false - -# If set to true, prevents fetching new legacy remote media. -# -# Legacy media may still be accessible if it was already fetched -# previously and allow_legacy_media is true. -# -# env: CONTINUWUITY_FREEZE_LEGACY_MEDIA -#freeze_legacy_media = true - # Check consistency of the media directory at startup: # 1. When `media_compat_file_link` is enabled, this check will upgrade # media when switching back and forth between Conduit and conduwuit. @@ -2677,3 +2672,144 @@ # # env: CONTINUWUITY_OAUTH__OIDC__PROFILE_KEY_IMPORT_MODE #profile_key_import_mode = "on_registration" + +[global.experiments] +# Continuwuity's experimental features are frequently updated. +# If you got this configuration via a package manager, chances are it's outdated. +# Check out the configuration reference online to see a fresh version: +# https://continuwuity.org/reference/config.html#:~:text=global.experiments +# +# Please keep in mind that experiments are used to enable unstable features. +# You probably don't need to enable any of these unless you know what they are, +# and consequently know why you should enable them. + + +# MSC3814: Dehydrated devices with SSSS +# +# Enables server-side support for "dehydrated devices", which are +# server-side devices (created by supporting clients) that can collect +# encryption keys when there are no online devices, which supporting +# clients can then "hydrate" to download any encryption keys that were +# sent while they were offline. +# +# Important: this is NOT required to receive encrypted messages while you +# are offline. Devices can still receive encrypted messages while they are +# offline, but to share those keys with new devices, they have to be +# online. Dehydrated devices work around this by providing a "shared" +# device new sessions can bootstrap from, to receive keys from before they +# logged in that haven't been uploaded to the server-side key backup yet. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/3814 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC3814 +#msc3814 = false + +# MSC4155: Invite filtering +# +# Provides advanced invite filtering rules for users, allowing complex +# configurations that can allow, ignore, and reject invites from users and +# servers broadly. +# +# Requires a supporting client to set up on an account. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4155 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4155 +#msc4155 = false + +# MSC4174: Web push +# +# Adds server-side support for web push, allowing web clients to receive +# push notifications directly without the need for an intermediary push +# gateway like Sygnal. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4174 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4174 +#msc4174 = false + +# MSC4406: `M_SENDER_IGNORED` error code +# +# Introduces a new error code that explicitly informs clients the reason +# they cannot access an event if it is sent by an ignored user. Without +# this proposal, clients will simply get a "not found" or "forbidden" +# error when requesting events sent by users that have been ignored, which +# leads to replies being shown as "this message could not be found". +# The new error code allows clients to distinguish unknown/forbidden +# events from ignored senders, allowing them to display an error message +# like "you have blocked this sender" instead. +# +# Requires a supporting client to be useful. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4406 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4406 +#msc4406 = false + +# MSC4484: Server Administration OAuth Scope +# +# Adds a new OAuth2 scope that explicitly grants a token temporary +# homeserver administrator privileges, granting temporary token access +# to administrator endpoints like locking & suspension. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4484 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4484 +#msc4484 = false + +# MSC4494: Membership-based invite blocking +# +# Adds a new invite blocking action that will reject all invites coming +# from users who do not share a room with the invitee that is not `public` +# (the join rule). +# +# This is not related to MSC4155, this proposal instead builds on the +# "invite blocking" proposal that landed in the specification in v1.17, +# which simply allows enabling or disabling invites altogether. +# +# MSC4494 is a good middle-ground between the allowlisting possible with +# MSC4155, and the general desire to block invites from users you may not +# know. +# +# Requires a supporting client to enable on an account. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4494 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4494 +#msc4494 = false + +# MSC4560: Stripped state requests over federation +# +# Implements a more efficient way for servers to acquire and serve +# "stripped state" to clients, which is typically only used for displaying +# rooms. The display of space hierarchies and room summaries is +# significantly faster when this proposal is enabled and used. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +# +# env: CONTINUWUITY_EXPERIMENTS__MSC4560 +#msc4560 = false + +#[global.experiments.msc2815] +# MSC2815: Proposal to allow room moderators to view redacted event content +# +# Allows the server to retain unredacted copies of events that have been +# redacted for a limited period of time, which allows room moderators and +# server administrators to reveal redacted contents. Useful for moderation +# and investigating reports. +# +# Requires a supporting client to use. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/2815 + + +# Whether to enable MSC2815. +# +# env: CONTINUWUITY_EXPERIMENTS__MSC2815__ENABLED +#enabled = false + +# How long, in seconds, to retain the original content of redacted +# events before it is permanently erased. Defaults to 90 days. +# +# env: CONTINUWUITY_EXPERIMENTS__MSC2815__UNREDACTED_CONTENT_MAX_AGE_SECS +#unredacted_content_max_age_secs = 7776000 diff --git a/docker/Dockerfile b/docker/Dockerfile index 1c32a245c..3af00fb98 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,7 +50,7 @@ EOF # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.25.3 +ENV BINSTALL_VERSION=1.28.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree @@ -192,7 +192,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ jq -r ".target_directory")) mkdir /out/sbin PACKAGE=conduwuit - CARGO_LOG=debug xx-cargo build --locked --profile ${RUST_PROFILE} \ + xx-cargo build --locked --profile ${RUST_PROFILE} \ --no-default-features --features ${CARGO_FEATURES} \ -p $PACKAGE; BINARIES=($(cargo metadata --no-deps --format-version 1 | \ diff --git a/docker/complement.Dockerfile b/docker/complement.Dockerfile index 1cef3527d..82dd1a970 100644 --- a/docker/complement.Dockerfile +++ b/docker/complement.Dockerfile @@ -1,11 +1,29 @@ -FROM ubuntu:latest +ARG CONTINUWUITY_IMAGE=continuwuity:latest-openreg +ARG BINARY_SOURCE=host + +FROM ${CONTINUWUITY_IMAGE} AS container-binary + +FROM scratch AS host-binary +ARG BINARY_PATH=target/debug/conduwuit +COPY ${BINARY_PATH} /sbin/conduwuit + +FROM ubuntu:latest AS base EXPOSE 8008 EXPOSE 8448 RUN apt-get update && apt-get install -y ca-certificates liburing2 && rm -rf /var/lib/apt/lists/* RUN mkdir -p /etc/continuwuity /var/lib/continuwuity /usr/local/bin/ COPY complement/complement-entrypoint.sh /usr/local/bin/complement-entrypoint.sh COPY complement/complement.config.toml /etc/continuwuity/config.toml -COPY target/debug/conduwuit /usr/local/bin/conduwuit -RUN chmod +x /usr/local/bin/conduwuit /usr/local/bin/complement-entrypoint.sh +RUN chmod +x /usr/local/bin/complement-entrypoint.sh #HEALTHCHECK --interval=30s --timeout=5s CMD curl --fail http://localhost:8008/_continuwuity/server_version || exit 1 ENTRYPOINT ["/usr/local/bin/complement-entrypoint.sh"] + +FROM base AS container +COPY --from=container-binary /sbin/conduwuit /usr/local/bin/conduwuit +RUN chmod +x /usr/local/bin/conduwuit + +FROM base AS host +COPY --from=host-binary /sbin/conduwuit /usr/local/bin/conduwuit +RUN chmod +x /usr/local/bin/conduwuit + +FROM ${BINARY_SOURCE} diff --git a/docker/musl.Dockerfile b/docker/musl.Dockerfile index 80dacba77..8e37b6d57 100644 --- a/docker/musl.Dockerfile +++ b/docker/musl.Dockerfile @@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \ # Developer tool versions # renovate: datasource=github-releases depName=cargo-bins/cargo-binstall -ENV BINSTALL_VERSION=1.25.3 +ENV BINSTALL_VERSION=1.28.0 # renovate: datasource=github-releases depName=psastras/sbom-rs ENV CARGO_SBOM_VERSION=0.9.1 # renovate: datasource=crate depName=lddtree diff --git a/docs/authentication/internal.mdx b/docs/authentication/internal.mdx index 05542b573..0aa566843 100644 --- a/docs/authentication/internal.mdx +++ b/docs/authentication/internal.mdx @@ -4,7 +4,7 @@ Continuwuity comes with an internal database for user authentication, which it u ## Registration -Registration is disabled by default. To enable it, set `allow_registration = true` in your config file and use at least one of the registration methods below. +The following registration methods are available for Continuwuity: | Method | Description | Additional configuration needed | | ------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | @@ -19,6 +19,8 @@ Admin-issued tokens are the recommended registration method. These tokens are we Other registration methods are meant for **untrusted, public registration**. Care must be taken when allowing these modes of operation. +If you wish to disable registration entirely, set `allow_registration = false` in your config file. + ## Email configuration Continuwuity can be configured to send emails via an SMTP relay of your choice. These are used for verifying user email addresses and sending password reset links to them. diff --git a/docs/authentication/oidc.mdx b/docs/authentication/oidc.mdx index 815d60af2..eafb82d73 100644 --- a/docs/authentication/oidc.mdx +++ b/docs/authentication/oidc.mdx @@ -1,3 +1,5 @@ +import { Tab, Tabs } from '@rspress/core/theme'; + # Delegated authentication with OIDC Continuwuity supports delegating user authentication to an external identity provider that implements the OpenID Connect (OIDC) specification, such as Authentik, Kanidm, or Keycloak. @@ -12,56 +14,110 @@ An account on the homeserver can only be associated with one OIDC subject claim A simple OIDC configuration is as easy as creating a new OIDC application in your identity provider's settings and supplying Continuwuity with the client ID and client secret. +The instructions below make the following assumptions: + +- Continuwuity's base URL: `https://matrix.example.com`. Note that if you employ [well-known delegation](../guides/delegation), this must match the client well-known domain rather than your server name. +- OIDC provider's base URL: `https://idm.example.com` + ### Configuring the OIDC provider -This guide will use [**Kanidm**][kanidm] as an example, but the described steps are broadly applicable to other identity providers. Contributions for them are welcome. +This guide will cover [**Kanidm**][kanidm] and [**Authelia**][authelia], but the basic concepts apply to most identity providers. Contributions for them are welcome. -First, create a new application for Continuwuity in your identity provider. + + + +Create a new application for continuwuity in kanidm. We will use `c10y` as the client ID. ```sh -# Here, `c10y` is the client ID that Kanidm will use, and `Continuwuity` is the display name. -# Other identity providers may generate a client ID for you. -# Use the domain that clients can reach Continuwuity at, which may not be the same as your server name -# if you have configured well-known delegation. -kanidm system oauth2 create c10y Continuwuity https://matrix.yourdomain.com +kanidm system oauth2 create c10y Continuwuity https://matrix.example.com ``` Configure the redirect URL that Continuwuity uses. ```sh -kanidm system oauth2 add-redirect-url c10y https://matrix.yourdomain.com/_continuwuity/oidc/complete +kanidm system oauth2 add-redirect-url c10y https://matrix.example.com/_continuwuity/oidc/complete ``` -Allow Continuwuity to request the `openid` scope. Other identity providers may not require this step. +Allow Continuwuity to request the `openid` scope. ```sh kanidm system oauth2 update-scope-map c10y idm_all_persons openid ``` -Find the client secret that was generated. Other identity providers may show this information in their web UI. +Find the client secret that was generated. ```sh kanidm system oauth2 show-basic-secret c10y d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr ``` +Now the discovery URL for KanIDM is: `https://idm.example.com/oauth2/openid/c10y` + + + + +To create a new client in Authelia, it is [recommended][authelia-faq-client-secret] to randomly generate both the client id and client secret. The commands below should get you those: + + + +```sh +# Generate random value for Client ID +authelia crypto rand --length 72 --charset rfc3986 +# Generate Client Secret (labeled Random Password) and its Digest +authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 +``` + + +```sh +# Generate random value for Client ID +docker run --rm authelia/authelia:latest authelia crypto rand --length 72 --charset rfc3986 +# Generate Client Secret (labeled Random Password) and its Digest +docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --variant sha512 --random --random.length 72 --random.charset rfc3986 +``` + + + +Authelia only needs to know the digest of the secret, whereas Continuwuity requires the secret itself. + +Go to your Authelia configuration file, find the `identity_provers` block, and add a block for Continuwuity to the `clients` list: + +```yaml +identity_providers: + oidc: + jwks: + # This part has the JWKs and is what you configured previously + # ... + clients: + # Add this block below to the clients list + - client_name: continuwuity + client_id: "client-id-goes-here" + # Use the client secret's DIGEST, not the client secret itself + client_secret: "client-secret-DIGEST-goes-here" + redirect_uris: ["https://matrix.example.com/_continuwuity/oidc/complete"] + scopes: [openid] +``` +Then restart Authelia to load the new configuration. + +The discovery URL is simply the root domain of your Authelia, where it can be reached by clients, i.e. `https://idm.example.com`. + + + + [kanidm]: https://kanidm.com +[authelia]: https://www.authelia.com +[authelia-faq-client-secret]: https://www.authelia.com/integration/openid-connect/frequently-asked-questions/#how-do-i-generate-a-client-identifier-or-client-secret ### Configuring Continuwuity -Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. Kanidm has a different discovery URL for each client, but other identity providers may have a single discovery URL at the root of their domain. +Configure Continuwuity with the client ID, client secret, and discovery URL provided from the steps above. ```toml [global.oauth.oidc] # `/.well-known/openid-configuration` will be appended automatically -discovery_url = "https://idm.example.com/oauth2/openid/c10y" +discovery_url = "https://your-discovery-url" -# This may be randomly generated by your identity provider. Kanidm requires -# you to set it manually when you create the application. -client_id = "c10y" - -# From the previous step -client_secret = "d1qgx352kkuvs1j70b6w293d65x68jve1f7b27fyk90gjhpr" +client_id = "your-client-id" +client_secret = "your-client-secret" ``` ### Testing that it works diff --git a/docs/calls.mdx b/docs/calls.mdx index 0f1fea978..28b83f05d 100644 --- a/docs/calls.mdx +++ b/docs/calls.mdx @@ -2,12 +2,16 @@ Matrix supports two types of calls: -- Element Call powered by [MatrixRTC](https://half-shot.github.io/msc-crafter/#msc/4143) and [LiveKit](https://github.com/livekit/livekit) -- Legacy calls, supported by a STUN/TURN server. +- [MatrixRTC][MSC4143] calls, powered by [LiveKit][livekit-server-github] and frontends such as [Element Call][element-call]. +- Legacy 1-to-1 calls, supported by a STUN/TURN server. -Both types of calls are supported by different sets of clients, but most clients are moving towards MatrixRTC / Element Call. +[MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 +[element-call-github]: https://github.com/element-hq/element-call/ +[livekit-server-github]: https://github.com/livekit/livekit + +Both types of calls are supported by different sets of clients, but most clients are moving towards MatrixRTC. For either one to work correctly, you have to do some additional setup: -- For legacy calls to work, you need to set up a TURN/STUN server. [Read the TURN guide for tips on how to set up coturn](./calls/turn.mdx) -- For MatrixRTC / Element Call to work, you have to set up the LiveKit backend. LiveKit also uses TURN/STUN to increase reliability - you can set up its built-in TURN server, or integrate with an existing one. [Read the LiveKit guide](./calls/livekit.mdx) +- For legacy calls to work, you need to set up a TURN/STUN server. [Read the TURN guide for instructions on how to set up coturn](./calls/turn.mdx) +- For MatrixRTC calls to work, you have to set up the LiveKit backend, and optionally configure a TURN server for increased reliability. [Read the LiveKit guide](./calls/livekit.mdx) diff --git a/docs/calls/livekit.mdx b/docs/calls/livekit.mdx index 7a1a0d57d..9931b2c9e 100644 --- a/docs/calls/livekit.mdx +++ b/docs/calls/livekit.mdx @@ -1,13 +1,15 @@ -import { Tab, Tabs} from '@rspress/core/theme'; +import { Tab, Tabs } from '@rspress/core/theme'; -# MatrixRTC/Element Call Setup +# MatrixRTC/LiveKit Setup -This guide assumes that you are using docker compose for deployment. +This guide assumes that you are using `docker compose` for deployment. :::tip -You can find help setting up MatrixRTC in our dedicated room - [#matrixrtc:continuwuity.org](https://matrix.to/#/%23matrixrtc%3Acontinuwuity.org) +You can find help setting up MatrixRTC in our support room - [`#continuwuity:continuwuity.org`][support-room] ::: +[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org + ## Instructions ### 1. Set up your domain @@ -58,7 +60,9 @@ services: - ./livekit.yaml:/etc/livekit.yaml:ro network_mode: "host" # /!\ LiveKit binds to all addresses by default. # Make sure port 7880 is blocked by your firewall to prevent access bypassing your reverse proxy - # Alternatively, uncomment the lines below and comment `network_mode: "host"` above to specify port mappings. + + # Alternatively, uncomment the lines below and comment out `network_mode: "host"` + # above to use bridge networking and manually specify port mappings. # ports: # - "127.0.0.1:7880:7880/tcp" # - "7881:7881/tcp" @@ -218,7 +222,9 @@ Start up the services using your usual method - for example `docker compose up - ## Testing -To test that LiveKit is successfully integrated with Continuwuity, you will need to replicate its [Token Exchange Flow](https://github.com/element-hq/lk-jwt-service#%EF%B8%8F-how-it-works--token-exchange-flow). Follow the steps below while checking Docker logs (`docker compose logs --follow`), in order to help [troubleshooting](#troubleshooting) any issues. +To test that LiveKit is successfully integrated with Continuwuity, you will need to replicate its [Token Exchange Flow][token-exchange-flow]. Follow the steps below while checking Docker logs (`docker compose logs --follow`), in order to help [troubleshooting](#troubleshooting) any issues. + +[token-exchange-flow]: https://github.com/element-hq/lk-jwt-service/tree/v0.6.0#%EF%B8%8F-how-it-works--token-exchange-flow First, you will need an access token for your current login session. These can be found in your client's settings or obtained via [this website][starstruck-mxtoken2]. @@ -279,7 +285,7 @@ You can then send this payload to the lk-jwt-service: curl -X POST -d @payload.json https://livekit.example.com/get_token ``` -The lk-jwt-service will, after checking against Continuwuity, answer with a `jwt` token to create a LiveKit media room: +The lk-jwt-service will, after checking against Continuwuity, answer with a `jwt` token to [create a LiveKit media room](#livekit-cli): ```json {"url":"wss://livekit.example.com","jwt":"a_really_really_long_string"} @@ -293,47 +299,35 @@ Use this token to test at the [LiveKit Connection Tester][livekit-connection-tes To debug any issues, you can place a call or redo the Testing instructions, and check the container logs for any specific errors. Use `docker compose logs --follow` to follow these logs in real-time. +Before debugging, ensure the following prerequisites: + +- The user has permissions to send call events into the room. See the Appendix section on [call modes](#call-modes) for more details. +- WebRTC is enabled, if using a browser client. + ### Common errors in Element Call UI -- `MISSING_MATRIX_RTC_FOCUS`/`MISSING_MATRIX_RTC_TRANSPORT`: LiveKit is missing from Continuwuity's config file -- "Waiting for media" popup always showing for yourself: a LiveKit URL has been configured in Continuwuity, but your client cannot connect to it for some reason -- `OPEN_ID_ERROR`: Your client can reach out to `lk-jwt-service`, but has problems authenticating with it. In this case, check `lk-jwt-service` logs for more details +- `MISSING_MATRIX_RTC_FOCUS`/`MISSING_MATRIX_RTC_TRANSPORT`: the client cannot find a suitable SFU. This is likely due to LiveKit being missing from Continuwuity's config file, and therefore not being exposed properly. -For browser-based clients, you can also inspect connections using DevTools' Networking tab, to see which requests are erroring out. +- `OPEN_ID_ERROR`: Your client can reach out to `lk-jwt-service`, but `lk-jwt-service` has problems authenticating you against Continuwuity. In this case, check `lk-jwt-service` logs for more details. The section below on [Docker loopback networking issues](#docker-loopback-networking-issues) may be of help. + +- Calls fail to start with `ServerUnreachable` error: a LiveKit URL has been properly configured and exposed in Continuwuity, but the client cannot connect to it for some reason. + +For browser-based clients, you can inspect connections using DevTools' Networking tab, to see which requests are erroring out. You may also want to toggle on Element Call's Developer tab via _Settings > Preferences > Developer mode_ \- various call details and advanced settings can be further tweaked there. ### Docker loopback networking issues -Some distros do not allow Docker containers in bridge networks to connect to their host's public IP by default. This makes `lk-jwt-service` fail connecting to `livekit` or `continuwuity` on the same host, causing refused and timed out connections to appear in the log entries of the JWT service, even when `LIVEKIT_URL` has been configured correctly. - -You can also test that this is the case by cURLing from a sidecar container: +Some distros do not allow Docker containers to connect to the host's public IP, and this breaks connections from `lk-jwt-service` towards `livekit` and `continuwuity` if they're on the same host. This can be tested by the following command: ```bash docker run --rm --net container:lk-jwt-service docker.io/curlimages/curl https://livekit.example.com # --- some errors --- ``` -To resolve this, configure an `extra_hosts` file mapping LiveKit's and Continuwuity's domain names to Docker's custom host loopback address, represented here by `host-gateway`: +To resolve this, follow the steps in [Docker loopback networking issues](../troubleshooting.mdx#docker-loopback-networking-issues) of the Troubleshooting page. -```diff -# in docker-compose.yaml -services: - lk-jwt-service: - ... -+ extra_hosts: -+ - "livekit.example.com:host-gateway" -+ - "matrix.example.com:host-gateway" -``` +### Incorrect IP addresses for LiveKit -After implementing the changes and restarting your compose, `lk-jwt-service` should now connect to your other services. The sidecar container test above should now return an `OK` from LiveKit. - -For more information about the `host-gateway` parameter, kindly refer to the `--add-host` documentation for [Docker][docker-add-host] and [Podman][podman-add-host]. Should you have further difficulties, feel free to enquire in the support rooms. - -[docker-add-host]: https://docs.docker.com/reference/cli/docker/container/run/#add-host -[podman-add-host]: https://docs.podman.io/en/latest/markdown/podman-run.1.html#add-host-hostname-hostname-ip - -### Incorrect IP address for LiveKit - -By default, LiveKit automatically finds its public IP address(es), which can be seen in the "Establishing WebRTC connection" section of the connection test page. If these IPs are incorrect, you may want to hardcode your own IP by doing the following: +By default, LiveKit automatically finds its public IP address(es), which are reflected in the "Establishing WebRTC connection" section of the connection test page. If these IPs are incorrect, you may want to hardcode your own IP by doing the following: ```diff ### in your livekit.yaml ### @@ -344,20 +338,21 @@ rtc: + node_ip: "1.2.3.4" ``` -### Workaround for non-federating servers +Run the LiveKit tests again, and the new updated `node_ip` should be included as one of the candidates. -When deploying on servers with federation disabled (`allow_federation = false`), LiveKit will fail as it can't fetch the required [OpenID endpoint](https://spec.matrix.org/v1.17/server-server-api/#get_matrixfederationv1openiduserinfo) via federation paths. +You may further restrict the advertised address to only the `node_ip` with the following configurations: -As a workaround, you can enable federation, but forbid all remote servers via the following config parameters: - -```toml -### in your continuwuity.toml file ### -allow_federation = true -forbidden_remote_server_names = [".*"] +```diff +### in your livekit.yaml ### +rtc: + # ... other configs here ... ++ enable_loopback_candidate: false ++ interfaces: ++ includes: [] ++ ips: ++ includes: [ "1.2.3.4/32" ] ``` -Subscribe to issue [!1440](https://forgejo.ellis.link/continuwuation/continuwuity/issues/1440) for future updates on this matter. - ## Related Documentation Guides: @@ -378,9 +373,15 @@ Specifications: - [MSC4143: MatrixRTC \- Real-time communication over Matrix][MSC4143] - [MSC4195: MatrixRTC Transport using LiveKit Backend][MSC4195] +- [MSC3401: Native Group VoIP Signalling][MSC3401] - state events for legacy calls +- [MSC4075: MatrixRTC invites and notifications][MSC4075] - for ringing users +- [MSC4354: Sticky Events][MSC4354] - for MatrixRTC 2.0 calls [MSC4143]: https://github.com/matrix-org/matrix-spec-proposals/pull/4143 [MSC4195]: https://github.com/matrix-org/matrix-spec-proposals/pull/4195 +[MSC3401]: https://github.com/matrix-org/matrix-spec-proposals/pull/3401 +[MSC4075]: https://github.com/matrix-org/matrix-spec-proposals/pull/4075 +[MSC4354]: https://github.com/matrix-org/matrix-spec-proposals/pull/4354 Source code: @@ -400,6 +401,47 @@ Other: ## Appendix +### MatrixRTC calling modes and enabling sticky events {#call-modes} + +MatrixRTC currently supports 3 calling modes: + +- **Legacy mode** (deprecated): calls are established by sending state events to a room. The call initiator's SFU hosts the entire call for all remote and local participants. +- **Compatibility mode*: same as Legacy mode, but utilizes multiple SFUs between federating servers. Clients publish media streams to their own SFUs, and fetch remote streams from remote SFUs. This is the most commonly used mode nowadays. +- **MatrixRTC 2.0 mode**: also utilizes multiple SFUs, but establishes calls with [sticky events] instead of state events. + +To support Legacy and Compatibility mode, ensure that the user is allowed to send the relevant state events. Usually, this means promoting them to a power level of 50 or above. Alternatively, set the power level required to send `org.matrix.msc3401.call.member` events to 0. + +To support MatrixRTC 2.0 mode, sticky events has to be enabled on the Matrix server. In Continuwuity, this is as easy as setting `enable_sticky_events = true` in the config file. + +### Creating LiveKit tokens via `livekit-cli` {#livekit-cli} + +To create room tokens directly without going through `lk-jwt-service`, use the [Livekit CLI tool][livekit-cli]. + + + + +First, download the [release tarball][livekit-cli-releases] and extract it. Then: + +```sh +./lk --url https://livekit.example.com \ + --api-key APIUxUnMnSkuFWV \ + --api-secret t93ZVjPeoEdyx7Wbet3kG4L3NGZIZVEFvqe0UuiVc22A \ + token create --create --join +``` + + +```sh +docker run --rm docker.io/livekit/livekit-cli --url https://livekit.example.com \ + --api-key APIUxUnMnSkuFWV \ + --api-secret t93ZVjPeoEdyx7Wbet3kG4L3NGZIZVEFvqe0UuiVc22A \ + token create --create --join +``` + + + +[livekit-cli]: https://github.com/livekit/livekit-cli +[livekit-cli-releases]: https://github.com/livekit/livekit-cli + ### Additional TURN-over-TLS on 443 configuration Most of the time, LiveKit [**does not need TURN**][sspaeth-matrix-voip-turn] to function. However, there are situations where clients may be unable to use nonstandard ports or UDP connections, such as in highly restrictive networks. In such cases, a TURN-over-TLS server on port 443 could relay traffic for the clients. @@ -506,6 +548,8 @@ Then configure LiveKit, making sure to replace `COTURN_SECRET` with the one you ### in your livekit.yaml ### rtc: # ... other configs here ... + stun_servers: + - coturn.example.com turn_servers: - host: coturn.example.com port: 443 diff --git a/docs/calls/turn.mdx b/docs/calls/turn.mdx index 82b71149c..a3be0cd97 100644 --- a/docs/calls/turn.mdx +++ b/docs/calls/turn.mdx @@ -1,16 +1,17 @@ # Setting up TURN/STUN -[TURN][turn] and [STUN][stun] are used as components in many calling systems. Matrix uses them directly for legacy calls and indirectly for MatrixRTC via Livekit. +[TURN][turn] and [STUN][stun] are used as components in many calling systems. Matrix uses them directly for legacy 1-to-1 calls and indirectly to assist MatrixRTC calls via Livekit. -Continuwuity recommends using [coturn][coturn] as your TURN/STUN server, which is available as a Docker image or a distro package. This guide assumes that you are using docker compose for deployment. +Continuwuity recommends using [coturn][coturn] as your TURN/STUN server, which is available as a Docker image or a distro package. This guide assumes that you are using `docker compose` for deployment. :::tip -You can find help setting up TURN/STUN in our MatrixRTC room - [#matrixrtc:continuwuity.org](https://matrix.to/#/%23matrixrtc%3Acontinuwuity.org) +You can find help setting up TURN/STUN in our support room - [`#continuwuity:continuwuity.org`][support-room] ::: [turn]: https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT [stun]: https://en.wikipedia.org/wiki/STUN [coturn]: https://github.com/coturn/coturn +[support-room]: https://matrix.to/#/%23continuwuity:continuwuity.org ## Installing coturn @@ -348,7 +349,7 @@ After configuration and spin-up, the destination `turns:turn.example.com:443?tra Using static credentials :::caution -Static credentials are less secure than shared secrets because they don't expire and must be configured in coturn separately. It is strongly advised you use [shared secret authentication](#2-configuration). +Static credentials are less secure than shared secrets because they don't expire and must be configured in coturn separately. It is strongly advised you use [shared secret authentication](#2-configuring-coturn). ::: If you prefer static username/password credentials instead of shared secrets: diff --git a/docs/deploying.mdx b/docs/deploying.mdx index 3a33819fe..267050c04 100644 --- a/docs/deploying.mdx +++ b/docs/deploying.mdx @@ -101,7 +101,7 @@ After Continuwuity is up and running, consider the following: - See the [**Authentication chapter**](./authentication.mdx) for various ways to access to your homeserver, such as logging in with an external OIDC provider. -- Consult the [**Maintenance**](./maintenance.mdx) page for guidance on maintaining your homeserver. +- Consult the [**Maintenance**](./maintenance.mdx) page for guidance on backups, moderation, and other topics for homeserver management. - If you want to set up an appservice, take a look at the [**Appservice Guide**](./appservices.mdx). diff --git a/docs/deploying/arch-linux.mdx b/docs/deploying/arch-linux.mdx index 928d1c8e5..90adad030 100644 --- a/docs/deploying/arch-linux.mdx +++ b/docs/deploying/arch-linux.mdx @@ -2,10 +2,16 @@ Continuwuity is available in the [`archlinuxcn`][archlinuxcn] repository and AUR with the same package name, [`continuwuity`][aur-continuwuity]. -The development version is available on the AUR as [`continuwuity-git`][aur-continuwuity-git]. +For instructions on adding the archlinuxcn repo to your machine, see the [archlinuxcn README][archlinuxcn-readme] page. For AUR instructions, consult its [entry][aur-archwiki] on the Arch Wiki. + +The development version, which tracks latest commits to the main branch, is also available on the AUR as [`continuwuity-git`][aur-continuwuity-git]. [archlinuxcn]: https://www.archlinuxcn.org/ +[archlinuxcn-readme]: https://github.com/archlinuxcn/repo#usage +[aur-archwiki]: https://wiki.archlinux.org/title/Arch_User_Repository [aur-continuwuity]: https://aur.archlinux.org/packages/continuwuity [aur-continuwuity-git]: https://aur.archlinux.org/packages/continuwuity-git -Simply install the `continuwuity` package. Configure the service in `/etc/conduwuit/conduwuit.toml`, then enable and start the `continuwuity.service`. +Once you're done configuring your repos, simply install the `continuwuity` package with `pacman -S continuwuity`. Consult the [generic deployment instructions](./generic.mdx) for detailed steps, which involves editing `/etc/conduwuit/conduwuit.toml` and setting up a reverse proxy. Finally, enable and start the `continuwuity.service`. + +After successfully setting up Continuwuity, navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. diff --git a/docs/deploying/docker.mdx b/docs/deploying/docker.mdx index d7133ee68..c7b105e2e 100644 --- a/docs/deploying/docker.mdx +++ b/docs/deploying/docker.mdx @@ -53,7 +53,7 @@ For more setups with `.well-known` delegation and split-domain deployments, cons Docker Compose is the recommended deployment method for Continuwuity containers. The following environment variables will be set: - `CONTINUWUITY_SERVER_NAME` - Your Matrix server's domain name. **This CANNOT be changed later without a data wipe.** -- `CONTINUWUITY_DATABASE_PATH` - Where to store your database. This must match the docker volume mount. +- `CONTINUWUITY_DATABASE_PATH` - Where to store your database. This must match the docker bind mount. - `CONTINUWUITY_ADDRESS` - Bind address (for Docker, use `0.0.0.0` to listen on all interfaces). Alternatively, you can specify a path to mount the configuration file using the `CONTINUWUITY_CONFIG` environment variable. @@ -69,7 +69,7 @@ Docker's default DNS resolver is known to [**cause timeout issues**](../troubles ```yaml title='docker-compose.yml' services: - homeserver: + continuwuity: # ... volumes: - ./continuwuity-resolv.conf:/etc/resolv.conf @@ -89,15 +89,17 @@ Consult the [**DNS tuning guide (recommended)**](../guides/dns.mdx) for full sol docker-compose.with-caddy.yml ([view raw](/deploying/docker-compose.with-caddy.yml)) -Create a Caddyfile with the following content: +Create a directory called `caddy-data`, which will store TLS certs obtained by Caddy. + +Then, create a Caddyfile with the following content: ``` https://example.com:443, https://example.com:8448 { - reverse_proxy http://homeserver:8008 + reverse_proxy http://continuwuity:8008 } ``` -Then, for the docker-compose: +Then, for the docker compose file: ```yaml file="../public/deploying/docker-compose.with-caddy.yml" @@ -110,6 +112,10 @@ Then, for the docker-compose:
docker-compose.with-caddy-labels.yml ([view raw](/deploying/docker-compose.with-caddy-labels.yml)) +Create a directory called `caddy-data`, which will store TLS certs obtained by Caddy. + +Then, for the docker compose file: + ```yaml file="../public/deploying/docker-compose.with-caddy-labels.yml" ``` @@ -132,6 +138,10 @@ Then, for the docker-compose:
docker-compose.with-traefik.yml ([view raw](/deploying/docker-compose.with-traefik.yml)) +Create a directory called `traefik-acme-data`, which will store TLS certs obtained by Caddy. + +Then, for the docker compose file: + ```yaml file="../public/deploying/docker-compose.with-traefik.yml" ``` @@ -164,10 +174,15 @@ See the [Other reverse proxies](generic.mdx#setting-up-the-reverse-proxy) sectio ### Starting Your Server -1. Choose your compose file from the above, and rename it to `docker-compose.yml`. Replace `example.com` with your homeserver's domain name, and edit other values as you see fit. -2. If using the override file, rename it to `docker-compose.override.yml` and - edit your values. -3. Start the server: +1. Create a directory named `continuwuity-data`. This will be where your server's database lives. + +2. Choose your compose file from the above, and rename it to `docker-compose.yml`. Replace `example.com` with your homeserver's domain name, and edit other values as you see fit. + + - Follow all extra instructions as needed. + + - If using the override file, rename it to `docker-compose.override.yml` and edit your values. + +3. Start the server with the following command: ```bash docker compose up -d @@ -189,9 +204,7 @@ See the [Other reverse proxies](generic.mdx#setting-up-the-reverse-proxy) sectio Pick your own username and password! ``` -5. Log in to your server with any Matrix client, and register for an account with the registration token from step 4. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin). - -See the [generic deployment guide](generic.mdx) for more deployment options. +5. Log in to your server with any Matrix client, and register for an account with the registration token from the previous step. You'll automatically be invited to the admin room where you can [manage your server](../reference/admin). ## Testing @@ -199,7 +212,9 @@ Test that your setup works by following these [instructions](./generic.mdx#how-d Check your container logs using `docker-compose logs --follow` to debug any issues. See the [Troubleshooting](../troubleshooting.mdx) page for common errors and how to fix them. -## Updating +## Maintenance + +### Updating To update to a new version of Continuwuity, use the following commands: @@ -212,6 +227,10 @@ docker compose pull docker compose up -d ``` +### Backups + +The database in `./continuwuity-data` is present on the host system as a regular directory, and therefore can be backed up using normal mechanisms. See the [Backup](../maintenance.mdx#backups) section of the Maintenance page for more details. + ## What's next? Navigate to [Post-installation](../deploying.mdx#post-installation) for next steps. @@ -270,12 +289,6 @@ Get a working Continuwuity server with an admin user in four steps: Once configured, log in to your server with any Matrix client, and register for an account with the registration token from step 3. If you did not configure step 4., log in via the `http://:8008` address. You will be automatically invited to the admin room where you can [manage your server](../reference/admin). -### (Optional) Building Custom Images - -For information on building your own Continuwuity Docker images, see the -[Building Docker Images](../development/index.mdx#building-docker-images) -section in the development documentation. - ### Accessing the Server's Console Before you can access the server's console and [send admin commands](../reference/admin/index.md) from the CLI, you will need to make the container interactive and allocate a pseudo-tty. Make sure you set `admin_console_automatic` to `true` in [the config](../reference/config.mdx) as well for Continuwuity to activate the CLI on startup. @@ -284,7 +297,7 @@ For Docker Compose deployments this means adding `stdin_open: true` and `tty: tr ```yaml services: - homeserver: + continuwuity: stdin_open: true tty: true # ... @@ -297,3 +310,31 @@ From there you can access the server's console by running `docker attach `, and the omission of the +configuration OR setting it to `false` disables the experiment. `ToggledExperiment` impls should +copy similar behaviour. + +Then, add a public field to the `Experiments` struct that is named the MSC's ID in lowercase. +Add a docstring to it, starting with the proposal title (including ID), then a brief paragraph or +so explaining what the proposal does in simple terms, and then finally end the docstring with a link +to the proposal. + +### Advertising support for unstable features + +If the proposal requires advertising an unstable feature flag, that flag must be added to +`unstable_features` in `src/core/matrix/versions.rs`. For example: + +```diff +pub fn unstable_features(experiments: &Experiments) -> BTreeMap { + BTreeMap::from_iter([ + // Always enabled feature (https://github.com/matrix-org/matrix-spec-proposals/pull/0000) + // Expected for spec v1.20 + ("org.matrix.msc0000".to_owned(), true), ++ // MSC9999: My Cool Feature (https://github.com/matrix-org/matrix-spec-proposals/pull/9999) ++ ("example.matrix.msc9999".to_owned(), experiments.msc9999.is_enabled()) + ]) +} +``` + +This will allow the `/_matrix/client/versions` endpoint to dynamically advertise whether the unstable +feature is enabled on the current server. + +## Removing unstable features + +If a proposal is abandoned, becomes obsolete, or is accepted into the specification, the unstable +configuration should be removed (and possibly migrated) as soon as possible. + +After removing a field from `experiments`, the key should be added to the `DEPRECATED_KEYS` slice in +`src/core/config/mod.rs` (really far down). This will ensure that a warning is printed on startup +when a configuration is using a now-removed config key. For example: + +```diff +pub struct Experiments { +- pub msc9999: SimpleExperiment, +} +``` +```diff +const DEPRECATED_KEYS: &[&str] = [ + "foo", ++ "experiments.msc9999", +]; +``` + +## Always-on experiments + +Some experiments can be forcefully enabled (i.e. always-on), or enabled by default. This should only +be the case in exceptional circumstances, and must be adequately well documented. Some examples of +situations that may warrant an experiment being always-enabled: + +* A proposal was implemented AFTER it was merged, but BEFORE it had a merged spec PR. +These proposals are typically as stable as they'll get, as major changes post-factum of an MSC +merge requires another MSC, so only minor changes can be made in the spec PR phase. +* The daily experience of users would be at a great detriment without the experiment being enabled. +* A proposal is so simple that making it opt-in would be pointless. This is *incredibly* rare. + +The latter two require explicit maintainer approval, so discuss those with the maintainer team +first. You can exercise your own judgement for the first. + +Always-on or enabled-by-default experiments must explain in detail why they're exempt from the +standard experiments policy via comments in surrounding areas, like +`src/core/config/experiments.rs` and `src/core/matrix/versions.rs`. Ideally, these features are not +unstable for too long, so explaining a timescale for how long before the feature is stabilised is +also helpful. diff --git a/docs/guides/delegation.mdx b/docs/guides/delegation.mdx index 7ce397e88..d3a379f03 100644 --- a/docs/guides/delegation.mdx +++ b/docs/guides/delegation.mdx @@ -226,10 +226,10 @@ The following Compose files are taken from [Docker deployment instructions](../d ```txt title="Caddyfile" https://matrix.example.com:443 { - reverse_proxy http://homeserver:8008 + reverse_proxy http://continuwuity:8008 } https://example.com:443 { - reverse_proxy /.well-known/matrix* http://homeserver:8008 + reverse_proxy /.well-known/matrix* http://continuwuity:8008 } ``` diff --git a/docs/guides/dns.mdx b/docs/guides/dns.mdx index cfe8995fc..6e880c114 100644 --- a/docs/guides/dns.mdx +++ b/docs/guides/dns.mdx @@ -37,7 +37,7 @@ networks: - subnet: "10.10.10.0/24" services: - homeserver: + continuwuity: # ... volume: - ./continuwuity-resolv.conf:/etc/resolv.conf:ro diff --git a/docs/guides/metrics.mdx b/docs/guides/metrics.mdx index cb5df8c70..83ea51bc7 100644 --- a/docs/guides/metrics.mdx +++ b/docs/guides/metrics.mdx @@ -71,6 +71,9 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry | `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions | | `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending | | `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers | +| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) | +| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting | +| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` | | `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users | | `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation | | `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media | @@ -82,6 +85,7 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry | `continuwuity_database_block_cache_bytes` | gauge | `column` | RocksDB block cache usage | | `continuwuity_cache_entries` | gauge | `name` | Entries in the auth chain and state info caches | | `continuwuity_jemalloc_memory_bytes` | gauge | `kind` | jemalloc statistics, only with the `jemalloc_stats` feature | +| `continuwuity_mimalloc_memory_bytes` | gauge | `kind` | mimalloc statistics, only with the `mimalloc` feature | | `process_uptime_seconds` | gauge | | Time since the server started | | `process_cpu_time_seconds_total` | counter | `cpu_mode` | CPU time used by the process | | `process_memory_usage_bytes` | gauge | | Resident memory (Linux) | diff --git a/docs/guides/performance.mdx b/docs/guides/performance.mdx index 08ecf7ac0..ff69329fb 100644 --- a/docs/guides/performance.mdx +++ b/docs/guides/performance.mdx @@ -82,6 +82,21 @@ Consult these documents for more information on compression tuning and levels: ## Other tweaks +### Tuning your trusted servers + +:::important Important: Vet your trusted servers! +Trusted servers are your first point of contact when obtaining public keys from the wider federated network. They could theoretically impersonate other servers and cause significant harm to your deployment. Please thoroughly verify your trusted servers' credibility before adding them to your configuration. + +If you need suggestions for trusted servers, ask in the Continuwuity support room. +::: + +For performance and reliability, it is recommended to set up 3 to 5 trusted servers for your deployment. Currently, these must all be Synapse servers. + +```toml +# Example config, using maintainers' recommended homeservers +trusted_servers = ["codestorm.net","starstruck.systems","unredacted.org","matrix.org"] +``` + ### Using UNIX sockets If your homeserver and reverse proxy live on the same machine, you may wish to expose Continuwuity on a UNIX socket instead of a port. This removes TCP overhead between the two programs. @@ -111,25 +126,6 @@ https://matrix.example.com {
-### Tuning your trusted servers - -:::info Vet your trusted servers! -Trusted servers are your first point of contact when obtaining public keys from other servers, and they could theoretically impersonate other servers and cause significant harm to your deployment. Please thoroughly verify your trusted servers' credibility before adding them to your configuration. - -If you need suggestions for trusted servers, ask in the Continuwuity main room. -::: - -Trusted servers are queried sequentially in the order they are listed. If you have multiple trusted servers configured, put the faster ones first: - -```toml -# Example config, using maintainers' recommended homeservers -trusted_servers = ["codestorm.net","starstruck.systems","unredacted.org","matrix.org"] -``` - -Avoid prioritising `matrix.org` as your primary trusted server, as it tends to be quite slow. - -Some users have also reported that increasing `trusted_server_batch_size` has helped with faster joins for huge rooms. Start with doubling the default to `2048` until you find a suitable value. - ### Enable HTTP/3 on your reverse proxy Consider enabling the newer **HTTP/3** protocol for inbound connections to Continuwuity. In Caddy HTTP/3 is allowed by default, but you must expose port :443/**udp** on your firewall. diff --git a/docs/guides/push.mdx b/docs/guides/push.mdx index 00a6c8e88..041296218 100644 --- a/docs/guides/push.mdx +++ b/docs/guides/push.mdx @@ -78,9 +78,9 @@ To debug and test your UnifiedPush installation, use the [UP-Example] app for An ### UnifiedPush and push gateways -The push gateway URL is usually pre-configured by the client app. However, some clients (such as Element X) implement UnifiedPush's [Gateway Discovery] mechanism, and attempt to detect a push gateway _on the same domain as the push provider_, before falling back to a hardcoded one. +Normally, the push gateway URL is pre-configured by the client app. However, some clients (such as Element X) implement UnifiedPush's [Gateway Discovery] mechanism, and attempt to detect a push gateway _on the same domain as the push provider_ to use before falling back to a hardcoded one. Users of these clients can therefore self-host their own push gateway. -Per the [spec][spec-push-gateway-api], these push gateways must be available on the `/_matrix/push/v1/notify` path of said domain. To test that a push gateway is accessible to the homeserver, make a request for it from the homeserver's IP: +Per the [spec][spec-push-gateway-api], these push gateways must be available on the `/_matrix/push/v1/notify` path of said domain. To test that a push gateway is usable, make a request to it from both the homeserver and the client. The returned response should look like the following: ```txt curl https://push.example.com/_matrix/push/v1/notify @@ -122,7 +122,7 @@ Community tutorials for selfhosting some of these stacks are listed below. Unles - Push gateway: [common-proxies] - Push server: [ejabberd's mod_unified_push] - Push app: [Conversations] (and forks) -- [Element X push notifications via Conversations][alfredolin-xmpp], by Alfredo Lin. +- [Element X push notifications via Conversations][alfredolin-xmpp], by Alfredolin. - Push gateway: [common-proxies] - Push server: [Prosody's mod_unified_push] - Push app: [Conversations] @@ -156,6 +156,8 @@ WARN conduwuit_service::pusher: Pusher URL is a forbidden remote address url=htt To fix this, remove your push gateway or push server's address from `ip_range_denylist`, and restart Continuwuity to apply the changes. +Docker deployments with the push server/gateway on the same host as Continuwuity may run into some further network issues. In this case, consult the [Docker loopback networking issues] section and its workarounds. + ### Push notifications not audible/not displaying This is likely an issue with your account's _push rules_, which determines which events are shown to to the user as notifications. Check these push rules in the client's notifications settings and tweak accordingly. Continuwuity also provides an [`!admin users reset-push-rules`](../reference/admin/users#admin-users-reset-push-rules) command, which restores the rules to the default of notifying for every message. @@ -175,7 +177,7 @@ If you find spurious log entries like this in your Continuwuity deployment: WARN push{user_id="@user:example.com" pushkey="very-long-string-of-letters" events=1}:send_push_notice:send_notice:send_request: conduwuit_service::pusher: Could not send request to pusher https//push.example.com: error sending request for url (https://push.example.com/_matrix/push/v1/notify) ``` -Then, your server is most likely sending push requests to too many invalid targets. This could be due to one of the following reasons: +Then, your server is sending push requests to too many invalid targets. This could be due to one of the following reasons: #### Connection issues between the server and the push gateway diff --git a/docs/maintenance.mdx b/docs/maintenance.mdx index 362e92d2b..329629eb9 100644 --- a/docs/maintenance.mdx +++ b/docs/maintenance.mdx @@ -17,7 +17,7 @@ Continuwuity has moderation admin commands for: - fetching `/.well-known/matrix/support` from servers (`!admin federation`) - blocking incoming federation for certain rooms (not the same as room banning) (`!admin federation`) -- deleting media (see [the media section](#media)) +- deleting media Any commands with `-list` in them will require a codeblock in the message with each object being newline delimited. An example of doing this is: diff --git a/docs/public/advanced/delegated.docker-compose.for-traefik.yml b/docs/public/advanced/delegated.docker-compose.for-traefik.yml index 4b5d0fed8..b339968a9 100644 --- a/docs/public/advanced/delegated.docker-compose.for-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.for-traefik.yml @@ -1,12 +1,12 @@ # Continuwuity - Behind Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml index 3a0f9566b..9cf49aec6 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy-labels.yml @@ -12,18 +12,18 @@ services: - proxy volumes: - /var/run/docker.sock:/var/run/docker.sock - - ./data:/data + - ./caddy-data:/data restart: unless-stopped labels: caddy: example.com - caddy.reverse_proxy: /.well-known/matrix/* homeserver:8008 + caddy.reverse_proxy: /.well-known/matrix/* continuwuity:8008 - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -46,8 +46,5 @@ services: caddy: matrix.example.com caddy.reverse_proxy: "{{upstreams 8008}}" -volumes: - db: - networks: proxy: diff --git a/docs/public/advanced/delegated.docker-compose.with-caddy.yml b/docs/public/advanced/delegated.docker-compose.with-caddy.yml index 99c3b3435..9a1178315 100644 --- a/docs/public/advanced/delegated.docker-compose.with-caddy.yml +++ b/docs/public/advanced/delegated.docker-compose.with-caddy.yml @@ -9,17 +9,17 @@ services: networks: - caddy volumes: - - ./data:/data + - ./caddy-data:/data # mount your created Caddyfile into the container - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -41,6 +41,3 @@ services: networks: proxy: - -volumes: - db: diff --git a/docs/public/advanced/delegated.docker-compose.with-traefik.yml b/docs/public/advanced/delegated.docker-compose.with-traefik.yml index 675f2a18e..9c9d744e0 100644 --- a/docs/public/advanced/delegated.docker-compose.with-traefik.yml +++ b/docs/public/advanced/delegated.docker-compose.with-traefik.yml @@ -1,12 +1,12 @@ # Continuwuity - With Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -40,7 +40,7 @@ services: - "443:443" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - - "acme:/etc/traefik/acme" + - "./traefik-acme-data:/etc/traefik/acme" labels: - "traefik.enable=true" @@ -77,9 +77,5 @@ services: TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock" TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false -volumes: - db: - acme: - networks: proxy: diff --git a/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml b/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml index 93dd6dae5..7eb68e19e 100644 --- a/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml +++ b/docs/public/calls/livekit.docker-compose.with-caddy-labels.yml @@ -37,7 +37,7 @@ services: # If you already configured `[global.well_known]` with Continuwuity, # comment out the *_respond labels and uncomment the line below: - # caddy.reverse_proxy: /.well-known/matrix/* homeserver:8008 + # caddy.reverse_proxy: /.well-known/matrix/* continuwuity:8008 # If you are having problems with continuwuity serving headers, # uncomment the header section below. @@ -48,7 +48,7 @@ services: # caddy.0_header.Access-Control-Allow-Headers: "Authorization" # caddy.0_header.Content-Type: "application/json" - homeserver: + continuwuity: image: forgejo.ellis.link/continuwuation/continuwuity:latest restart: unless-stopped # add additional environment, volume, and network config here... diff --git a/docs/public/deploying/docker-compose.for-traefik.yml b/docs/public/deploying/docker-compose.for-traefik.yml index 61cdb1bea..7394886a9 100644 --- a/docs/public/deploying/docker-compose.for-traefik.yml +++ b/docs/public/deploying/docker-compose.for-traefik.yml @@ -1,12 +1,12 @@ # Continuwuity - Behind Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -18,7 +18,7 @@ services: - "traefik.http.routers.continuwuity.tls=true" - "traefik.http.routers.continuwuity.service=continuwuity" - "traefik.http.services.continuwuity.loadbalancer.server.port=8008" - # possibly, depending on your config: + # enable tls with the `letsencrypt` certificate resolver (actual name dependant on your static config) # - "traefik.http.routers.continuwuity.tls.certresolver=letsencrypt" environment: CONTINUWUITY_SERVER_NAME: example.com @@ -34,9 +34,6 @@ services: server=example.com:443 } -volumes: - db: - networks: # This must match the network name that Traefik listens on proxy: diff --git a/docs/public/deploying/docker-compose.override.yml b/docs/public/deploying/docker-compose.override.yml index 5906bb314..be1ef8522 100644 --- a/docs/public/deploying/docker-compose.override.yml +++ b/docs/public/deploying/docker-compose.override.yml @@ -1,7 +1,7 @@ # Continuwuity - Traefik Reverse Proxy Labels (override file) services: - homeserver: + continuwuity: labels: - "traefik.enable=true" - "traefik.docker.network=proxy" # Change this to the name of your Traefik docker proxy network diff --git a/docs/public/deploying/docker-compose.with-caddy-labels.yml b/docs/public/deploying/docker-compose.with-caddy-labels.yml index 078e7802b..3099ee176 100644 --- a/docs/public/deploying/docker-compose.with-caddy-labels.yml +++ b/docs/public/deploying/docker-compose.with-caddy-labels.yml @@ -12,15 +12,15 @@ services: - proxy volumes: - /var/run/docker.sock:/var/run/docker.sock - - ./data:/data + - ./caddy-data:/data restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: diff --git a/docs/public/deploying/docker-compose.with-caddy.yml b/docs/public/deploying/docker-compose.with-caddy.yml index 7f8d83fbf..3e7609e4a 100644 --- a/docs/public/deploying/docker-compose.with-caddy.yml +++ b/docs/public/deploying/docker-compose.with-caddy.yml @@ -10,17 +10,17 @@ services: networks: - proxy volumes: - - ./data:/data + - ./caddy-data:/data # mount your created Caddyfile into the container - ./Caddyfile:/etc/caddy/Caddyfile restart: unless-stopped - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's # - ./continuwuity.toml:/etc/continuwuity.toml environment: @@ -43,6 +43,3 @@ services: networks: proxy: - -volumes: - db: diff --git a/docs/public/deploying/docker-compose.with-traefik.yml b/docs/public/deploying/docker-compose.with-traefik.yml index 9eac48e82..afc084300 100644 --- a/docs/public/deploying/docker-compose.with-traefik.yml +++ b/docs/public/deploying/docker-compose.with-traefik.yml @@ -1,12 +1,12 @@ # Continuwuity - With Traefik Reverse Proxy services: - homeserver: + continuwuity: image: "forgejo.ellis.link/continuwuation/continuwuity:latest" restart: unless-stopped command: /sbin/conduwuit volumes: - - db:/var/lib/continuwuity + - ./continuwuity-data:/var/lib/continuwuity - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's #- ./continuwuity.toml:/etc/continuwuity.toml networks: @@ -40,7 +40,7 @@ services: - "443:443" volumes: - "/var/run/docker.sock:/var/run/docker.sock:ro" - - "acme:/etc/traefik/acme" + - "./traefik-acme-data:/etc/traefik/acme" labels: - "traefik.enable=true" @@ -77,9 +77,5 @@ services: TRAEFIK_PROVIDERS_DOCKER_ENDPOINT: "unix:///var/run/docker.sock" TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: false -volumes: - db: - acme: - networks: proxy: diff --git a/docs/public/deploying/docker-compose.yml b/docs/public/deploying/docker-compose.yml index a9d4491e0..342a94615 100644 --- a/docs/public/deploying/docker-compose.yml +++ b/docs/public/deploying/docker-compose.yml @@ -1,41 +1,38 @@ # Continuwuity - Bare Configuration (for other reverse proxies) services: - homeserver: - image: "forgejo.ellis.link/continuwuation/continuwuity:latest" - restart: unless-stopped - command: /sbin/conduwuit - ports: + homeserver: + image: "forgejo.ellis.link/continuwuation/continuwuity:latest" + restart: unless-stopped + command: /sbin/conduwuit + ports: - # If your reverse proxy is on the host, use this - # and configure it to connect to `127.0.0.1:8008` - - 127.0.0.1:8008:8008 + # If your reverse proxy is on the host, use this + # and configure it to connect to `127.0.0.1:8008` + - 127.0.0.1:8008:8008 - # If your reverse proxy is on another machine, use this - # and configure it to connect to :8008 - # - 8008:8008 + # If your reverse proxy is on another machine, use this + # and configure it to connect to :8008 + # - 8008:8008 - # If your reverse proxy is a docker container on the same network, - # comment out the entire `ports` section, and configure it to connect to `continuwuity:8008` + # If your reverse proxy is a docker container on the same network, + # comment out the entire `ports` section, and configure it to connect to `continuwuity:8008` - volumes: - - db:/var/lib/continuwuity - - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's - #- ./continuwuity.toml:/etc/continuwuity.toml - environment: - CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS - CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity - CONTINUWUITY_ADDRESS: 0.0.0.0 - CONTINUWUITY_PORT: 8008 - #CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above + volumes: + - ./continuwuity-data:/var/lib/continuwuity + - ./continuwuity-resolv.conf:/etc/resolv.conf # use custom resolvers rather than Docker's + #- ./continuwuity.toml:/etc/continuwuity.toml + environment: + CONTINUWUITY_SERVER_NAME: example.com # EDIT THIS + CONTINUWUITY_DATABASE_PATH: /var/lib/continuwuity + CONTINUWUITY_ADDRESS: 0.0.0.0 + CONTINUWUITY_PORT: 8008 + #CONTINUWUITY_CONFIG: '/etc/continuwuity.toml' # Uncomment if you mapped config toml above - ## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443 - ## If you do this, remove all routes to port :8448 on your reverse proxy - # CONTINUWUITY_WELL_KNOWN: | - # { - # client=https://example.com, - # server=example.com:443 - # } - -volumes: - db: + ## (Optional) Serve .well-known files to tell others to reach Continuwuity on port :443 + ## If you do this, remove all routes to port :8448 on your reverse proxy + # CONTINUWUITY_WELL_KNOWN: | + # { + # client=https://example.com, + # server=example.com:443 + # } diff --git a/docs/public/guides/grafana-dashboard.json b/docs/public/guides/grafana-dashboard.json index e7922d37b..4f1b73520 100644 --- a/docs/public/guides/grafana-dashboard.json +++ b/docs/public/guides/grafana-dashboard.json @@ -302,7 +302,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "", "refId": "A", "range": true @@ -496,7 +496,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p50", "refId": "A", "range": true @@ -506,7 +506,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p95", "refId": "B", "range": true @@ -516,7 +516,7 @@ "type": "prometheus", "uid": "${datasource}" }, - "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))", + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))", "legendFormat": "p99", "refId": "C", "range": true @@ -1228,7 +1228,7 @@ { "type": "timeseries", "title": "PDU lag", - "description": "Time between an accepted PDU's origin_server_ts and its arrival; affected by clock skew", + "description": "Time between an accepted PDU's origin_server_ts and its transaction arriving; affected by clock skew", "id": 21, "datasource": { "type": "prometheus", diff --git a/docs/reference/admin/server.md b/docs/reference/admin/server.md index 95a0af91d..0a56394fe 100644 --- a/docs/reference/admin/server.md +++ b/docs/reference/admin/server.md @@ -36,10 +36,6 @@ List database backups Send a message to the admin room -## `!admin server reload` - -Hot-reload the server - ## `!admin server restart` Restart the server diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index 025e69bd7..be145114b 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -1,9 +1,9 @@ # Troubleshooting Continuwuity -:::warning{title="Docker users:"} -Docker can be difficult to use and debug. It's common for Docker -misconfigurations to cause issues, particularly with networking and permissions. -Please check that your issues are not due to problems with your Docker setup. +:::warning{title="For Docker users"} +It's common for Docker misconfigurations to cause issues, particularly with networking and +permissions. Before continuing, please first check that your issues are notdue Docker +problems. See the dedicated [**Docker issues**](#docker-issues) section for more details. ::: ## Continuwuity issues @@ -13,9 +13,9 @@ Please check that your issues are not due to problems with your Docker setup. Some slowness is to be expected if you're the first person on your homeserver to join a room (which will always be the case for single-user homeservers). In this situation, your homeserver has to verify the signatures of all of the state events sent by other servers before your join. To make this process as fast as possible, make sure you have -[multiple fast, trusted servers](./guides/performance.mdx#tuning-your-trusted-servers) listed in `trusted_servers` in your configuration, and ensure -`query_trusted_key_servers_first_on_join` is set to true (the default). -If you need suggestions for trusted servers, ask in the Continuwuity main room. +multiple fast, trusted servers listed in `trusted_servers` in your configuration, and ensure +`query_trusted_key_servers_first_on_join` is set to true (the default). Read the +[Tuning your trusted servers](./guides/performance.mdx#tuning-your-trusted-servers) section for more details on doing so. However, _very_ slow joins, especially to rooms with only a few users in them or rooms created by another user on your homeserver, may be caused by [issue !779](https://forgejo.ellis.link/continuwuation/continuwuity/issues/779), @@ -119,11 +119,63 @@ much possible corruption is restored - If all goes will, you should be able to restore back to using `TolerateCorruptedTailRecords` and you have successfully recovered your database +## Docker issues + +### Debugging Docker networking + +The Continuwuity image does not ship with any shell or internal debugging utilities. To debug network conditions for Continuwuity, run another sidecar container that is attached to its network namespace. For example, using the `curl` container: + +```bash +docker run --rm -it \ + --network container:continuwuity \ + docker.io/curlimages/curl \ + curl https://continuwuity.org/.well-known/matrix/server +``` + +### Docker loopback networking issues + +Some distros disallow Docker containers in bridge networks to reach out to their host's public IP by default. This can cause connectivity issues between Continuwuity and other services that are on the same host machine, such as LiveKit or a push server. + +One can test if this is the case by cURLing those services with a sidecar container: + +```bash +docker run --rm -it --network container:continuwuity docker.io/curlimages/curl curl https://push.example.com +# --- some timeout or refused connection errors --- +``` + +To fix this, use the `extra_hosts` parameter to map local service domains to `host-gateway` - a special Docker value that resolves to the internal IP address of the host. + +```diff title="docker-compose.yaml" +services: + continuwuity: + ... +# allow Continuwuity to reach out to the push server and livekit +# via the host gateway loopback address ++ extra_hosts: ++ - "push.example.com:host-gateway" ++ - "livekit.example.com:host-gateway" + + lk-jwt-service: + ... +# allow jwt service to reach out to Continuwuity and livekit +# via the host gateway loopback address ++ extra_hosts: ++ - "livekit.example.com:host-gateway" ++ - "matrix.example.com:host-gateway" +``` + +Reload the compose file, and connections between these services (as well as the sidecar container test above) should now work. + +For more information about the `host-gateway` parameter, kindly consult the Docker docs on [custom DNS with `extra_hosts`][docker-custom-dns] and the [`--add-host` option][docker-add-host]. + +[docker-custom-dns]: https://docs.docker.com/compose/how-tos/networking/#custom-dns-with-extra_hosts +[docker-add-host]: https://docs.docker.com/reference/cli/docker/container/run/#add-host + ## Debugging Note that users should not really need to debug things. If you find yourself debugging and find the issue, please let us know and/or how we can fix it. -Various debug commands can be [found in `!admin debug`](./reference/admin/debug). +Various debug commands can be found in [`!admin debug`](./reference/admin/debug). ### Debug/Trace log level @@ -136,23 +188,34 @@ you need to access debug/trace log levels, you will need to build without the Continuwuity supports changing the tracing log environment filter on-the-fly using the admin command `!admin debug change-log-level `. This accepts -a string **without quotes** the same format as the `log` config option. +a string **without quotes** in the same format as the `log` config option. Complex +filters are also supported as well. -Example: `!admin debug change-log-level debug` +```bash +# set log level to debug +!admin debug change-log-level debug -This can also accept complex filters such as: -`!admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,ruma_state_res=trace` -`!admin debug change-log-level info,conduit_service[{dest="example.com"}]=trace,conduit_service[send{dest="example.org"}]=trace` +# trace logs for all outgoing federation to `example.com` +!admin debug change-log-level info,conduwuit_service::federation[{dest="example.com"}]=trace -And to reset the log level to the one that was set at startup / last config -load, simply pass the `--reset` flag. +# trace logs for client syncs +!admin debug change-log-level info,conduwuit_api::client=trace -`!admin debug change-log-level --reset` +# debug logs for everything except h2 and presence +!admin debug change-log-level trace,h2=off,conduwuit_service::presence=off +``` + +To reset the log level to the one that was set at last config +load, simply do: + +```bash +!admin debug change-log-level --reset +``` ### Pinging servers Continuwuity can ping other servers using `!admin debug ping `. This takes -a server name and goes through the server discovery process and queries +a server name, goes through the server discovery process, and queries `/_matrix/federation/v1/version`. Errors are outputted. While it does measure the latency of the request, it is not indicative of @@ -198,3 +261,10 @@ and is not easy for non-developers to understand. [unbound-tuning]: https://unbound.docs.nlnetlabs.nl/en/latest/topics/core/performance.html [unbound-arch]: https://wiki.archlinux.org/title/Unbound + +## Other troubleshooting topics + +- [LiveKit troubleshooting](./calls/livekit.mdx#troubleshooting) +- [TURN server troubleshooting](./calls/turn.mdx#troubleshooting) +- [Delegation/split-domain troubleshooting](./guides/delegation.mdx#troubleshooting) +- [Push notifications troubleshooting](./guides/push.mdx#troubleshooting) diff --git a/flake.lock b/flake.lock index b7f225738..5834dcd97 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "advisory-db": { "flake": false, "locked": { - "lastModified": 1789329924, - "narHash": "sha256-mykGMFabQ7yP6G373M3VHkrac9PJPKJstrhQz2D/Rdc=", + "lastModified": 1793979272, + "narHash": "sha256-oUcBtPbtS7PlEMuSrgTAN4wv49cXYbwKbQqhH2pah5w=", "owner": "rustsec", "repo": "advisory-db", - "rev": "455fd4bac659b5f1fca3810661c2d8b3c25dad05", + "rev": "309392b18f6b17022f82c701f300433126901068", "type": "github" }, "original": { @@ -18,11 +18,11 @@ }, "crane": { "locked": { - "lastModified": 1788465171, - "narHash": "sha256-Y1/TTVXjYXGF068IThQH9fPSZ0SIE74PABlUxnWTUH0=", + "lastModified": 1793836618, + "narHash": "sha256-TREenflwEjxOSq292FYwbc3kEm7TDRtXCZRNWEdjBmg=", "owner": "ipetkov", "repo": "crane", - "rev": "eb35abda9f232cc6610b1d1e3200d15c49b7ac54", + "rev": "79fd63528501446749c09f08cad486a58c7d173e", "type": "github" }, "original": { @@ -39,11 +39,11 @@ "rust-analyzer-src": "rust-analyzer-src" }, "locked": { - "lastModified": 1789298866, - "narHash": "sha256-6eaV5+MdWy1tAlN4HAFr64pTnYc9jiKGXBsu18cyVjE=", + "lastModified": 1794142885, + "narHash": "sha256-xWFSr7q8IerDAVRk4W7/CgTmi05hMy2qjZ0z3VYpOVk=", "owner": "nix-community", "repo": "fenix", - "rev": "1fc6f36a23fa16e3740987957266f6e4b915c3cd", + "rev": "f7d416b5073152c7f2e4de1a28d1a4330dd30a26", "type": "github" }, "original": { @@ -74,11 +74,11 @@ "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1788450739, - "narHash": "sha256-glZLQlzIn1fXH6PazR2iUmTo7kzzyYSshrWhLS9TqCU=", + "lastModified": 1793576659, + "narHash": "sha256-V1h85lUaJBQoHFrB2vpXZOE0Ju1MYSnIpsehoVZYlDo=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "31729ca8cbdb4fa927b34e5f4353e6a83f39e993", + "rev": "ea2630b7470978622c7689a1ff75d2b389175399", "type": "github" }, "original": { @@ -89,11 +89,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1789149629, - "narHash": "sha256-H6GwaZzZf+4npqv0tph94w9tZddSjFjmQrVsW0z78uk=", + "lastModified": 1794042290, + "narHash": "sha256-ziZn2PvCJE5JEEpqTdxXwJpPB+L3YqoCpTAMCzyaP3U=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "eaad089433ca2bb662274377d33df3d0e51ef28b", + "rev": "f4a03c008967841f2a0b3cb7c436fc6fc31671f6", "type": "github" }, "original": { @@ -105,11 +105,11 @@ }, "nixpkgs-lib": { "locked": { - "lastModified": 1788057806, - "narHash": "sha256-DTQSMxzDWmT0zhguthvegnVkn7CFqGCv4IHCzk5ZUpM=", + "lastModified": 1793504054, + "narHash": "sha256-ThkfL3D/FhCiZFc9+3BtxwuMmpuK+/bGtXCSo1+yVew=", "owner": "nix-community", "repo": "nixpkgs.lib", - "rev": "596e2e3940e09b2abbeb03f75fa1828c57fcd72c", + "rev": "7851ba61fd862b277cb6a9cef37394bc18bb94e4", "type": "github" }, "original": { @@ -132,11 +132,11 @@ "rust-analyzer-src": { "flake": false, "locked": { - "lastModified": 1789128286, - "narHash": "sha256-KRxxgHiKIBp7R2n41IJuE5K4IUiLOpg47EEi3AxuSp8=", + "lastModified": 1794096810, + "narHash": "sha256-dWC+YtMX+cwH3e9ndiFB77ijTsKtO5I2OxfcvUY4j3k=", "owner": "rust-lang", "repo": "rust-analyzer", - "rev": "6aeeb8cf02741e5da07a1615a05faa506cecb21a", + "rev": "03ae6be57aa063bb373f69eead3b8e15168a45d2", "type": "github" }, "original": { @@ -153,11 +153,11 @@ ] }, "locked": { - "lastModified": 1786901030, - "narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=", + "lastModified": 1791885023, + "narHash": "sha256-C3alQ2MEt0zVrUSho5NUDo3jmhbff72++bfwoqT9Omo=", "owner": "numtide", "repo": "treefmt-nix", - "rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa", + "rev": "0d6d739a833ba9a9c93034862e4a7b061a062a1c", "type": "github" }, "original": { diff --git a/nix/packages/continuwuity.nix b/nix/packages/continuwuity.nix index 8baf26b3d..7ba27815d 100644 --- a/nix/packages/continuwuity.nix +++ b/nix/packages/continuwuity.nix @@ -42,7 +42,12 @@ let env = { CARGO_PROFILE = profile; - RUSTFLAGS = rustflags; + # Rust links with its bundled rust-lld by default on linux-gnu targets. + # This bypasses nixpkgs' linker wrapper (and its rpaths), so we make it use the system one. + # `-C linker-features=-lld` is only stable on x86_64, but cc takes the last `-fuse-ld`. + RUSTFLAGS = lib.concatStringsSep " " ( + lib.optional stdenv.hostPlatform.isLinux "-C link-arg=-fuse-ld=bfd" ++ [ rustflags ] + ); GIT_COMMIT_HASH = self.rev or self.dirtyRev or ""; GIT_COMMIT_HASH_SHORT = self.shortRev or self.dirtyShortRev or ""; } @@ -60,18 +65,6 @@ craneLib.buildPackage ( inherit cargoExtraArgs; cargoArtifacts = craneLib.buildDepsOnly attrs; - # Needed to make continuwuity link to rocksdb - postFixup = lib.optionalString (stdenv.hostPlatform.isLinux && rocksdb != null) '' - old_rpath="$(patchelf --print-rpath $out/bin/conduwuit)" - extra_rpath="${ - lib.makeLibraryPath [ - rocksdb - ] - }" - - patchelf --set-rpath "$old_rpath:$extra_rpath" $out/bin/conduwuit - ''; - meta = { description = "A community-driven Matrix homeserver in Rust"; mainProgram = "conduwuit"; diff --git a/nix/packages/default.nix b/nix/packages/default.nix index 7cba9b870..26171e846 100644 --- a/nix/packages/default.nix +++ b/nix/packages/default.nix @@ -18,6 +18,23 @@ { packages = let + # These musl deps aren't in the binary cache, so they're built locally, and their + # test suites run (and break) when the builder can execute musl binaries. + # + # TODO: drop tzdata override once https://github.com/NixOS/nixpkgs/pull/582577 reaches nixos-unstable + # - tzdata: `now.ck` checks against the current date. + # TODO: drop sqlite override once https://github.com/NixOS/nixpkgs/issues/580629 is resolved + # - sqlite: its test runner fails to build `testfixture` when cross-compiling to musl. + muslOverlay = + _final: prev: + lib.genAttrs [ "tzdata" "sqlite" ] ( + name: + if prev.stdenv.hostPlatform.isMusl then + prev.${name}.overrideAttrs { doCheck = false; } + else + prev.${name} + ); + mkPackages = pkgs: let @@ -78,6 +95,7 @@ import inputs.nixpkgs { localSystem = system; crossSystem = "x86_64-unknown-linux-musl"; + overlays = [ muslOverlay ]; } ) )) @@ -86,6 +104,7 @@ import inputs.nixpkgs { localSystem = system; crossSystem = "aarch64-unknown-linux-musl"; + overlays = [ muslOverlay ]; } ) )); diff --git a/nix/packages/rocksdb.nix b/nix/packages/rocksdb.nix index b4427dbc4..8b5076535 100644 --- a/nix/packages/rocksdb.nix +++ b/nix/packages/rocksdb.nix @@ -18,13 +18,13 @@ inherit enableJemalloc; }).overrideAttrs ({ - version = "continuwuity-v0.5.0-unstable-2026-05-19"; + version = "continuwuity-v0.5.0-unstable-2026-11-08"; src = fetchFromGitea { domain = "forgejo.ellis.link"; owner = "continuwuation"; repo = "rocksdb"; - rev = "3756b2b905e13216d8b56bcc783d814e7b073aff"; - hash = "sha256-rSv4fr2bf9JJwdodgeuPCuceeh7k97KVxrAOC0wyPQY="; + rev = "722fa3219df4169610fda8962221a1ff74026fdb"; + hash = "sha256-ZuXXp83Hgj0B5v499CNxa9oNQUS/ZKYOAZEhmarUifc="; }; # We have this already at https://forgejo.ellis.link/continuwuation/rocksdb/commit/a935c0273e1ba44eacf88ce3685a9b9831486155 diff --git a/nix/rust.nix b/nix/rust.nix index 0d4ee40a4..5af1e067d 100644 --- a/nix/rust.nix +++ b/nix/rust.nix @@ -12,7 +12,7 @@ target: target.fromToolchainName { name = (lib.importTOML "${inputs.self}/rust-toolchain.toml").toolchain.channel; - sha256 = "sha256-zm3dyIY2T414ZRR3EhLOvptzG6gta4WZUcawzMUWtqI="; + sha256 = "sha256-MFHoWVcPZKjFrLnQnodCXbUsfZcofGfo9tV9fTTvklg="; }; in { diff --git a/package-lock.json b/package-lock.json index 2e62f2d1a..f8ff7b797 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,26 +11,26 @@ "devDependencies": { "@rspress/core": "^2.0.0", "@rspress/plugin-client-redirects": "^2.0.0", - "@rspress/plugin-sitemap": "^2.0.0", + "@types/node": "^26.6.6", "typescript": "^7.0.0" } }, "node_modules/@emnapi/core": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", - "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "version": "2.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz", + "integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.3", + "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "version": "2.0.0-beta.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz", + "integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==", "dev": true, "license": "MIT", "optional": true, @@ -39,9 +39,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", - "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", "dev": true, "license": "MIT", "optional": true, @@ -106,33 +106,36 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", - "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz", + "integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==", "dev": true, "license": "MIT", "optional": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "node_modules/@rsbuild/core": { - "version": "2.2.11", - "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.2.11.tgz", - "integrity": "sha512-avPW0j6RaEbtV2mfl0AzTAJEimPX4Xj0pCcZyxNCrE9vkS91HmweM5V7XQj3kI5iTYfHRp9Y6To8RRHYLEvG7A==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.3.tgz", + "integrity": "sha512-IdbBXZrIY16RxnQduXRrsRBQtJ/X7JkYESrk6D46WA918wrckYTBxE09vHvDxR+3JoCLE02vOm2NPBNxqaUw5A==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/core": "~2.2.8", - "@swc/helpers": "^0.5.23" + "@rspack/core": "~2.3.3", + "@swc/helpers": "^0.5.24" }, "bin": { "rsbuild": "bin/rsbuild.js" @@ -150,14 +153,14 @@ } }, "node_modules/@rsbuild/plugin-react": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.1.0.tgz", - "integrity": "sha512-RQTIAWB/CwPjoWt9iAl+8HixeQVgZ7kEIBrWPCixfITyHdiD84h0YpUTpEUuz6kGHw1KXT9mHZ3Rwy6WG7aRDA==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@rsbuild/plugin-react/-/plugin-react-2.1.1.tgz", + "integrity": "sha512-tLtUedsRtTLS6M4VtwzI6aakFLOFdgl9Sh1ZNBWvxb0Te3EnHrppaE7UiYEmDUXQDJ50gfr6yyirtxY5N6moyg==", "dev": true, "license": "MIT", "dependencies": { "@rspack/plugin-react-refresh": "^2.0.2", - "react-refresh": "^0.18.0" + "react-refresh": "^0.19.0" }, "peerDependencies": { "@rsbuild/core": "^2.0.0" @@ -169,32 +172,32 @@ } }, "node_modules/@rspack/binding": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.2.8.tgz", - "integrity": "sha512-c9flkSua3khHnOKBCRk8BkHGOwU9YB7niv+5JfQXiLZIvJmgKsZ7PD8QrFklMhsJT3oVAc6c9GN7/wy1YkACjA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.3.tgz", + "integrity": "sha512-wwF++36a3rqYi0G9zj+rUavn/GIMzbzXehelGS1jkYeKPHyPXrVYwRHqwEKNKMD9z+FdW4YJKQcfFkPlHEiwUg==", "dev": true, "license": "MIT", "optionalDependencies": { - "@rspack/binding-darwin-arm64": "2.2.8", - "@rspack/binding-darwin-x64": "2.2.8", - "@rspack/binding-linux-arm64-gnu": "2.2.8", - "@rspack/binding-linux-arm64-musl": "2.2.8", - "@rspack/binding-linux-ppc64-gnu": "2.2.8", - "@rspack/binding-linux-riscv64-gnu": "2.2.8", - "@rspack/binding-linux-riscv64-musl": "2.2.8", - "@rspack/binding-linux-s390x-gnu": "2.2.8", - "@rspack/binding-linux-x64-gnu": "2.2.8", - "@rspack/binding-linux-x64-musl": "2.2.8", - "@rspack/binding-wasm32-wasi": "2.2.8", - "@rspack/binding-win32-arm64-msvc": "2.2.8", - "@rspack/binding-win32-ia32-msvc": "2.2.8", - "@rspack/binding-win32-x64-msvc": "2.2.8" + "@rspack/binding-darwin-arm64": "2.3.3", + "@rspack/binding-darwin-x64": "2.3.3", + "@rspack/binding-linux-arm64-gnu": "2.3.3", + "@rspack/binding-linux-arm64-musl": "2.3.3", + "@rspack/binding-linux-ppc64-gnu": "2.3.3", + "@rspack/binding-linux-riscv64-gnu": "2.3.3", + "@rspack/binding-linux-riscv64-musl": "2.3.3", + "@rspack/binding-linux-s390x-gnu": "2.3.3", + "@rspack/binding-linux-x64-gnu": "2.3.3", + "@rspack/binding-linux-x64-musl": "2.3.3", + "@rspack/binding-wasm32-wasi": "2.3.3", + "@rspack/binding-win32-arm64-msvc": "2.3.3", + "@rspack/binding-win32-ia32-msvc": "2.3.3", + "@rspack/binding-win32-x64-msvc": "2.3.3" } }, "node_modules/@rspack/binding-darwin-arm64": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.2.8.tgz", - "integrity": "sha512-d6GuY/k7kJk7SOXmruIz0m+2fIXaLv2SnBHEYsbvBzE7ZO6QXq7fSABWFWNnSnNu+brYHA5Dr/skV81bXgTTCw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.3.tgz", + "integrity": "sha512-G9WcBOP/6ZWeqTM/G0/rkJRY4DWmYQvk2untzcpj92uO12tqjZ9BSMgtBFvwElwagfQBkX8PPutkAZgtnlAoWA==", "cpu": [ "arm64" ], @@ -206,9 +209,9 @@ ] }, "node_modules/@rspack/binding-darwin-x64": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.2.8.tgz", - "integrity": "sha512-xCVou/jJASjEAjwy1T3hPJcJqA5QZASJfUwHqEk+nA0v44MagwH8tM8lsOvRfhzR7N2+YFac1rfZOUT8uM3awg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.3.tgz", + "integrity": "sha512-6agI5XDoihay+84vzZgIwwpQQ3xBWbe2HTWBRc0n42LzynIj9h7Qv8CJzf1gSDV1Ts0jzDgAJCYUFJ6Ya5F6MA==", "cpu": [ "x64" ], @@ -220,16 +223,13 @@ ] }, "node_modules/@rspack/binding-linux-arm64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.2.8.tgz", - "integrity": "sha512-Zy/ss6YAQTjOWKDkcWrbKtu+pySltqT22wn68nlrWKygPWLNmMdU5anlsnwRTIuQ3MF0YJRS42ARauVtlqvRQw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.3.tgz", + "integrity": "sha512-VdjK1mDq+GBexd041lmWBFmAvcWIZy7kepTJbJgxLeHYYOnI3KmBG15kemhlK0pBySa+bePX7p2w8uYtl1HsCA==", "cpu": [ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -237,16 +237,13 @@ ] }, "node_modules/@rspack/binding-linux-arm64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.2.8.tgz", - "integrity": "sha512-lxgp5O8PhL3St9p82llHoNoeWzp9jltW5S9F00p00XPJZHUIuxbwfLSzn/6Wg86USEmafLoBkyD9CM8rBd3SNQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.3.tgz", + "integrity": "sha512-xF4Wy4XwGjC3m13tFm1q9p9Qpm31qrk6f5zEMPZC31UVabb+2jrgTI1pfZ8IRuo9x/Qw9s+Zq3hyDbtJvvD8Pg==", "cpu": [ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -254,16 +251,13 @@ ] }, "node_modules/@rspack/binding-linux-ppc64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.2.8.tgz", - "integrity": "sha512-MY+YqpT02tcDCMgHy+IewQsaz7ql4mbJaAqqMlTIqvQwAUl9dXEP7BL352OgCxm9VRebTldE5lK99A3wVd3zqA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.3.tgz", + "integrity": "sha512-jVmn+LpF44D4FdZyT91rlT/tPMdHIfPfQTgVzwPB5nDICp4b57SFjVBApuAPIxnLT1pKLkv/LIcdvGSdAeX12w==", "cpu": [ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -271,16 +265,13 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.2.8.tgz", - "integrity": "sha512-wmN9OigSGNGCKY+AOYaWI8LJcIi8qvs5KjueBueCKOnTV6MPIEujA75QZH1pehTTYKvdGv7r2EtUXUmWpn7/SQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.3.tgz", + "integrity": "sha512-JcQJm8M634jkbG6zJ3TfziKYsCINEAh3FwKuxLljvBgGDEupBxPuB0n2bXBIUeI8P9C33B45IYX6BwWYXll/zw==", "cpu": [ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -288,16 +279,13 @@ ] }, "node_modules/@rspack/binding-linux-riscv64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.2.8.tgz", - "integrity": "sha512-ZcQMYR10hLh581zs9MFnFFn0F7wyt5fkDffyukeMHJEoPJrbkfl6cQtsUdpQnZ+mYGYS5KydD1DT9/eMH65jjw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.3.tgz", + "integrity": "sha512-YMIOS7rFvCDnpeyxoVEVbM7U/TwcC2VDtN3Oiq9BenRsNTEvk0imINhuVRFanh15+wkiQHk9h0b+pzcggYLAsA==", "cpu": [ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -305,16 +293,13 @@ ] }, "node_modules/@rspack/binding-linux-s390x-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.2.8.tgz", - "integrity": "sha512-ahBiE+Ir1FMYvStYicihhSJlS2YRagxtry0jWH8zW287o7C0eiHJ+pteJHHC15T5RJqm0j6w5TuwYe+F9AYxxg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.3.tgz", + "integrity": "sha512-tHGtIG6GGHsk2KvSleQp/BrVqiGdjDsLJuMKR7hE7W1uJW6WDJ+a+Z23Rk5kHXh5BjeFLjXxcufGuokvmLmTag==", "cpu": [ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -322,16 +307,13 @@ ] }, "node_modules/@rspack/binding-linux-x64-gnu": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.2.8.tgz", - "integrity": "sha512-dncEI515NoPXh3zzWk06Rb3mhSV76myiFKqXiJ8K4fVAe5x/RlweMhvPhHhm7RnIMeBld7BeStzOqj38XFsWGA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.3.tgz", + "integrity": "sha512-spe8SjywfO+dD7Sk+vIpPaOXf56wstrgeuztfJdiI9zTeQmf/lhdaNUUSUAXlGIaLjrN/PhV8i5kbQ7VaAkenw==", "cpu": [ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -339,16 +321,13 @@ ] }, "node_modules/@rspack/binding-linux-x64-musl": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.2.8.tgz", - "integrity": "sha512-pfFyU03PjD0GaQG8zOQOHwq51rrJZetXjTGpMmz7iA1hq/f9lChJsDWrC8/7VXeQLwBofLZlOODqe8OM8OBzgA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.3.tgz", + "integrity": "sha512-4E4OJodrmsS52zkSAWShG/F07etr0OG4oSrIN+/2BBgc0qR2wwu2T+rAs308IL3lbywlS+J+cynrRcsSFMD+Kg==", "cpu": [ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -356,9 +335,9 @@ ] }, "node_modules/@rspack/binding-wasm32-wasi": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.2.8.tgz", - "integrity": "sha512-3mOJuZTrF56jOh/GD9chLMJKbzPZ6Ty2OIML7+lLz0Yk2XS/xWRfLn85Dmnkb/O6UF65x7+p8VPAIZlBtLTclw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.3.tgz", + "integrity": "sha512-AhlsPjW31TGP8N+J7OmbCPaamARUl+OQNiT3xo0PL5Dz5oMm+bEfYLostpehKyy8MNDrmJcY97M9pDb5MDMA0w==", "cpu": [ "wasm32" ], @@ -366,15 +345,15 @@ "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "1.11.3", - "@emnapi/runtime": "1.11.3", - "@napi-rs/wasm-runtime": "1.1.6" + "@emnapi/core": "2.0.0-beta.3", + "@emnapi/runtime": "2.0.0-beta.3", + "@napi-rs/wasm-runtime": "1.2.7" } }, "node_modules/@rspack/binding-win32-arm64-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.2.8.tgz", - "integrity": "sha512-Cu/RMZT/16s+67xhl6X1pswetL3GLSQl+LnugKRh08Ul21A/tR7vxC4g4aih4u9k5SXCAngxFUt8zAjKnHIBqA==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.3.tgz", + "integrity": "sha512-Zqbj7GBPtkJ8GlUKAjFgvmOxKkQwjfS3XfjwGBcmoIAUb4IxUsmMqvi+gfKrvI45SjYVFZaJnTpOJw6GL79K+Q==", "cpu": [ "arm64" ], @@ -386,9 +365,9 @@ ] }, "node_modules/@rspack/binding-win32-ia32-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.2.8.tgz", - "integrity": "sha512-H/erd6di8OapZhhM0raA/7XduPn9jusfLMeO1XF+AmF9WF3HzHgMjha1j+KwtPgQnaH69w6AhY+G2472VIwQmw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.3.tgz", + "integrity": "sha512-sJJmbrdzH6kI48mCsUu5a2+BzEktLmHrHUmWGkAPAi0zhi4anA7sOdS1+uERbkkd/XAzs0bdn3JXyT2djY+3IA==", "cpu": [ "ia32" ], @@ -400,9 +379,9 @@ ] }, "node_modules/@rspack/binding-win32-x64-msvc": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.2.8.tgz", - "integrity": "sha512-BziHSUlIQM0MliCqdcHuBXSkQGtPoHQTXJce7fsgnTAzQFgPeog92qTNezYI4IrQ7pQouyiVJ2HPieUbVPRKQQ==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.3.tgz", + "integrity": "sha512-1r3wxV1pBNykqpbEbZWqcrZd13PKLq0e7Ku6qv8IGKKeftuf3RUxTkeM5AzppGMGEIA9sw8mRdN7NvEXxqLLxw==", "cpu": [ "x64" ], @@ -414,13 +393,13 @@ ] }, "node_modules/@rspack/core": { - "version": "2.2.8", - "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.2.8.tgz", - "integrity": "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.3.tgz", + "integrity": "sha512-stAYr0SXf+ZFXFsWTv+Ljxoj/nQs2p7gX9V1kBwlO2IXlRAAhabLONYibT3ZeEGybx3kowrs7uJkcOQsuHgghw==", "dev": true, "license": "MIT", "dependencies": { - "@rspack/binding": "2.2.8" + "@rspack/binding": "2.3.3" }, "engines": { "node": "^20.19.0 || >=22.12.0" @@ -455,40 +434,41 @@ } }, "node_modules/@rspress/core": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.0.23.tgz", - "integrity": "sha512-two8zdTxN9iJBSyiFXwRLLDXz/yLY2+4ycz8wHjJYzeeuFi/EN2eqsKw1nSpY7sxEGIssY1X74c6017JJUBTyA==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.4.tgz", + "integrity": "sha512-7OmP7ABDgQLSpVfpBHfpjqu4H3PGBGMyhLxF1crPQ48Q6MIWAVu77nw7cONn8AZa9GoVq0N/DoE3GEtgZzlu6w==", "dev": true, "license": "MIT", "dependencies": { "@mdx-js/mdx": "^3.1.1", "@mdx-js/react": "^3.1.1", - "@rsbuild/core": "^2.2.10", - "@rsbuild/plugin-react": "~2.1.0", - "@rspress/shared": "2.0.23", + "@rsbuild/core": "^2.3.3", + "@rsbuild/plugin-react": "~2.1.1", + "@rspress/shared": "2.1.4", "@shikijs/rehype": "^4.2.0", + "@shikijs/transformers": "^4.2.0", "@types/mdast": "^4.0.4", - "@types/react": "^19.2.18", + "@types/react": "^19.3.0", "@unhead/react": "^2.1.17", "body-scroll-lock": "4.0.0-beta.0", "clsx": "2.1.1", "copy-to-clipboard": "^3.3.3", "flexsearch": "0.8.212", "hast-util-heading-rank": "^3.0.0", - "hast-util-to-jsx-runtime": "^2.3.6", + "hast-util-to-jsx-runtime": "^2.3.7", "mdast-util-mdx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.1", - "medium-zoom": "1.1.0", + "medium-zoom": "1.1.2", "nprogress": "^0.2.0", - "react": "^19.2.8", - "react-dom": "^19.2.8", + "react": "^19.3.1", + "react-dom": "^19.3.1", "react-lazy-with-preload": "^2.2.1", "react-render-to-markdown": "19.1.0", - "react-router-dom": "^7.18.4", + "react-router-dom": "^7.18.5", "rehype-external-links": "^3.0.0", "rehype-raw": "^7.0.0", - "remark-cjk-friendly": "^2.3.1", - "remark-cjk-friendly-gfm-strikethrough": "^2.3.1", + "remark-cjk-friendly": "^2.3.4", + "remark-cjk-friendly-gfm-strikethrough": "^2.3.3", "remark-gfm": "^4.0.1", "remark-mdx": "^3.1.1", "remark-parse": "^11.0.0", @@ -508,71 +488,58 @@ } }, "node_modules/@rspress/plugin-client-redirects": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.0.23.tgz", - "integrity": "sha512-TdpvO3TREv6s2mE32ztFvG3P232qUwjyQCKKsb9g0XT0q7rzcStZFRE7XT/L8i0XTzH/mfli1tVl4guTea/J3Q==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.4.tgz", + "integrity": "sha512-6/g+Mr8lslqiFzlMBouex8TLm6PlQK6cmZ71Yfv82+Uxcrb+LaFAFiPbq2G7gToXBQUoECM4D/7nSLAfeOhnEQ==", "dev": true, "license": "MIT", "engines": { "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "@rspress/core": "^2.0.10" - } - }, - "node_modules/@rspress/plugin-sitemap": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.0.23.tgz", - "integrity": "sha512-r37TvCP2wuQX8JbA7hHti8JXhVx4HiaJPn702NgFhGyolGJYIUTRQCO2/ixiP1FZJuxZ4c0yb4ZyNeDa9ZPMlw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || >=22.12.0" - }, - "peerDependencies": { - "@rspress/core": "^2.0.10" + "@rspress/core": "^2.1.0-beta.2" } }, "node_modules/@rspress/shared": { - "version": "2.0.23", - "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.0.23.tgz", - "integrity": "sha512-kE2GXRCQ7GAl2wll1JBWRHEkZICKcWv3V86m8TkjiWb0eEdjACl3kns7j00KTq4UbE35kUPOs+0Lx8vGqK7q9w==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz", + "integrity": "sha512-SuQyVKn9xcQwkzfl+4bPBzX10gxbhCs9UupqSoPtxvyr9pMgSbXnlo3gxTPZXLzk5HUqZZ6tlIju25PVCEtYWA==", "dev": true, "license": "MIT", "dependencies": { - "@rsbuild/core": "^2.2.10", + "@rsbuild/core": "^2.3.3", "@shikijs/rehype": "^4.2.0", - "@types/react": "^19.2.18", - "mdast-util-mdx-jsx": "^3.2.0", + "@types/react": "^19.3.0", + "mdast-util-mdx-jsx": "^3.2.1", "unified": "^11.0.5" } }, "node_modules/@shikijs/core": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.4.3.tgz", - "integrity": "sha512-QCR4q2ZO/ILJEuwiBMel4wdcTDb1JGwfjKTxPDF6x8ixOaluPrVqIn06C99AcRPhmYlBR56d/Fb+GN58GzExpg==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.6.0.tgz", + "integrity": "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/primitive": "4.4.3", - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/primitive": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", - "hast-util-to-html": "^9.0.5" + "hast-util-to-html": "^9.0.6" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/engine-javascript": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.4.3.tgz", - "integrity": "sha512-FbOjFJp9VLdo1Wevs10BBtVxiTWwNLqZh5Gkhjgda/ioL15YOgeSl9n+6XMa3qRlPQzfhFNe641SrynFHYG0nQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.6.0.tgz", + "integrity": "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" }, "engines": { @@ -580,41 +547,41 @@ } }, "node_modules/@shikijs/engine-oniguruma": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.4.3.tgz", - "integrity": "sha512-EcOQkxdxGQrc1Row/cC2c96/v1dbZqGnEVu1qTuT/MJmp6+cXCvQussowVmCv5Tqr3KuY3c7IbM6HTW3LJ1k9w==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.6.0.tgz", + "integrity": "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2" + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/langs": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.4.3.tgz", - "integrity": "sha512-ePic0yfAJGOF83D5wBHK/00EjK65oahBYxFk5epgq33WRv7X9UuxLEV8PtR0szC0z8dl7INIpIodB99JRFlR+A==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.6.0.tgz", + "integrity": "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3" + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/primitive": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.4.3.tgz", - "integrity": "sha512-m0wBeLDQDeIxRdUmrCPdQqfuUamDwRL5isCfYbguKD6NiaKpVbsv+3J81DyIKgNW5h4WAIIr8T4EkgQrBBxvaQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.6.0.tgz", + "integrity": "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -622,44 +589,58 @@ } }, "node_modules/@shikijs/rehype": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.4.3.tgz", - "integrity": "sha512-vkG9jG1aRnrx05R31uAOKQHE8qpY7r1cBXE2sAZgFK2IaPnQHwaP4L1C6amQixmZ8thBsKwfbSsYxMDoo46UWQ==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/rehype/-/rehype-4.6.0.tgz", + "integrity": "sha512-qv3mGfYJuy+TW6UUyC2QrYSEmTxJNGXZ/NmCEsyH0NHfJIOYGvpWm0kNu6P2Ec14jmGwwTfVLMta/FZtY+MrJQ==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3", + "@shikijs/types": "4.6.0", "@types/hast": "^3.0.5", "hast-util-to-string": "^3.0.1", - "shiki": "4.4.3", + "shiki": "4.6.0", "unified": "^11.0.5", - "unist-util-visit": "^5.1.0" + "unist-util-visit": "^5.2.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/themes": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.4.3.tgz", - "integrity": "sha512-w8UHjeUnIR965KMWJHUPXOc2mNJUnK3vpVLYLvw5IYU2mnTTJ89E24OrJDBNiJDQ0qzb0tc4l7mrIXx5cFeIyw==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.6.0.tgz", + "integrity": "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/types": "4.4.3" + "@shikijs/types": "4.6.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@shikijs/transformers": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-4.6.0.tgz", + "integrity": "sha512-oZ28gYlPOYspv6AD74lCb14AAJugSY/+nJxRWjH42yDbdLAdftVU/PP36tOhb435Sfop2UGWcRGXY7HLLveKCg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "4.6.0", + "@shikijs/types": "4.6.0" }, "engines": { "node": ">=20" } }, "node_modules/@shikijs/types": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.4.3.tgz", - "integrity": "sha512-UEJxmRR++MAGR6hugn0vgVS2W/6lWAts84FFSrnlH9sP0LNol7E5+NQ792pH8liWUhyMyjhTgSUH3k7iD7tc5g==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.6.0.tgz", + "integrity": "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -667,26 +648,23 @@ } }, "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.1.0.tgz", + "integrity": "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ==", "dev": true, "license": "MIT" }, "node_modules/@swc/helpers": { - "version": "0.5.23", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", - "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz", + "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==", "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.8.0" - } + "license": "Apache-2.0" }, "node_modules/@tybys/wasm-util": { - "version": "0.10.4", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", - "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", "dev": true, "license": "MIT", "optional": true, @@ -705,9 +683,9 @@ } }, "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", "dev": true, "license": "MIT" }, @@ -755,6 +733,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, "node_modules/@types/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", @@ -1136,9 +1124,9 @@ } }, "node_modules/acorn": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", - "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", "bin": { @@ -1368,13 +1356,13 @@ } }, "node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=0.12" + "node": ">=20.19.0" }, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" @@ -1562,9 +1550,9 @@ "license": "Apache-2.0" }, "node_modules/get-east-asian-width": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz", - "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "dev": true, "license": "MIT", "engines": { @@ -1575,9 +1563,9 @@ } }, "node_modules/hast-util-from-parse5": { - "version": "8.0.3", - "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.3.tgz", - "integrity": "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==", + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/hast-util-from-parse5/-/hast-util-from-parse5-8.0.4.tgz", + "integrity": "sha512-Yq7XlXor0Cpb71sI2E0zpv8QxQ5a6rfhDEETk4bcgrFX2SvJAY2PHocWwFtL6U9qyfiyByW3wZ6sZEfP2kW81g==", "dev": true, "license": "MIT", "dependencies": { @@ -1638,9 +1626,9 @@ } }, "node_modules/hast-util-raw": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.1.0.tgz", - "integrity": "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==", + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/hast-util-raw/-/hast-util-raw-9.2.0.tgz", + "integrity": "sha512-1zVq3M9AlZiBZ4mlMPnLtkK2rdd+I8VhmFLNLb//XJm6xA2AVH2tz19EHy25RgRWut6z6FpTARAs7P8rnmRJUQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1651,7 +1639,7 @@ "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", - "parse5": "^7.0.0", + "parse5": "^8.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", @@ -1693,9 +1681,9 @@ } }, "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.6.tgz", + "integrity": "sha512-1SZUxCN3TtJAE7e2BQN2MBHsoZ1gnmi9GoCP5Di59CSWptIezSAW09yDZyVbanb78V9eCwrKqdQsjtfVTxYHWA==", "dev": true, "license": "MIT", "dependencies": { @@ -1717,9 +1705,9 @@ } }, "node_modules/hast-util-to-jsx-runtime": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz", - "integrity": "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==", + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.7.tgz", + "integrity": "sha512-F7DNV2NMcTxA4GqPVHnXzX+mpoPHAIY9rJAVH3CZ1FdBZOcBUEjUuvMkMpHVs/sicEtznh9tMGj5WUR9S4E2rg==", "dev": true, "license": "MIT", "dependencies": { @@ -1735,7 +1723,7 @@ "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", - "style-to-js": "^1.0.0", + "style-to-object": "^2.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" }, @@ -1744,6 +1732,23 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-jsx-runtime/node_modules/inline-style-parser": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.9.tgz", + "integrity": "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/hast-util-to-jsx-runtime/node_modules/style-to-object": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-2.0.2.tgz", + "integrity": "sha512-QmbXPUylqU80HAgTOJeEOdbA40W9KtxmjMhQy+tq+b8F2aoh3aQLuy82hh2jm2qsC9hR9eI0+eQidTMydKcqRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inline-style-parser": "0.2.9" + } + }, "node_modules/hast-util-to-parse5": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/hast-util-to-parse5/-/hast-util-to-parse5-8.0.1.tgz", @@ -1793,9 +1798,9 @@ } }, "node_modules/hastscript": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz", - "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.3.tgz", + "integrity": "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA==", "dev": true, "license": "MIT", "dependencies": { @@ -1811,9 +1816,9 @@ } }, "node_modules/hookable": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.1.tgz", - "integrity": "sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==", + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/hookable/-/hookable-6.1.2.tgz", + "integrity": "sha512-+abwxtiEA52GCVIsQqut3S/uKTbUwYIp4Pe/vv+6py5XiXBCqMZHg6pA6Y5qhgLSEys0/cYuPbO0z1QFj5ZCmg==", "dev": true, "license": "MIT" }, @@ -1828,13 +1833,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/inline-style-parser": { - "version": "0.2.7", - "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", - "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", - "dev": true, - "license": "MIT" - }, "node_modules/is-absolute-url": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-absolute-url/-/is-absolute-url-4.0.1.tgz", @@ -1934,9 +1932,9 @@ } }, "node_modules/markdown-table": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz", - "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.1.0.tgz", + "integrity": "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw==", "dev": true, "license": "MIT", "funding": { @@ -1945,16 +1943,16 @@ } }, "node_modules/mdast-util-find-and-replace": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.2.tgz", - "integrity": "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.4.tgz", + "integrity": "sha512-z4B5c6jrnJ1ltOQemhWYPBSAo6y42Z8Gt2yEgfgNTMcLSU59B8bfj8Z8AnAlJrBGLnqkdAUZ7jdDEqQw3KuipQ==", "dev": true, "license": "MIT", "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -1962,9 +1960,9 @@ } }, "node_modules/mdast-util-from-markdown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.3.tgz", - "integrity": "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.1.0.tgz", + "integrity": "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A==", "dev": true, "license": "MIT", "dependencies": { @@ -2007,9 +2005,9 @@ } }, "node_modules/mdast-util-gfm-autolink-literal": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz", - "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.1.0.tgz", + "integrity": "sha512-Jx6QSK8wDo558Bcf7q+1pe0v81g2PVs09Hlvu9xJHmCFRF3sAPW7vXFVIAwBncs3sde92WbsVqNxwdqViA2XnQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2043,9 +2041,9 @@ } }, "node_modules/mdast-util-gfm-strikethrough": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.0.tgz", - "integrity": "sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz", + "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==", "dev": true, "license": "MIT", "dependencies": { @@ -2059,9 +2057,9 @@ } }, "node_modules/mdast-util-gfm-table": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz", - "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.1.tgz", + "integrity": "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA==", "dev": true, "license": "MIT", "dependencies": { @@ -2069,7 +2067,9 @@ "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", - "mdast-util-to-markdown": "^2.0.0" + "mdast-util-to-markdown": "^2.0.0", + "mdast-util-to-string": "^4.0.0", + "unist-util-visit": "^5.0.0" }, "funding": { "type": "opencollective", @@ -2077,9 +2077,9 @@ } }, "node_modules/mdast-util-gfm-task-list-item": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz", - "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.1.tgz", + "integrity": "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA==", "dev": true, "license": "MIT", "dependencies": { @@ -2131,9 +2131,9 @@ } }, "node_modules/mdast-util-mdx-jsx": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.0.tgz", - "integrity": "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.2.1.tgz", + "integrity": "sha512-oXp1GIa+E9IwIs3a106+tr3Bz2MlTTBvlXjOZMoIat11kk7vjqgmBnksB9WHmWv+gZh7k3IUgpAHlwHB7DH4GQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2212,9 +2212,9 @@ } }, "node_modules/mdast-util-to-markdown": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.1.2.tgz", - "integrity": "sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown/-/mdast-util-to-markdown-2.2.3.tgz", + "integrity": "sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==", "dev": true, "license": "MIT", "dependencies": { @@ -2223,8 +2223,10 @@ "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", + "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", + "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" }, @@ -2234,15 +2236,17 @@ } }, "node_modules/mdast-util-to-markdown-cjk-friendly": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly/-/mdast-util-to-markdown-cjk-friendly-1.0.0.tgz", - "integrity": "sha512-BoaAm8mlJ+LAYz0Qs532Y3ciTuQYgBUPZcSFbvC/ZKmEMAKgulw84YvQK1gI34t/vL2euSfuaWlqczkTBgamkw==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly/-/mdast-util-to-markdown-cjk-friendly-1.0.2.tgz", + "integrity": "sha512-1HCuZwTxQX3WfaNFk8PDb/VW8Ulvzn+nHD+W79Q9k5NXUSkGXH9Zv3eMJ4VI7GjZIz4Ff7WbruEFgMUaPmRJ8g==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown": "^2.1.2", + "mdast-util-to-markdown": "^2.1.3", "micromark-extension-cjk-friendly-util": "3.0.1", - "micromark-util-symbol": "^2.0.1" + "micromark-util-character": "^2.1.1", + "micromark-util-classify-character": "^2.0.1", + "micromark-util-html-tag-name": "^2.0.1" }, "engines": { "node": ">=18" @@ -2257,16 +2261,15 @@ } }, "node_modules/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough/-/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-1.0.0.tgz", - "integrity": "sha512-1ePVfB4P/vz3xSsm6H3D32r6VYGErxclnuLLFK02/2ReF+UdEKm7caulK6Vm0LBIp5gPRtB2Z1OYDznCkX3k2w==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough/-/mdast-util-to-markdown-cjk-friendly-gfm-strikethrough-1.0.2.tgz", + "integrity": "sha512-aidUweNq42Mok1p6KTJG7m0Ds0+njX3Sp6shhh3/VhwIkyWdn2SqEzkeiwJsK+Ksz0pL6vZUHrVFgFtyX9NMYg==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-gfm-strikethrough": "^2.0.0", - "mdast-util-to-markdown": "^2.1.2", - "micromark-extension-cjk-friendly-util": "3.0.1", - "micromark-util-symbol": "^2.0.1" + "mdast-util-gfm-strikethrough": "^2.0.1", + "mdast-util-to-markdown": "^2.1.3", + "mdast-util-to-markdown-cjk-friendly": "1.0.2" }, "engines": { "node": ">=18" @@ -2295,16 +2298,20 @@ } }, "node_modules/medium-zoom": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/medium-zoom/-/medium-zoom-1.1.0.tgz", - "integrity": "sha512-ewyDsp7k4InCUp3jRmwHBRFGyjBimKps/AJLjRSox+2q/2H4p/PNpQf+pwONWlJiOudkBXtbdmVbFjqyybfTmQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/medium-zoom/-/medium-zoom-1.1.2.tgz", + "integrity": "sha512-0wTqeCQ4NGzjPghi7i2lMI6RyGj9N60fGvzY9HiNcxDTcvOw7S+ri7K3xVkrIZ+2uzUg4w/KSVMDdZXYMtHkdw==", "dev": true, - "license": "MIT" + "license": "MIT", + "workspaces": [ + "website", + "examples/*" + ] }, "node_modules/micromark": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", - "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", + "integrity": "sha512-oGYfQzHSG5dOMovQcJ3fyTmZlWAWpi0XA0sJwJs+i6OT88o1+Jtw/8z0CmdowSLxGhhFK89rQ/oXph/wN02PNw==", "dev": true, "funding": [ { @@ -2328,6 +2335,7 @@ "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", @@ -2338,9 +2346,9 @@ } }, "node_modules/micromark-core-commonmark": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.3.tgz", - "integrity": "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", "dev": true, "funding": [ { @@ -2358,24 +2366,25 @@ "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", - "micromark-factory-space": "^2.0.0", + "micromark-factory-space": "^2.1.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" + "micromark-util-types": "^2.0.3" } }, "node_modules/micromark-extension-cjk-friendly": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly/-/micromark-extension-cjk-friendly-2.0.1.tgz", - "integrity": "sha512-OkzoYVTL1ChbvQ8Cc1ayTIz7paFQz8iS9oIYmewncweUSwmWR+hkJF9spJ1lxB90XldJl26A1F4IkPOKS3bDXw==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-extension-cjk-friendly/-/micromark-extension-cjk-friendly-2.0.2.tgz", + "integrity": "sha512-/BqZNCkDWg3Hj9zEEcRitZ5uMF3X78qmBFuP17oAjnVDZ0+H1GHiDKMJZDpJsXasCHEn/kzl6QHozUiWgCHtPQ==", "dev": true, "license": "MIT", "dependencies": { @@ -2755,9 +2764,9 @@ } }, "node_modules/micromark-factory-space": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.0.1.tgz", - "integrity": "sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", "dev": true, "funding": [ { @@ -2948,6 +2957,26 @@ "micromark-util-symbol": "^2.0.0" } }, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, "node_modules/micromark-util-encode": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", @@ -3111,9 +3140,9 @@ "license": "MIT" }, "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", "dev": true, "funding": [ { @@ -3188,13 +3217,13 @@ "license": "MIT" }, "node_modules/parse5": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", - "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", "dev": true, "license": "MIT", "dependencies": { - "entities": "^6.0.0" + "entities": "^9.0.0" }, "funding": { "url": "https://github.com/inikulin/parse5?sponsor=1" @@ -3212,9 +3241,9 @@ } }, "node_modules/react": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", - "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", "dev": true, "license": "MIT", "engines": { @@ -3222,16 +3251,16 @@ } }, "node_modules/react-dom": { - "version": "19.3.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", - "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", "dev": true, "license": "MIT", "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { - "react": "^19.3.0" + "react": "^19.3.1" } }, "node_modules/react-lazy-with-preload": { @@ -3265,9 +3294,9 @@ "license": "MIT" }, "node_modules/react-refresh": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", - "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.19.0.tgz", + "integrity": "sha512-5HdstYgoJBbBofjapO5qCPcovECJCBfvjLb+iTcsmqDFVMRdqy0qs7iiInBJTUXmIFc2bjoc5b2HVLp2zRtYhQ==", "dev": true, "license": "MIT", "engines": { @@ -3288,9 +3317,9 @@ } }, "node_modules/react-router": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.4.tgz", - "integrity": "sha512-PUPQcMhMGRAslLcvtlPz/kmzBEWPhLdgLFrL7pLNepBL6dX0lWj4WD2cUYVgYCuT3jxvghYFg81cDTj44DhetQ==", + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz", + "integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==", "dev": true, "license": "MIT", "dependencies": { @@ -3311,13 +3340,13 @@ } }, "node_modules/react-router-dom": { - "version": "7.18.4", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.4.tgz", - "integrity": "sha512-yrfmJHIpDG7taCpqKjT1G5B6q3O2K+RN8/fgNf0lTjCwiPbQ0ei6vXX9ZjQR+7ld8Tr7Z5xmyMnZ8YJrphWQUw==", + "version": "7.18.5", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz", + "integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==", "dev": true, "license": "MIT", "dependencies": { - "react-router": "7.18.4" + "react-router": "7.18.5" }, "engines": { "node": ">=20.0.0" @@ -3477,14 +3506,14 @@ } }, "node_modules/remark-cjk-friendly": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.1.tgz", - "integrity": "sha512-f+pKZRxCRwNEGFBKNRAZAqU91GIK1SAo3ZyFHWRUgC9zcxRR0BXKd6YwqgSsxtW0rNpUDtONj7H5nje2WL3fcA==", + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/remark-cjk-friendly/-/remark-cjk-friendly-2.3.4.tgz", + "integrity": "sha512-xhBzjXkumeN5tKXXg6k/THSCZCP6AYV6+wSxnCsPTkxHt60bb9Yk0IWhdD87CFaDCiTqd86LKHtVObcJTmgcow==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown-cjk-friendly": "1.0.0", - "micromark-extension-cjk-friendly": "2.0.1" + "mdast-util-to-markdown-cjk-friendly": "1.0.2", + "micromark-extension-cjk-friendly": "2.0.2" }, "engines": { "node": ">=18" @@ -3500,13 +3529,13 @@ } }, "node_modules/remark-cjk-friendly-gfm-strikethrough": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.3.1.tgz", - "integrity": "sha512-JE3TGgouk/sy92SemNMEUhO5mNP4on04cmzOV3s3R5Dbk160ewmpM4tgPiinKKvoJ5UW2fTu7FOYsjVbusSA9w==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/remark-cjk-friendly-gfm-strikethrough/-/remark-cjk-friendly-gfm-strikethrough-2.3.3.tgz", + "integrity": "sha512-UBujdRd1TTgr79iPdXhCnB9ag7kaM54FBCzTa/jLCNfZFGPyZCZb8G6yoCA0k4M3HTKDvilIVKvPxU6K/05dDw==", "dev": true, "license": "MIT", "dependencies": { - "mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": "1.0.0", + "mdast-util-to-markdown-cjk-friendly-gfm-strikethrough": "1.0.2", "micromark-extension-cjk-friendly-gfm-strikethrough": "2.0.1" }, "engines": { @@ -3625,26 +3654,26 @@ } }, "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", + "version": "2.7.3", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.3.tgz", + "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", "dev": true, "license": "MIT" }, "node_modules/shiki": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.4.3.tgz", - "integrity": "sha512-Mb/GvXPHBAXdgGIcnfU5L3ldpn1XcxrGkPHwqgRx17/I2XRfqlFKk2vGkHWINn1kdXvzJZeuO3is6I9KLPFm0g==", + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.6.0.tgz", + "integrity": "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/core": "4.4.3", - "@shikijs/engine-javascript": "4.4.3", - "@shikijs/engine-oniguruma": "4.4.3", - "@shikijs/langs": "4.4.3", - "@shikijs/themes": "4.4.3", - "@shikijs/types": "4.4.3", - "@shikijs/vscode-textmate": "^10.0.2", + "@shikijs/core": "4.6.0", + "@shikijs/engine-javascript": "4.6.0", + "@shikijs/engine-oniguruma": "4.6.0", + "@shikijs/langs": "4.6.0", + "@shikijs/themes": "4.6.0", + "@shikijs/types": "4.6.0", + "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" }, "engines": { @@ -3697,7 +3726,14 @@ "style-to-object": "1.0.14" } }, - "node_modules/style-to-object": { + "node_modules/style-to-js/node_modules/inline-style-parser": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", + "integrity": "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==", + "dev": true, + "license": "MIT" + }, + "node_modules/style-to-js/node_modules/style-to-object": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/style-to-object/-/style-to-object-1.0.14.tgz", "integrity": "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==", @@ -3737,11 +3773,12 @@ } }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "dev": true, - "license": "0BSD" + "license": "0BSD", + "optional": true }, "node_modules/typescript": { "version": "7.0.2", @@ -3778,6 +3815,13 @@ "@typescript/typescript-win32-x64": "7.0.2" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, "node_modules/unhead": { "version": "2.1.17", "resolved": "https://registry.npmjs.org/unhead/-/unhead-2.1.17.tgz", @@ -3868,15 +3912,15 @@ } }, "node_modules/unist-util-visit": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", - "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.2.0.tgz", + "integrity": "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ==", "dev": true, "license": "MIT", "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.1.0" }, "funding": { "type": "opencollective", @@ -3898,9 +3942,9 @@ } }, "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz", + "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==", "dev": true, "license": "MIT", "dependencies": { @@ -3928,9 +3972,9 @@ } }, "node_modules/vfile-location": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.3.tgz", - "integrity": "sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/vfile-location/-/vfile-location-5.0.4.tgz", + "integrity": "sha512-vEvxatYZCIpNvzGk2UD+u4I/sZkSKoOsdRCbkOIsN73QpJbriJ1qvvBAL1PeI0y55Leoqf7pORbaSPpG/smmOg==", "dev": true, "license": "MIT", "dependencies": { @@ -3943,9 +3987,9 @@ } }, "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.4.tgz", + "integrity": "sha512-66ycRswIkNmHH9PHku7ADtv5RVwgIrOcuv3J8Svz6h4qgGRrKVa+9/neuKyJZUXyOpYwLTvS+whZ4R2urHHgQg==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 6ae3569a6..aa2e0db2c 100644 --- a/package.json +++ b/package.json @@ -20,11 +20,11 @@ "keywords": [], "author": "", "license": "ISC", - "type": "commonjs", + "type": "module", "devDependencies": { "@rspress/core": "^2.0.0", "@rspress/plugin-client-redirects": "^2.0.0", - "@rspress/plugin-sitemap": "^2.0.0", + "@types/node": "^26.6.6", "typescript": "^7.0.0" } } diff --git a/rspress.config.ts b/rspress.config.ts index 9f4931069..3739a13fe 100644 --- a/rspress.config.ts +++ b/rspress.config.ts @@ -1,16 +1,20 @@ import { defineConfig } from '@rspress/core'; -import { pluginSitemap } from '@rspress/plugin-sitemap'; import { pluginClientRedirects } from '@rspress/plugin-client-redirects'; +const sitePath: string = process.env.SITE_PATH ?? '/'; + export default defineConfig({ root: 'docs', title: 'Continuwuity', + siteOrigin: sitePath != "/" ? "https://preview.continuwuity.org" : "https://continuwuity.org", + base: sitePath, description: 'A community-driven Matrix homeserver', icon: '/assets/logo.svg', logo: { light: '/assets/logo.svg', dark: '/assets/logo.svg', }, + llms: false, // Use `.no-zoom` class to disable image zooms mediumZoom: { selector: '.rspress-doc :not(.no-zoom *) > img', @@ -40,7 +44,9 @@ export default defineConfig({ }, }, }, + webMcp: false, themeConfig: { + llmsUI: false, socialLinks: [ { icon: { @@ -72,14 +78,10 @@ export default defineConfig({ lastUpdated: true, enableContentAnimation: true, enableAppearanceAnimation: false, - footer: { - }, + footer: {}, }, - plugins: [pluginSitemap({ - siteUrl: 'https://continuwuity.org', // TODO: Set automatically in build pipeline - }), - pluginClientRedirects({ + plugins: [pluginClientRedirects({ redirects: [{ from: '^/config_reference$', to: '/reference/config' @@ -102,8 +104,8 @@ export default defineConfig({ from: "^/source(|_code)$", to: "https://forgejo.ellis.link/continuwuation/continuwuity", }, { - from: "^/(CONTRIBUTING.md|contributing)$", - to: "/development/contributing" + from: "^/(CONTRIBUTING.md|contributing)$", + to: "/development/contributing" } ] })], diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 8965f816a..cb88237df 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -10,7 +10,7 @@ [toolchain] profile = "minimal" -channel = "1.99.0" +channel = "1.100.0" components = [ # For rust-analyzer "rust-src", diff --git a/src/admin/Cargo.toml b/src/admin/Cargo.toml index 6495ad400..446276ff0 100644 --- a/src/admin/Cargo.toml +++ b/src/admin/Cargo.toml @@ -62,8 +62,6 @@ release_max_log_level = [ "conduwuit-service/release_max_log_level", "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] zstd_compression = [ "conduwuit-api/zstd_compression", @@ -84,7 +82,6 @@ ctor.workspace = true dtor.workspace = true futures.workspace = true lettre.workspace = true -log.workspace = true ruma.workspace = true serde_json.workspace = true serde-saphyr.workspace = true diff --git a/src/admin/appservice/commands.rs b/src/admin/appservice/commands.rs index 9bccc643d..86fa51f27 100644 --- a/src/admin/appservice/commands.rs +++ b/src/admin/appservice/commands.rs @@ -1,4 +1,4 @@ -use conduwuit::{Err, Result, checked}; +use conduwuit::{Err, Result, checked, utils::ReadyExt}; use futures::{FutureExt, StreamExt, TryFutureExt}; impl crate::Context<'_> { @@ -49,7 +49,6 @@ impl crate::Context<'_> { .services .appservice .get_registration(&appservice_identifier) - .await { | None => return Err!("Appservice does not exist."), | Some(config) => { @@ -78,12 +77,11 @@ impl crate::Context<'_> { self.services .users .stream_local_users() - .filter_map(async |user_id| { - if self.services.appservice.is_user_id(&user_id).await { - Some(user_id) - } else { - None - } + .ready_filter_map(|user_id| { + self.services + .appservice + .is_user_id(&user_id) + .then_some(user_id) }) .for_each(async |user_id| { self.services diff --git a/src/admin/debug/commands.rs b/src/admin/debug/commands.rs index 9fc69aae9..8846ffbaa 100644 --- a/src/admin/debug/commands.rs +++ b/src/admin/debug/commands.rs @@ -14,7 +14,7 @@ use conduwuit::{ state_res::EventTypeExt, trace, utils, utils::{ - stream::{IterStream, ReadyExt}, + stream::{BroadbandExt, IterStream, ReadyExt}, string::EMPTY, to_canonical_object, }, @@ -983,7 +983,8 @@ impl crate::Context<'_> { let resolver: &MatrixResolver = if no_cache { &MatrixResolverBuilder::new() .dangerous_tls_accept_invalid_certs(self.services.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .http_client(self.services.client.dns.clone()) + .http_client(self.services.client.matrix_http_client.clone()) + .dns_resolver(self.services.client.dns_resolver.clone()) .build()? } else { &self.services.client.matrix_resolver @@ -1006,7 +1007,7 @@ impl crate::Context<'_> { pub(super) async fn memory_stats(&self, opts: Option) -> Result { const OPTS: &str = "abcdefghijklmnopqrstuvwxyz"; - let opts: String = OPTS + let mut mapped_opts: String = OPTS .chars() .filter(|&c| { let allow_any = opts.as_ref().is_some_and(|opts| opts == "*"); @@ -1017,7 +1018,11 @@ impl crate::Context<'_> { }) .collect(); - let stats = conduwuit::alloc::memory_stats(&opts).unwrap_or_default(); + if opts.as_ref().is_some_and(|opts| opts.contains('J')) { + mapped_opts.push('J'); + } + + let stats = conduwuit::alloc::memory_stats(&mapped_opts).unwrap_or_default(); self.write_str("```\n").await?; self.write_str(&stats).await?; @@ -1207,6 +1212,46 @@ impl crate::Context<'_> { .await } + pub(super) async fn room_extremities(&self, room_id: OwnedRoomId) -> Result { + let mut extremities = self + .services + .rooms + .state + .get_forward_extremities(&room_id) + .broad_filter_map(|event_id| async move { + self.services.rooms.timeline.get_pdu(&event_id).await.ok() + }) + .collect::>() + .await; + extremities.sort_by_key(|pdu| (pdu.depth, pdu.origin_server_ts)); + if extremities.is_empty() { + return Err!("No room extremities."); + } + self.write_str("| Event ID | Kind | Sender | Timestamp | Depth |\n") + .await?; + self.write_str("| -------- | ---- | ------ | --------- | ----- |\n") + .await?; + for pdu in extremities { + let url = format!( + "https://matrix.to/#/{}/{}?via={}", + room_id, + pdu.event_id(), + self.services.server.name + ); + self.write_str(&format!( + "| [`{}`]({url}) | `{}` | `{}` | `{}` | `{}` |\n", + pdu.event_id(), + pdu.kind(), + pdu.sender(), + pdu.origin_server_ts, + pdu.depth + )) + .await?; + } + + Ok(()) + } + pub(super) async fn servers_in_backoff( &self, room_id: Option, diff --git a/src/admin/debug/mod.rs b/src/admin/debug/mod.rs index f544637ab..85a1c3a77 100644 --- a/src/admin/debug/mod.rs +++ b/src/admin/debug/mod.rs @@ -192,7 +192,8 @@ pub enum DebugCommand { /// /// Optional argument is a character mask (a sequence of characters in any /// order) which enable additional extended statistics. Known characters are - /// "abdeglmx". For convenience, a '*' will enable everything. + /// "abdeglmx" and 'J' for JSON output. For convenience, a '*' will enable + /// everything. MemoryStats { opts: Option, }, @@ -234,6 +235,10 @@ pub enum DebugCommand { page: Option, }, + RoomExtremities { + room_id: OwnedRoomId, + }, + /// Lists remote servers that are currently in a "backoff" state. /// /// Servers in this list will not be contacted until the retry time elapses, diff --git a/src/admin/federation/commands.rs b/src/admin/federation/commands.rs index 966c7bdcf..a4fbbabe0 100644 --- a/src/admin/federation/commands.rs +++ b/src/admin/federation/commands.rs @@ -142,11 +142,11 @@ impl crate::Context<'_> { .await?; self.write_str("| ------ | ---------- | --------------------------- |\n") .await?; - for (key_id, key) in &response.verify_keys { + for (key_id, key) in &response.parsed.verify_keys { self.write_str(&format!("| {key_id} | {} | |\n", key.key)) .await?; } - for (key_id, old_key) in &response.old_verify_keys { + for (key_id, old_key) in &response.parsed.old_verify_keys { self.write_str(&format!( "| {key_id} | {} | {:0<13} |\n", old_key.key, diff --git a/src/admin/mod.rs b/src/admin/mod.rs index fd73c3f15..eab68e4d0 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -2,6 +2,7 @@ #![allow(clippy::wildcard_imports)] #![allow(clippy::enum_glob_use)] #![allow(clippy::too_many_arguments)] +#![allow(clippy::large_unopt_stack_frames, reason = "very large Subcommand macro expansions")] conduwuit_macros::introspect_crate! {} @@ -33,23 +34,16 @@ pub(crate) use crate::{context::Context, utils::get_room_info}; pub(crate) const PAGE_SIZE: usize = 100; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - pub use crate::admin::AdminCommand; /// Install the admin command processor -pub async fn init(admin_service: &service::admin::Service) { +pub fn init(admin_service: &service::admin::Service) { _ = admin_service.complete.write().insert(processor::complete); - _ = admin_service - .handle - .write() - .await - .insert(processor::dispatch); + _ = admin_service.handle.write().insert(processor::dispatch); } /// Uninstall the admin command handler -pub async fn fini(admin_service: &service::admin::Service) { - _ = admin_service.handle.write().await.take(); +pub fn fini(admin_service: &service::admin::Service) { + _ = admin_service.handle.write().take(); _ = admin_service.complete.write().take(); } diff --git a/src/admin/query/appservice.rs b/src/admin/query/appservice.rs index e2f04acf3..45dec01e5 100644 --- a/src/admin/query/appservice.rs +++ b/src/admin/query/appservice.rs @@ -24,7 +24,7 @@ pub(super) async fn process(subcommand: AppserviceCommand, context: &Context<'_> match subcommand { | AppserviceCommand::GetRegistration { appservice_id } => { let timer = tokio::time::Instant::now(); - let results = services.appservice.get_registration(&appservice_id).await; + let results = services.appservice.get_registration(&appservice_id); let query_time = timer.elapsed(); diff --git a/src/admin/server/commands.rs b/src/admin/server/commands.rs index 1173c5457..51042f89b 100644 --- a/src/admin/server/commands.rs +++ b/src/admin/server/commands.rs @@ -110,14 +110,6 @@ impl crate::Context<'_> { self.write_str("Notice was sent to #admins").await } - pub(super) async fn reload_mods(&self) -> Result { - self.bail_restricted()?; - - self.services.server.reload()?; - - self.write_str("Reloading server...").await - } - #[cfg(unix)] pub(super) async fn restart(&self, force: bool) -> Result { use conduwuit::utils::sys::current_exe_deleted; diff --git a/src/admin/server/mod.rs b/src/admin/server/mod.rs index ff6933ef9..c9fb6d299 100644 --- a/src/admin/server/mod.rs +++ b/src/admin/server/mod.rs @@ -39,10 +39,6 @@ pub enum ServerCommand { message: Vec, }, - /// Hot-reload the server - #[command(name = "reload", alias = "reload-mods")] - ReloadMods, - #[cfg(unix)] /// Restart the server Restart { diff --git a/src/api/Cargo.toml b/src/api/Cargo.toml index 4385fbe7f..689902717 100644 --- a/src/api/Cargo.toml +++ b/src/api/Cargo.toml @@ -51,8 +51,6 @@ jemalloc_stats = [ release_max_log_level = [ "conduwuit-core/release_max_log_level", "conduwuit-service/release_max_log_level", - "log/max_level_trace", - "log/release_max_level_info", "tracing/max_level_trace", "tracing/release_max_level_info", ] @@ -80,7 +78,6 @@ http-body-util.workspace = true hyper.workspace = true itertools.workspace = true lettre.workspace = true -log.workspace = true rand.workspace = true reqwest.workspace = true ruma.workspace = true @@ -90,6 +87,7 @@ serde.workspace = true sha1.workspace = true tokio.workspace = true tracing.workspace = true +wildmatch.workspace = true [lints] workspace = true diff --git a/src/api/client/account/threepid.rs b/src/api/client/account/threepid.rs index 93531eb02..edcd9017d 100644 --- a/src/api/client/account/threepid.rs +++ b/src/api/client/account/threepid.rs @@ -135,7 +135,6 @@ pub(crate) async fn add_3pid_route( let email = services .threepid .get_valid_session(&body.sid, &body.client_secret) - .await .map_err(|message| err!(Request(ThreepidAuthFailed("{message}"))))? .consume(); diff --git a/src/api/client/account_data.rs b/src/api/client/account_data.rs index 60fec42ab..bc9dc4bab 100644 --- a/src/api/client/account_data.rs +++ b/src/api/client/account_data.rs @@ -117,10 +117,13 @@ async fn set_account_data( data: &RawJsonValue, ) -> Result { if event_type_s == "m.fully_read" { - return Err!(Request(BadJson( - "This endpoint cannot be used for marking a room as fully read (setting \ - m.fully_read)" - ))); + return Err!(Request( + BadJson( + "This endpoint cannot be used for marking a room as fully read (setting \ + m.fully_read)" + ), + METHOD_NOT_ALLOWED + )); } let data: serde_json::Value = serde_json::from_str(data.get()) diff --git a/src/api/client/alias.rs b/src/api/client/alias.rs index 5d4dec081..f10e03083 100644 --- a/src/api/client/alias.rs +++ b/src/api/client/alias.rs @@ -20,8 +20,7 @@ pub(crate) async fn create_alias_route( services .rooms .alias - .appservice_checks(&body.room_alias, body.identity.appservice_info()) - .await?; + .appservice_checks(&body.room_alias, body.identity.appservice_info())?; // this isn't apart of alias_checks or delete alias route because we should // allow removing forbidden room aliases @@ -69,8 +68,7 @@ pub(crate) async fn delete_alias_route( services .rooms .alias - .appservice_checks(&body.room_alias, body.identity.appservice_info()) - .await?; + .appservice_checks(&body.room_alias, body.identity.appservice_info())?; services .rooms diff --git a/src/api/client/capabilities.rs b/src/api/client/capabilities.rs index 28a5e0fc5..5851fb9bc 100644 --- a/src/api/client/capabilities.rs +++ b/src/api/client/capabilities.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use axum::extract::State; -use conduwuit::{Result, Server}; +use conduwuit::{Result, Server, config::experiments::ToggledExperiment}; use ruma::{ RoomVersionId, api::{ @@ -46,14 +46,18 @@ pub(crate) async fn get_capabilities_route( capabilities.get_login_token = GetLoginTokenCapability::new(services.server.config.login_via_existing_session); - capabilities.forget_forced_upon_leave.enabled = true; + capabilities.forget_forced_upon_leave.enabled = + services.server.config.forget_forced_upon_leave; if services.users.is_admin(sender_user).await { capabilities.account_moderation.lock = true; capabilities.account_moderation.suspend = true; - capabilities.admin = - AdminCapability::new(BTreeSet::from_iter([OAuthClientScope::ServerAdministration])); + if services.config.experiments.msc4484.is_enabled() { + capabilities.admin = AdminCapability::new(BTreeSet::from_iter([ + OAuthClientScope::ServerAdministration, + ])); + } } capabilities.profile_fields = Some( @@ -62,7 +66,10 @@ pub(crate) async fn get_capabilities_route( capabilities.set( "org.matrix.msc4174.webpush", - json!({ "enabled": true, "vapid": services.pusher.webpush_vapid_public_key() }), + json!({ + "enabled": services.config.experiments.msc4174.is_enabled(), + "vapid": services.pusher.webpush_vapid_public_key() + }), )?; Ok(get_capabilities::v3::Response::new(capabilities)) diff --git a/src/api/client/dehydrated_device.rs b/src/api/client/dehydrated_device.rs index 72ae2b955..124b90f19 100644 --- a/src/api/client/dehydrated_device.rs +++ b/src/api/client/dehydrated_device.rs @@ -3,10 +3,10 @@ use conduwuit::{Err, Result, at}; use futures::StreamExt; use ruma::{ api::client::dehydrated_device::{ - delete_dehydrated_device::unstable as delete_dehydrated_device, - get_dehydrated_device::unstable as get_dehydrated_device, - get_events::unstable as get_events, - put_dehydrated_device::unstable as put_dehydrated_device, + delete_dehydrated_device::msc3814 as delete_dehydrated_device, + get_dehydrated_device::msc3814 as get_dehydrated_device, + get_events::msc3814 as get_events, + put_dehydrated_device::msc3814 as put_dehydrated_device, }, assign, }; diff --git a/src/api/client/keys.rs b/src/api/client/keys.rs index c9a002804..271e6b836 100644 --- a/src/api/client/keys.rs +++ b/src/api/client/keys.rs @@ -15,8 +15,7 @@ use ruma::{ OneTimeKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId, api::{ client::keys::{ - claim_keys, get_key_changes, get_keys, upload_keys, - upload_signatures::{self}, + claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures, upload_signing_keys, }, federation, @@ -523,7 +522,22 @@ where for (server, response) in futures { match response { | Ok(response) => { - for (user, master_key) in response.master_keys { + let is_wanted = |user_id: &UserId| { + user_id.server_name() == server && device_keys_input.contains_key(user_id) + }; + let filtered_master_keys = response + .master_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + let filtered_self_signing_keys = response + .self_signing_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + let filtered_device_keys = response + .device_keys + .into_iter() + .filter(|(user_id, _)| is_wanted(user_id)); + for (user, master_key) in filtered_master_keys { let (master_key_id, mut master_key) = parse_master_key(&user, &master_key)?; if let Ok(our_master_key) = services @@ -549,8 +563,8 @@ where } } - self_signing_keys.extend(response.self_signing_keys); - device_keys.extend(response.device_keys); + self_signing_keys.extend(filtered_self_signing_keys); + device_keys.extend(filtered_device_keys); }, | Err(e) => { failures.insert(server.to_string(), json!({ "error": e.to_string() })); diff --git a/src/api/client/media.rs b/src/api/client/media.rs index 824d98541..a078bb968 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -2,7 +2,7 @@ use std::time::Duration; use axum::extract::State; use conduwuit::{ - Err, Result, err, + Err, Result, debug, err, utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize}, }; use conduwuit_core::error; @@ -30,9 +30,9 @@ pub(crate) async fn get_media_config_route( State(services): State, _body: Ruma, ) -> Result { - Ok(get_media_config::v1::Response::new(ruma_from_usize( + Ok(get_media_config::v1::Response::new(Some(ruma_from_usize( services.server.config.max_request_size, - ))) + )))) } /// # `POST /_matrix/media/v3/upload` @@ -219,10 +219,12 @@ pub(crate) async fn get_media_preview_route( ))); } + debug!("Fetching a URL preview for {url} on behalf of {sender_user}"); let preview = services .media .get_url_preview(&url) .await + .inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview")) .map_err(|error| { err!(Request(Unknown( debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}") diff --git a/src/api/client/media_legacy.rs b/src/api/client/media_legacy.rs deleted file mode 100644 index ddc7e9c92..000000000 --- a/src/api/client/media_legacy.rs +++ /dev/null @@ -1,398 +0,0 @@ -#![allow(deprecated)] - -use axum::extract::State; -use conduwuit::{ - Err, Result, err, - utils::{content_disposition::make_content_disposition, math::ruma_from_usize}, -}; -use conduwuit_service::media::{CORP_CROSS_ORIGIN, Dim, FileMeta}; -use reqwest::Url; -use ruma::{ - api::client::media::{ - create_content, get_content, get_content_as_filename, get_content_thumbnail, - get_media_config, get_media_preview, - }, - assign, -}; -use service::media::mxc::Mxc; - -use crate::{Ruma, RumaResponse, client::create_content_route}; - -/// # `GET /_matrix/media/v3/config` -/// -/// Returns max upload size. -pub(crate) async fn get_media_config_legacy_route( - State(services): State, - _body: Ruma, -) -> Result { - Ok(get_media_config::v3::Response::new(ruma_from_usize( - services.server.config.max_request_size, - ))) -} - -/// # `GET /_matrix/media/v1/config` -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// Returns max upload size. -pub(crate) async fn get_media_config_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_media_config_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/preview_url` -/// -/// Returns URL preview. -pub(crate) async fn get_media_preview_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let sender_user = body.identity.expect_sender_user()?; - - let url = &body.url; - let url = Url::parse(&body.url).map_err(|e| { - err!(Request(InvalidParam( - debug_warn!(%sender_user, %url, "Requested URL is not valid: {e}") - ))) - })?; - - if !services.media.url_preview_allowed(&url) { - return Err!(Request(Forbidden( - debug_warn!(%sender_user, %url, "URL is not allowed to be previewed") - ))); - } - - let preview = services.media.get_url_preview(&url).await.map_err(|e| { - err!(Request(Unknown( - debug_error!(%sender_user, %url, "Failed to fetch a URL preview: {e}") - ))) - })?; - - serde_json::value::to_raw_value(&preview) - .map(get_media_preview::v3::Response::from_raw_value) - .map_err(|error| { - err!(Request(Unknown( - debug_error!(%sender_user, %url, "Failed to parse URL preview: {error}") - ))) - }) -} - -/// # `GET /_matrix/media/v1/preview_url` -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// Returns URL preview. -pub(crate) async fn get_media_preview_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_media_preview_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `POST /_matrix/media/v1/upload` -/// -/// Permanently save media in the server. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Some metadata will be saved in the database -/// - Media will be saved in the media/ directory -pub(crate) async fn create_content_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - create_content_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}` -/// -/// Load media from our server or over federation. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - match services.media.get(&mxc).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}` -/// -/// Load media from our server or over federation. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}` -/// -/// Load media from our server or over federation, permitting desired filename. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_as_filename_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - match services.media.get(&mxc).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - Some(&body.filename), - ); - - Ok(assign!(get_content_as_filename::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_content_legacy(&mxc, body.allow_redirect, body.timeout_ms) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_as_filename::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.into()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}` -/// -/// Load media from our server or over federation, permitting desired filename. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_as_filename_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_as_filename_legacy_route(State(services), body) - .await - .map(RumaResponse) -} - -/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}` -/// -/// Load media thumbnail from our server or over federation. -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_thumbnail_legacy_route( - State(services): State, - body: Ruma, -) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; - match services.media.get_thumbnail(&mxc, &dim).await? { - | Some(FileMeta { - content, - content_type, - content_disposition, - }) => { - let content_disposition = make_content_disposition( - content_disposition.as_ref(), - content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_thumbnail::v3::Response::new( - content.expect("entire file contents"), - content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), - } - )) - }, - | _ => - if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { - let response = services - .media - .fetch_remote_thumbnail_legacy(&body) - .await - .map_err(|e| { - err!(Request(NotFound(debug_warn!(%mxc, "Fetching media failed: {e:?}")))) - })?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - Ok(assign!( - get_content_thumbnail::v3::Response::new( - response.file, - response.content_type.unwrap_or_default(), - content_disposition, - ), - { - cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), - } - )) - } else { - Err!(Request(NotFound("Media not found."))) - }, - } -} - -/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}` -/// -/// Load media thumbnail from our server or over federation. -/// -/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or -/// clients may call. conduwuit adds these for compatibility purposes. -/// See -/// -/// - Only allows federation if `allow_remote` is true -/// - Only redirects if `allow_redirect` is true -/// - Uses client-provided `timeout_ms` if available, else defaults to 20 -/// seconds -pub(crate) async fn get_content_thumbnail_legacy_legacy_route( - State(services): State, - body: Ruma, -) -> Result> { - get_content_thumbnail_legacy_route(State(services), body) - .await - .map(RumaResponse) -} diff --git a/src/api/client/membership/knock.rs b/src/api/client/membership/knock.rs index f24ede158..d7ef2458a 100644 --- a/src/api/client/membership/knock.rs +++ b/src/api/client/membership/knock.rs @@ -1,4 +1,4 @@ -use std::{borrow::Borrow, collections::HashMap, iter::once, sync::Arc}; +use std::{borrow::Borrow, collections::HashMap, sync::Arc}; use axum::extract::State; use conduwuit::{ @@ -16,10 +16,7 @@ use futures::{FutureExt, StreamExt}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, UserId, - api::{ - client::knock::knock_room, - federation::{self}, - }, + api::{client::knock::knock_room, federation}, canonical_json::to_canonical_value, events::{ StateEventType, @@ -461,14 +458,13 @@ async fn knock_room_helper_local( services .rooms .timeline - .append_pdu( - &parsed_knock_pdu, - knock_event, - once(parsed_knock_pdu.event_id.borrow()), - &state_lock, - room_id, - ) + .progress_extremities(&parsed_knock_pdu) .await?; + services + .rooms + .timeline + .append_pdu(&parsed_knock_pdu, knock_event, room_id) + .await; Ok(()) } @@ -587,7 +583,7 @@ async fn knock_room_helper_remote( let mut state_map: HashMap = HashMap::new(); - for event in state { + for mut event in state { let Some(state_key) = event.get("state_key") else { debug_warn!("send_knock stripped state event missing state_key: {event:?}"); continue; @@ -614,6 +610,7 @@ async fn knock_room_helper_remote( .get_or_create_shortstatekey(&event_type, &state_key) .await; + event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string())); services.rooms.outlier.add_pdu_outlier(&event_id, &event); state_map.insert(shortstatekey, event_id.clone()); } @@ -662,14 +659,13 @@ async fn knock_room_helper_remote( services .rooms .timeline - .append_pdu( - &parsed_knock_pdu, - knock_event, - once(parsed_knock_pdu.event_id.borrow()), - &state_lock, - room_id, - ) + .progress_extremities(&parsed_knock_pdu) .await?; + services + .rooms + .timeline + .append_pdu(&parsed_knock_pdu, knock_event, room_id) + .await; info!("Setting final room state for new room"); // We set the room state after inserting the pdu, so that we never have a diff --git a/src/api/client/membership/leave.rs b/src/api/client/membership/leave.rs index 1ef0b21fa..a10aff0f9 100644 --- a/src/api/client/membership/leave.rs +++ b/src/api/client/membership/leave.rs @@ -10,10 +10,7 @@ use conduwuit::{ use futures::{FutureExt, StreamExt, pin_mut}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedServerName, RoomId, UserId, - api::{ - client::membership::leave_room, - federation::{self}, - }, + api::{client::membership::leave_room, federation}, events::{ StateEventType, room::member::{MembershipState, RoomMemberEventContent}, diff --git a/src/api/client/membership/members.rs b/src/api/client/membership/members.rs index 5c8d00829..e2695bd3a 100644 --- a/src/api/client/membership/members.rs +++ b/src/api/client/membership/members.rs @@ -9,7 +9,7 @@ use conduwuit::{ use futures::{FutureExt, StreamExt, future::join}; use ruma::{ api::client::membership::{ - get_member_events::{self}, + get_member_events, joined_members::{self, v3::RoomMember}, }, events::{ diff --git a/src/api/client/message.rs b/src/api/client/message.rs index 72b1b29e5..2bb3cbbc0 100644 --- a/src/api/client/message.rs +++ b/src/api/client/message.rs @@ -1,6 +1,8 @@ use axum::extract::State; use conduwuit::{ - Err, Error, Result, at, debug_warn, + Err, Error, Result, at, + config::experiments::ToggledExperiment, + debug_warn, matrix::{ event::{Event, Matches}, pdu::PduCount, @@ -22,7 +24,7 @@ use conduwuit_service::{ }; use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut}; use ruma::{ - RoomId, UserId, + EventId, RoomId, UserId, api::{ Direction, client::{filter::RoomEventFilter, message::get_message_events}, @@ -30,8 +32,9 @@ use ruma::{ }, assign, events::{ - AnyStateEvent, StateEventType, + AnyStateEvent, StateEventType, SyncEphemeralRoomEvent, TimelineEventType::{self, *}, + receipt::ReceiptEventContent, }, serde::Raw, }; @@ -209,36 +212,32 @@ pub(crate) async fn lazy_loading_witness<'a, I>( where I: Iterator + Clone + Send, { - let oldest = events - .clone() - .map(|(count, _)| count) - .copied() - .min() - .unwrap_or_else(PduCount::max); - - let newest = events - .clone() - .map(|(count, _)| count) - .copied() - .max() - .unwrap_or_else(PduCount::max); + let chunk_event_ids: std::collections::HashSet<&EventId> = + events.clone().map(|(_, event)| event.event_id()).collect(); let receipts = services .rooms .read_receipt - .readreceipts_since(lazy_loading_context.room_id, Some(oldest.into_unsigned())); + .readreceipts_since(lazy_loading_context.room_id, None); pin_mut!(receipts); + let receipt_users = receipts.ready_filter_map(|(user_id, _, raw)| { + let event = + serde_json::from_str::>(raw.json().get()) + .ok()?; + event + .content + .keys() + .any(|id| chunk_event_ids.contains(&**id)) + .then_some(user_id) + }); + let witness: MemberSet = events .stream() .map(ref_at!(1)) .map(Event::sender) .map(ToOwned::to_owned) - .chain( - receipts - .ready_take_while(|(_, c, _)| *c <= newest.into_unsigned()) - .map(|(user_id, ..)| user_id), - ) + .chain(receipt_users) .collect() .await; @@ -318,21 +317,29 @@ where if server_ignored { // the sender's server is ignored, so ignore this event - return Err(Error::BadRequest( - ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()), - "The sender's server is ignored by this server.", - )); + return if services.config.experiments.msc4406.is_enabled() { + Err(Error::BadRequest( + ErrorKind::SenderIgnored(SenderIgnoredErrorData::new()), + "The sender's server is ignored by this server.", + )) + } else { + Err!(Request(NotFound("This event's sender's homeserver is ignored by this server."))) + }; } if user_ignored && !services.config.send_messages_from_ignored_users_to_client { // the recipient of this PDU has the sender ignored, and we're not // configured to send ignored messages to clients - return Err(Error::BadRequest( - ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender( - event.sender().to_owned(), - )), - "You have ignored this sender.", - )); + return if services.config.experiments.msc4406.is_enabled() { + Err(Error::BadRequest( + ErrorKind::SenderIgnored(SenderIgnoredErrorData::with_sender( + event.sender().to_owned(), + )), + "You have ignored this sender.", + )) + } else { + Err!(Request(NotFound("You have ignored the sender of this event."))) + }; } Ok(false) diff --git a/src/api/client/mod.rs b/src/api/client/mod.rs index c0bb2dc98..fa372a67c 100644 --- a/src/api/client/mod.rs +++ b/src/api/client/mod.rs @@ -12,7 +12,6 @@ pub(super) mod directory; pub(super) mod filter; pub(super) mod keys; pub(super) mod media; -pub(super) mod media_legacy; pub(super) mod membership; pub(super) mod message; pub(super) mod mutual_rooms; @@ -24,6 +23,7 @@ pub(super) mod push; pub(super) mod read_marker; pub(super) mod redact; pub(super) mod relations; +pub(super) mod rendezvous; pub(super) mod report; pub(super) mod room; pub(super) mod search; @@ -57,7 +57,6 @@ pub(super) use directory::*; pub(super) use filter::*; pub(super) use keys::*; pub(super) use media::*; -pub(super) use media_legacy::*; pub(super) use membership::*; pub use membership::{leave_all_rooms, leave_room, remote_leave_room}; pub(super) use message::*; @@ -71,6 +70,7 @@ pub(super) use push::*; pub(super) use read_marker::*; pub(super) use redact::*; pub(super) use relations::*; +pub(super) use rendezvous::*; pub(super) use report::*; pub(super) use room::*; pub(super) use search::*; diff --git a/src/api/client/mutual_rooms.rs b/src/api/client/mutual_rooms.rs index 532a5cc79..265238545 100644 --- a/src/api/client/mutual_rooms.rs +++ b/src/api/client/mutual_rooms.rs @@ -13,8 +13,8 @@ use crate::Ruma; #[tracing::instrument(skip_all, name = "mutual_rooms", level = "info")] pub(crate) async fn get_mutual_rooms_unstable_route( State(services): State, - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { let sender_user = body.identity.expect_sender_user()?; if sender_user == body.user_id { @@ -28,7 +28,7 @@ pub(crate) async fn get_mutual_rooms_unstable_route( .collect() .await; - Ok(get_mutual_rooms::unstable::Response::new(mutual_rooms)) + Ok(get_mutual_rooms::msc2666::Response::new(mutual_rooms)) } /// # `GET /_matrix/client/v1/mutual_rooms` diff --git a/src/api/client/read_marker.rs b/src/api/client/read_marker.rs index 2f8b21a39..aeacd9adc 100644 --- a/src/api/client/read_marker.rs +++ b/src/api/client/read_marker.rs @@ -1,14 +1,14 @@ use std::collections::BTreeMap; use axum::extract::State; -use conduwuit::{Err, PduCount, Result, err}; +use conduwuit::{Err, Result, err}; use ruma::{ MilliSecondsSinceUnixEpoch, api::client::{read_marker::set_read_marker, receipt::create_receipt}, events::{ RoomAccountDataEventType, fully_read::{FullyReadEvent, FullyReadEventContent}, - receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptType}, + receipt::{Receipt, ReceiptEvent, ReceiptEventContent, ReceiptThread, ReceiptType}, }, }; @@ -27,6 +27,15 @@ pub(crate) async fn set_read_marker_route( ) -> Result { let sender_user = body.identity.expect_sender_user()?; + if !services + .rooms + .state_cache + .is_joined(sender_user, &body.room_id) + .await + { + return Err!(Request(Forbidden("You are not in this room."))); + } + if let Some(event) = &body.fully_read { let fully_read_event = FullyReadEvent::new(FullyReadEventContent::new(event.to_owned())); @@ -92,13 +101,8 @@ pub(crate) async fn set_read_marker_route( .timeline .get_pdu_count(event) .await - .map_err(|_| err!(Request(NotFound("Event not found."))))?; - - let PduCount::Normal(count) = count else { - return Err!(Request(InvalidParam( - "Event is a backfilled PDU and cannot be marked as read." - ))); - }; + .map_err(|_| err!(Request(NotFound("Event not found."))))? + .into_unsigned(); services .rooms @@ -122,11 +126,26 @@ pub(crate) async fn create_receipt_route( ) -> Result { let sender_user = body.identity.expect_sender_user()?; + if !services + .rooms + .state_cache + .is_joined(sender_user, &body.room_id) + .await + { + return Err!(Request(Forbidden("You are not in this room."))); + } + services .users .update_device_last_seen(sender_user, body.identity.sender_device(), client_ip) .await; + if body.receipt_type == create_receipt::v3::ReceiptType::FullyRead + && body.thread != ReceiptThread::Unthreaded + { + return Err!(Request(InvalidParam("thread_id cannot be specified for m.fully_read"))); + } + if matches!( &body.receipt_type, create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate @@ -159,44 +178,41 @@ pub(crate) async fn create_receipt_route( ) .await?; }, - | create_receipt::v3::ReceiptType::Read => { - let receipt_content = [( - body.event_id.clone(), - BTreeMap::from_iter([( - ReceiptType::Read, + | create_receipt::v3::ReceiptType::Read => + if services.config.allow_local_read_receipts + && !services.users.is_suspended(sender_user).await? + { + let mut receipt = Receipt::new(MilliSecondsSinceUnixEpoch::now()); + receipt.thread = body.thread.clone(); + let receipt_content = [( + body.event_id.clone(), BTreeMap::from_iter([( - sender_user.to_owned(), - Receipt::new(MilliSecondsSinceUnixEpoch::now()), + ReceiptType::Read, + BTreeMap::from_iter([(sender_user.to_owned(), receipt)]), )]), - )]), - )]; + )]; - services - .rooms - .read_receipt - .readreceipt_update( - sender_user, - &body.room_id, - ReceiptEvent::new( - body.room_id.clone(), - ReceiptEventContent::from_iter(receipt_content), - ), - ) - .await; - }, + services + .rooms + .read_receipt + .readreceipt_update( + sender_user, + &body.room_id, + ReceiptEvent::new( + body.room_id.clone(), + ReceiptEventContent::from_iter(receipt_content), + ), + ) + .await; + }, | create_receipt::v3::ReceiptType::ReadPrivate => { let count = services .rooms .timeline .get_pdu_count(&body.event_id) .await - .map_err(|_| err!(Request(NotFound("Event not found."))))?; - - let PduCount::Normal(count) = count else { - return Err!(Request(InvalidParam( - "Event is a backfilled PDU and cannot be marked as read." - ))); - }; + .map_err(|_| err!(Request(NotFound("Event not found."))))? + .into_unsigned(); services .rooms diff --git a/src/api/client/relations.rs b/src/api/client/relations.rs index 6d1bd4ffd..1ef92898c 100644 --- a/src/api/client/relations.rs +++ b/src/api/client/relations.rs @@ -2,7 +2,7 @@ use axum::extract::State; use conduwuit::{ Err, Result, at, debug_warn, err, matrix::{Event, event::RelationTypeEqual, pdu::PduCount}, - utils::{IterStream, ReadyExt, result::FlatOk, stream::WidebandExt}, + utils::{IterStream, result::FlatOk, stream::WidebandExt}, }; use conduwuit_service::Services; use futures::StreamExt; @@ -98,6 +98,10 @@ pub(crate) async fn get_relating_events_route( .await } +// Spec (v1.10) recommends a depth of at least 3 +const RECURSION_DEPTH: u8 = 3; +const LEVELS_BELOW: u8 = RECURSION_DEPTH - 1; + #[allow(clippy::too_many_arguments)] async fn paginate_relations_with_filter( services: &Services, @@ -147,28 +151,49 @@ async fn paginate_relations_with_filter( .unwrap_or(30) .min(100); - // Spec (v1.10) recommends depth of at least 3 - let depth: u8 = if recurse { 3 } else { 1 }; + let max_depth = if recurse { LEVELS_BELOW } else { 0 }; - let events: Vec<_> = services + // One more than the limit, to know whether there's another page + let mut events = services .rooms .pdu_metadata - .get_relations(sender_user, room_id, target, start, limit, depth, dir) - .await + .get_relations( + sender_user, + room_id, + target, + start, + limit.saturating_add(1), + max_depth, + dir, + |pdu| { + filter_event_type + .as_ref() + .is_none_or(|kind| kind == pdu.kind()) + && filter_rel_type + .as_ref() + .is_none_or(|rel_type| rel_type.relation_type_equal(pdu)) + }, + ) + .await; + + let past_to = to.and_then(|to| { + events + .iter() + .position(|(count, _)| !to.is_after(*count, dir)) + }); + if let Some(past_to) = past_to { + events.truncate(past_to); + } + + let has_more = past_to.is_none() && events.len() > limit; + events.truncate(limit); + + let next_batch = + has_more.then(|| events.last().map_or(start, |(count, _)| *count).to_string()); + + let chunk: Vec<_> = events .into_iter() - .filter(|(_, pdu)| { - filter_event_type - .as_ref() - .is_none_or(|kind| kind == pdu.kind()) - }) - .filter(|(_, pdu)| { - filter_rel_type - .as_ref() - .is_none_or(|rel_type| rel_type.relation_type_equal(pdu)) - }) .stream() - .ready_take_while(|(count, _)| Some(*count) != to) - .take(limit) .wide_filter_map(|item| visibility_filter(services, sender_user, item)) .wide_filter_map(|item| ignored_filter(services, item, sender_user)) .then(async |mut pdu| { @@ -182,32 +207,15 @@ async fn paginate_relations_with_filter( } pdu }) - .collect() - .await; - - // Determine if there are more events to fetch - let has_more = events.len() >= limit; - - let next_batch = if has_more { - match dir { - | Direction::Forward => events.last(), - | Direction::Backward => events.first(), - } - .map(|(count, _)| count.to_string()) - } else { - None - }; - - let chunk: Vec<_> = events - .into_iter() .map(at!(1)) .map(Event::into_format) - .collect(); + .collect() + .await; Ok(assign!(get_relating_events::v1::Response::new(chunk), { next_batch, prev_batch: from.map(Into::into), - recursion_depth: recurse.then_some(depth.into()), + recursion_depth: recurse.then_some(RECURSION_DEPTH.into()), })) } diff --git a/src/api/client/rendezvous.rs b/src/api/client/rendezvous.rs new file mode 100644 index 000000000..d779b74a3 --- /dev/null +++ b/src/api/client/rendezvous.rs @@ -0,0 +1,76 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use http::HeaderMap; +use ruma::api::client::rendezvous::{ + create_rendezvous_session, delete_rendezvous_session, discover_rendezvous, + get_rendezvous_session, update_rendezvous_session, +}; +use service::Services; + +use crate::{Ruma, router::ClientIdentity}; + +/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous` +pub(crate) async fn discover_rendezvous_route( + State(services): State, + body: Ruma, +) -> Result { + Ok(discover_rendezvous::msc4388::Response::new(rendezvous_available( + &services, + body.identity.as_ref(), + ))) +} + +/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/` +pub(crate) async fn create_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + if !rendezvous_available(&services, body.identity.as_ref()) { + return Err!(Request(Forbidden("You are not authorized to create a rendezvous session"))); + } + + services.rendezvous.create_session(body.data.clone()) +} + +/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}` +pub(crate) async fn update_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + services.rendezvous.update_session( + &body.id, + body.txn_id.clone(), + body.sequence_token.clone(), + body.data.clone(), + ) +} + +/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}` +pub(crate) async fn get_rendezvous_session_route( + State(services): State, + headers: HeaderMap, + body: Ruma, +) -> Result { + if let Some(mode) = headers.get("Sec-Fetch-Mode") + && let Ok(mode) = mode.to_str() + && mode == "navigate" + { + return Err!(Request(Forbidden( + "Rendezvous sessions do not accept browser navigation requests." + ))); + } + + services.rendezvous.get_session(&body.id) +} + +/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}` +pub(crate) async fn delete_rendezvous_session_route( + State(services): State, + body: Ruma, +) -> Result { + services.rendezvous.delete_session(&body.id) +} + +fn rendezvous_available(services: &Services, identity: Option<&ClientIdentity>) -> bool { + !services.config.require_auth_for_rendezvous || identity.is_some() +} diff --git a/src/api/client/room/create.rs b/src/api/client/room/create.rs index 582169346..74f0653db 100644 --- a/src/api/client/room/create.rs +++ b/src/api/client/room/create.rs @@ -1,18 +1,21 @@ -use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::{ + collections::{BTreeMap, BTreeSet, HashSet}, + sync::atomic::{AtomicU64, Ordering::SeqCst}, +}; use axum::extract::State; use conduwuit::{ Err, Error, Result, debug, debug_info, err, info, matrix::{StateKey, pdu::PartialPdu}, trace, - utils::to_canonical_object, + utils::{self, to_canonical_object}, warn, }; use conduwuit_service::{Services, appservice::RegistrationInfo}; use futures::FutureExt; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, Int, MilliSecondsSinceUnixEpoch, OwnedRoomAliasId, - OwnedUserId, RoomAliasId, RoomId, + OwnedUserId, RoomAliasId, RoomId, UInt, api::{ client::room::{ self, @@ -46,6 +49,8 @@ use serde_json::value::to_raw_value; use crate::{Ruma, client::invite_helper}; +static LAST_CREATE_TS: AtomicU64 = AtomicU64::new(0); + // We use this to keep around extra data in the `creation_content` // while still parsing and validating keys that we care about. #[derive(Deserialize, Default)] @@ -72,7 +77,7 @@ struct FullCreationContent { /// - Send events listed in initial state /// - Send events implied by `name` and `topic` /// - Send invite events -#[allow(clippy::large_stack_frames)] +#[allow(clippy::large_unopt_stack_frames)] #[allow(clippy::cognitive_complexity)] pub(crate) async fn create_room_route( State(services): State, @@ -116,7 +121,10 @@ pub(crate) async fn create_room_route( // ID exactly matches this, and abort if it doesn't. Otherwise, we use it // as the room ID itself. let expect_room_id = { - let body_ref = body.json_body.as_ref().unwrap(); + let body_ref = body + .json_body + .as_ref() + .ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?; if let Some(CanonicalJsonValue::String(room_id)) = body_ref .get("fi.mau.room_id") .or_else(|| body_ref.get("room_id")) @@ -297,7 +305,10 @@ pub(crate) async fn create_room_route( // Allow requesters to override the `origin_server_ts` to customize room ids // from v12 onwards let custom_origin_server_ts = { - let body_ref = body.json_body.as_ref().unwrap(); + let body_ref = body + .json_body + .as_ref() + .ok_or_else(|| err!(Request(BadJson("Invalid JSON body"))))?; body_ref .get("origin_server_ts") .or_else(|| body_ref.get("fi.mau.origin_server_ts")) @@ -307,6 +318,17 @@ pub(crate) async fn create_room_route( .map(MilliSecondsSinceUnixEpoch) }; + // v12+ room IDs are the create event's hash, so give each create event a + // unique timestamp to avoid collisions. + let create_timestamp = custom_origin_server_ts.or_else(|| { + room_id.is_none().then(|| { + let now = utils::millis_since_unix_epoch(); + let next = |last: u64| now.max(last.saturating_add(1)); + let prev = LAST_CREATE_TS.update(SeqCst, SeqCst, next); + MilliSecondsSinceUnixEpoch(UInt::new_saturating(next(prev))) + }) + }); + let mut create_event_content = to_canonical_object(create_event_content) .expect("should be able to serialize create event content"); @@ -322,7 +344,7 @@ pub(crate) async fn create_room_route( event_type: TimelineEventType::RoomCreate, content: to_raw_value(&create_event_content)?, state_key: Some(StateKey::new()), - timestamp: custom_origin_server_ts, + timestamp: create_timestamp, ..Default::default() }, sender_user, @@ -758,11 +780,7 @@ async fn room_alias_check( if !info.aliases.is_match(full_room_alias.as_str()) { return Err!(Request(Exclusive("Room alias is not in namespace."))); } - } else if services - .appservice - .is_exclusive_alias(&full_room_alias) - .await - { + } else if services.appservice.is_exclusive_alias(&full_room_alias) { return Err!(Request(Exclusive("Room alias reserved by appservice.",))); } diff --git a/src/api/client/room/event.rs b/src/api/client/room/event.rs index 268ca92c1..d4917f73a 100644 --- a/src/api/client/room/event.rs +++ b/src/api/client/room/event.rs @@ -1,14 +1,30 @@ -use axum::extract::State; -use conduwuit::{Err, Event, Result, debug_warn, err}; -use ruma::api::client::room::get_room_event; +use axum::extract::{Query, State}; +use conduwuit::{ + Err, Error, Event, PduEvent, Result, config::experiments::ToggledExperiment, debug_warn, err, +}; +use futures::TryFutureExt; +use http::StatusCode; +use ruma::{ + UserId, + api::{client::room::get_room_event, error::ErrorKind}, +}; +use serde::Deserialize; +use serde_json::json; use crate::{Ruma, client::is_ignored_pdu}; +#[derive(Deserialize)] +pub(crate) struct Msc2815Params { + #[serde(rename = "fi.mau.msc2815.include_unredacted_content", default)] + include_unredacted_content: Option, +} + /// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}` /// /// Gets a single event. pub(crate) async fn get_room_event_route( State(ref services): State, + Query(params): Query, ref body: Ruma, ) -> Result { let sender_user = body.identity.expect_sender_user()?; @@ -24,7 +40,7 @@ pub(crate) async fn get_room_event_route( services.rooms.state_accessor.is_world_readable(room_id) ); if !joined && !world_readable { - return Err!(Request(NotFound("Event {} not found.", event_id))); + return Err!(Request(NotFound("Event {event_id} not found."))); } services @@ -32,10 +48,15 @@ pub(crate) async fn get_room_event_route( .timeline .get_remote_pdu(room_id, event_id) .await - .map_err(|_| err!(Request(NotFound("Event {} not found.", event_id))))? + .map_err(|_| err!(Request(NotFound("Event {event_id} not found."))))? }, | Err(e) => return Err(e), }; + if !event.room_id_or_hash().eq(room_id) { + // Return not found instead of invalid param to avoid revealing the + // existence of events the user might not be allowed to know about. + return Err!(Request(NotFound("Event {event_id} not found."))); + } // NOTE: checked after fetching, as visibility of an unknown event cannot // be determined (user_can_see_event returns true for those). @@ -49,6 +70,13 @@ pub(crate) async fn get_room_event_route( return Err!(Request(Forbidden("You don't have permission to view this event."))); } + if services.config.experiments.msc2815.is_enabled() + && params.include_unredacted_content.unwrap_or(false) + && event.is_redacted() + { + unredact(services, sender_user, &mut event).await?; + } + if let Err(e) = services .rooms .pdu_metadata @@ -67,3 +95,59 @@ pub(crate) async fn get_room_event_route( Ok(get_room_event::v3::Response::new(event.into_format())) } + +async fn unredact(services: &crate::State, sender_user: &UserId, event: &mut PduEvent) -> Result { + if !services.users.is_admin(sender_user).await { + let power_levels = services + .rooms + .state_accessor + .get_room_power_levels(&event.room_id_or_hash()) + .await; + + if power_levels.for_user(sender_user) < power_levels.redact { + return Err!(Request(Forbidden( + "You don't have permission to view redacted content in this room." + ))); + } + } + + let content = services + .rooms + .timeline + .get_pdu_id(event.event_id()) + .and_then(async |pdu_id| { + services + .rooms + .timeline + .get_unredacted_content(&pdu_id) + .await + }) + .await; + + let Ok(content) = content else { + // CustomErrorKind has private fields; only serde can build one. + let keep_ms = services + .config + .experiments + .msc2815 + .expect("msc2815 config is disabled but unredact() attempted to access it anyway") + .unredacted_content_max_age_secs + .saturating_mul(1000); + + let kind = serde_json::from_value::(json!({ + "errcode": "FI.MAU.MSC2815_UNREDACTED_CONTENT_DELETED", + "fi.mau.msc2815.content_keep_ms": keep_ms, + })) + .expect("errcode is a valid custom error kind"); + + return Err(Error::Request( + kind, + "The unredacted content of this event is not available.".into(), + StatusCode::NOT_FOUND, + )); + }; + + event.content = content; + + Ok(()) +} diff --git a/src/api/client/room/initial_sync.rs b/src/api/client/room/initial_sync.rs index 9ae8dd73f..70b50f961 100644 --- a/src/api/client/room/initial_sync.rs +++ b/src/api/client/room/initial_sync.rs @@ -94,8 +94,7 @@ pub(crate) async fn room_initial_sync_route( .first() .map(at!(0)) .as_ref() - .map(ToString::to_string) - .unwrap_or_default(); + .map_or_default(ToString::to_string); let start = events.last().map(at!(0)).as_ref().map(ToString::to_string); let chunk = events diff --git a/src/api/client/room/mod.rs b/src/api/client/room/mod.rs index e249e18b6..78487f8da 100644 --- a/src/api/client/room/mod.rs +++ b/src/api/client/room/mod.rs @@ -2,11 +2,14 @@ mod aliases; mod create; mod event; mod initial_sync; +mod stripped_state; mod summary; +mod timestamp_to_event; mod upgrade; pub(crate) use self::{ aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route, - initial_sync::room_initial_sync_route, summary::get_room_summary, + initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route, + summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route, upgrade::upgrade_room_route, }; diff --git a/src/api/client/room/stripped_state.rs b/src/api/client/room/stripped_state.rs new file mode 100644 index 000000000..cf686ef2f --- /dev/null +++ b/src/api/client/room/stripped_state.rs @@ -0,0 +1,71 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use ruma::{ + api::client::state::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS, +}; +use service::rooms::summary::{Accessibility, RoomStrippedState}; + +use crate::{Ruma, router::ClientIdentity}; + +/// # `POST /_matrix/client/unstable/org.continuwuity.msc4560.stripped_state/{room_id_or_alias}` ([MSC4560]) +/// +/// Returns a room's stripped state. +/// +/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +#[tracing::instrument(skip_all, name = "stripped_state", level = "info")] +pub(crate) async fn get_stripped_state_route( + State(services): State, + body: Ruma, +) -> Result { + let user_id = body.identity.as_ref().and_then(ClientIdentity::sender_user); + + if body.via.len() > get_stripped_state::msc4560::MAX_VIAS { + return Err!(Request(TooLarge("Too many vias, please be less indecisive."))); + } + + if let Some(forbidden_type) = body + .state + .iter() + .find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type)) + { + return Err!(Request(InvalidParam( + "Event type {forbidden_type} may not be requested as stripped state." + ))); + } + + let (room_id, _) = services + .rooms + .alias + .resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone())) + .await?; + + if services.rooms.metadata.is_banned(&room_id).await { + return Err!(Request(Forbidden("This room is banned on this homeserver."))); + } + + match services + .rooms + .summary + .get_stripped_state_for_user( + user_id, + &room_id, + &body.via, + &body.state, + body.num_joined_members, + ) + .await + { + | Accessibility::Accessible(( + via, + RoomStrippedState { state, num_joined_members, .. }, + )) => Ok( + assign!(get_stripped_state::msc4560::Response::new(via), { state, num_joined_members }), + ), + | Accessibility::Inaccessible => { + Err!(Request(Forbidden("You may not request this room's stripped state."))) + }, + | Accessibility::NotFound => { + Err!(Request(NotFound("This room does not exist."))) + }, + } +} diff --git a/src/api/client/room/summary.rs b/src/api/client/room/summary.rs index da6958242..6c60cd88b 100644 --- a/src/api/client/room/summary.rs +++ b/src/api/client/room/summary.rs @@ -13,7 +13,7 @@ pub(crate) async fn get_room_summary( State(services): State, body: Ruma, ) -> Result { - let (room_id, servers) = services + let (room_id, _) = services .rooms .alias .resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone())) @@ -27,12 +27,9 @@ pub(crate) async fn get_room_summary( .rooms .summary .get_room_summary_for_user( - body.identity - .as_ref() - .map(ClientIdentity::expect_sender_user) - .transpose()?, + body.identity.as_ref().and_then(ClientIdentity::sender_user), &room_id, - &servers, + &body.via, ) .await?; @@ -42,7 +39,7 @@ pub(crate) async fn get_room_summary( Err!(Request(Forbidden("You may not preview this room."), FORBIDDEN)) }, | Accessibility::NotFound => { - Err!(Request(Forbidden("This room does not exist."), FORBIDDEN)) + Err!(Request(NotFound("This room does not exist."))) }, } } diff --git a/src/api/client/room/timestamp_to_event.rs b/src/api/client/room/timestamp_to_event.rs new file mode 100644 index 000000000..0ce077a9b --- /dev/null +++ b/src/api/client/room/timestamp_to_event.rs @@ -0,0 +1,61 @@ +use axum::extract::State; +use conduwuit::{Err, Event, Result, utils::stream::TryIgnore}; +use futures::{StreamExt, pin_mut}; +use ruma::api::client::room::get_event_by_timestamp; + +use crate::Ruma; + +const MAX_CANDIDATES: usize = 20; + +/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` +/// +/// Gets the ID of the event closest to the given timestamp, in the direction +/// specified by `dir`. +pub(crate) async fn get_event_by_timestamp_route( + State(ref services): State, + body: Ruma, +) -> Result { + let sender_user = body.identity.expect_sender_user()?; + let room_id = &body.room_id; + + if !services + .rooms + .state_accessor + .user_can_see_state_events(sender_user, room_id) + .await + { + return Err!(Request(Forbidden("You don't have permission to view this room."))); + } + + if !services.rooms.timeline.timestamp_index_ready().await { + return Err!(FeatureDisabled("timestamp_to_event")); + } + + let candidates = services + .rooms + .timeline + .pdus_by_timestamp(room_id, body.ts, body.dir) + .ignore_err() + .take(MAX_CANDIDATES); + + pin_mut!(candidates); + while let Some((_, pdu)) = candidates.next().await { + if services + .rooms + .state_accessor + .user_can_see_event(sender_user, room_id, pdu.event_id()) + .await + { + return Ok(get_event_by_timestamp::v1::Response::new( + pdu.event_id().to_owned(), + pdu.origin_server_ts(), + )); + } + } + + Err!(Request(NotFound( + "Unable to find event from {} in direction {:?}", + body.ts.get(), + body.dir + ))) +} diff --git a/src/api/client/send.rs b/src/api/client/send.rs index b87f7eb2e..41e3804b0 100644 --- a/src/api/client/send.rs +++ b/src/api/client/send.rs @@ -95,12 +95,7 @@ pub(crate) async fn send_message_event_route( PartialPdu { event_type: body.event_type.clone().into(), content, - sticky: services - .config - .allow_sticky_events - .then_some(body.sticky_duration_ms) - .flatten() - .map(sticky::object), + sticky: body.sticky_duration_ms.map(sticky::object), unsigned: Some(unsigned), timestamp: if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await diff --git a/src/api/client/sync/v3/joined.rs b/src/api/client/sync/v3/joined.rs index d2e8a8909..536dc2a9d 100644 --- a/src/api/client/sync/v3/joined.rs +++ b/src/api/client/sync/v3/joined.rs @@ -15,7 +15,7 @@ use conduwuit::{ }, warn, }; -use conduwuit_service::Services; +use conduwuit_service::{Services, rooms::read_receipt::pack_receipts}; use futures::{ FutureExt, StreamExt, TryFutureExt, future::{OptionFuture, join, join3, join4, try_join, try_join3}, @@ -64,7 +64,7 @@ pub(super) async fn load_joined_room( services: &Services, sync_context: SyncContext<'_>, ref room_id: OwnedRoomId, -) -> Result<(JoinedRoom, DeviceListUpdates)> { +) -> Result { /* Building a sync response involves many steps which all depend on each other. To parallelize the process as much as possible, each step is divided into its own function, @@ -80,7 +80,6 @@ pub(super) async fn load_joined_room( sticky, summary, notification_counts, - device_list_updates, }, ) = try_join3( build_account_data(services, sync_context, room_id), @@ -117,7 +116,7 @@ pub(super) async fn load_joined_room( unread_thread_notifications: BTreeMap::new(), }); - Ok((joined_room, device_list_updates)) + Ok(joined_room) } /// Collect changes to the syncing user's account data events. @@ -243,9 +242,14 @@ async fn build_ephemeral( let (receipt_events, typing_event, private_read_event) = join3(receipt_events, typing_event, private_read_event).await; - let mut edus = receipt_events; + let mut all_receipts = receipt_events; + all_receipts.extend(private_read_event); + + let mut edus = Vec::new(); + if !all_receipts.is_empty() { + edus.push(pack_receipts(all_receipts.into_iter()).cast()); + } edus.extend(typing_event); - edus.extend(private_read_event); Ok(assign!(Ephemeral::new(), { events: edus })) } @@ -258,7 +262,6 @@ struct StateAndTimeline { sticky: Sticky, summary: Option, notification_counts: Option, - device_list_updates: DeviceListUpdates, } async fn build_sticky_events( @@ -268,10 +271,6 @@ async fn build_sticky_events( timeline: &TimelinePdus, joined_since_last_sync: bool, ) -> Sticky { - if !services.config.allow_sticky_events { - return Sticky::new(); - } - let SyncContext { syncing_user, last_sync_end_count, @@ -376,24 +375,14 @@ async fn build_state_and_timeline( debug_warn!("timeline for newly joined room is empty"); } - let (summary, device_list_updates) = try_join( - build_room_summary( - services, - sync_context, - room_id, - shortstatehashes, - &timeline, - &state_events, - joined_since_last_sync, - ), - build_device_list_updates( - services, - sync_context, - room_id, - shortstatehashes, - &state_events, - joined_since_last_sync, - ), + let summary = build_room_summary( + services, + sync_context, + room_id, + shortstatehashes, + &timeline, + &state_events, + joined_since_last_sync, ) .await?; @@ -429,7 +418,6 @@ async fn build_state_and_timeline( sticky, summary, notification_counts, - device_list_updates, }) } @@ -799,8 +787,7 @@ async fn build_room_summary( Ok(Some(assign!(RoomSummary::new(), { heroes: heroes - .map(|heroes| heroes.into_iter().collect()) - .unwrap_or_default(), + .map_or_default(|heroes| heroes.into_iter().collect()), joined_member_count: Some(ruma_from_u64(joined_member_count)), invited_member_count: Some(ruma_from_u64(invited_member_count)), }))) @@ -853,35 +840,34 @@ async fn build_heroes( .await } -/// Collect updates to users' device lists for E2EE. -#[tracing::instrument(level = "debug", skip_all)] -async fn build_device_list_updates( +/// Collect updates to users' device lists for E2EE in a joined room. +#[tracing::instrument(level = "debug", skip_all, fields(%room_id))] +pub(super) async fn load_device_list_updates( services: &Services, - SyncContext { + sync_context: SyncContext<'_>, + room_id: &RoomId, +) -> Result { + let SyncContext { syncing_user, last_sync_end_count, current_count, .. - }: SyncContext<'_>, - room_id: &RoomId, - ShortStateHashes { current_shortstatehash, .. }: ShortStateHashes, - state_events: &Vec, - joined_since_last_sync: bool, -) -> Result { - let is_encrypted_room = services - .rooms - .state_accessor - .state_get(current_shortstatehash, &StateEventType::RoomEncryption, "") - .is_ok(); + } = sync_context; + + let mut device_list_updates = DeviceListUpdates::new(); // initial syncs don't include device updates, and rooms which aren't // encrypted don't affect them, so return early in either of those cases - if last_sync_end_count.is_none() || !(is_encrypted_room.await) { - return Ok(DeviceListUpdates::new()); + if last_sync_end_count.is_none() + || !services + .rooms + .state_accessor + .is_encrypted_room(room_id) + .await + { + return Ok(device_list_updates); } - let mut device_list_updates = DeviceListUpdates::new(); - // add users with changed keys to the `changed` list services .users @@ -892,19 +878,56 @@ async fn build_device_list_updates( }) .await; - // add users who now share encrypted rooms to `changed` and - // users who no longer share encrypted rooms to `left` - for state_event in state_events { - if state_event.kind == RoomMember { - let Some(content): Option = state_event.get_content().ok() + let shortstatehashes = fetch_shortstatehashes(services, sync_context, room_id).await?; + let ShortStateHashes { + current_shortstatehash, + last_sync_end_shortstatehash, + } = shortstatehashes; + + if check_joined_since_last_sync(services, shortstatehashes, sync_context).await? { + // the syncing user now shares an encrypted room with every member + services + .rooms + .state_cache + .room_members(room_id) + .ready_for_each(|user_id| { + device_list_updates.changed.insert(user_id); + }) + .await; + } else if let Some(last_sync_end_shortstatehash) = last_sync_end_shortstatehash + && last_sync_end_shortstatehash != current_shortstatehash + { + // add users who now share encrypted rooms to `changed` and + // users who no longer share encrypted rooms to `left` + let state_added = services + .rooms + .state_accessor + .state_added((last_sync_end_shortstatehash, current_shortstatehash)) + .await?; + + for (shortstatekey, _) in state_added { + let Ok((StateEventType::RoomMember, state_key)) = services + .rooms + .short + .get_statekey_from_short(shortstatekey) + .await else { continue; }; - let Some(user_id): Option = state_event - .state_key - .as_ref() - .and_then(|key| key.parse().ok()) + let Ok(user_id) = OwnedUserId::try_from(state_key.as_str()) else { + continue; + }; + + let Ok(content): Result = services + .rooms + .state_accessor + .state_get_content( + current_shortstatehash, + &StateEventType::RoomMember, + user_id.as_str(), + ) + .await else { continue; }; @@ -920,7 +943,7 @@ async fn build_device_list_updates( | Leave if !shares_encrypted_room => { device_list_updates.left.insert(user_id); }, - | Join if joined_since_last_sync || shares_encrypted_room => { + | Join if shares_encrypted_room => { device_list_updates.changed.insert(user_id); }, | _ => (), diff --git a/src/api/client/sync/v3/mod.rs b/src/api/client/sync/v3/mod.rs index 4987534cf..e004ec08d 100644 --- a/src/api/client/sync/v3/mod.rs +++ b/src/api/client/sync/v3/mod.rs @@ -3,7 +3,6 @@ mod left; mod state; use std::{ - cmp::{self}, collections::{BTreeMap, HashMap, HashSet}, time::Duration, }; @@ -21,7 +20,7 @@ use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture}; use ruma::{ DeviceId, OwnedUserId, RoomId, UserId, api::client::{ - filter::FilterDefinition, + filter::{self, FilterDefinition, RoomFilter}, sync::sync_events::{ self, DeviceLists, v3::{ @@ -39,13 +38,17 @@ use service::{ account_data::AnyRawAccountDataEvent, rooms::lazy_loading::{self, MemberSet, Options as _}, }; +use wildmatch::WildMatch; use super::{load_timeline, share_encrypted_room}; use crate::{ Ruma, client::{ is_ignored_invite, - sync::v3::{joined::load_joined_room, left::load_left_room}, + sync::v3::{ + joined::{load_device_list_updates, load_joined_room}, + left::load_left_room, + }, }, client_ip::ClientIp, }; @@ -201,9 +204,14 @@ pub(crate) async fn sync_events_route( .update_device_last_seen(sender_user, Some(sender_device), client_ip) .await; - let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await; + let mut wake_receiver = services.sync.subscribe_to_wake(sender_user); let response = build_sync_events(&services, &body).await?; - if body.body.full_state + + let timeout_duration = body.body.timeout.unwrap_or_default(); + // If the timeout is zero, request has full_state=true, or there's + // meaningful data to return, do so immediately. + if timeout_duration.is_zero() + || body.body.full_state || !(response.rooms.is_empty() && response.presence.is_empty() && response.account_data.is_empty() @@ -213,11 +221,15 @@ pub(crate) async fn sync_events_route( return Ok(response); } - // Hang a few seconds so requests are not spammed - // Stop hanging if new info arrives - let default = Duration::from_secs(30); - let duration = cmp::min(body.body.timeout.unwrap_or(default), default); - _ = tokio::time::timeout(duration, wake_receiver.changed()).await; + // Otherwise, wait for a wake signal to rebuild changes. Cap timeout at 30 + // seconds (this isn't specced, but a reasonable cap since most clients have + // a 30-second polling interval). + let duration = timeout_duration.min(Duration::from_secs(30)); + let mut shutdown_signal = services.server.signal.subscribe(); + tokio::select! { + _ = tokio::time::timeout(duration, wake_receiver.changed()) => {}, + _ = shutdown_signal.recv() => return Err!(Request(Unknown("Server is shutting down"), SERVICE_UNAVAILABLE)), + }; // Retry returning data build_sync_events(&services, &body).await @@ -271,34 +283,47 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_joined(syncing_user) + .ready_filter(|room_id| room_selected(&filter.room, room_id)) .broad_filter_map(|room_id| async { let joined_room = load_joined_room(services, context, room_id.clone()).await; match joined_room { - | Ok((room, updates)) => Some((room_id, room, updates)), + | Ok(room) => Some((room_id, room)), | Err(err) => { error!(?err, %room_id, "error loading joined room"); None }, } }) - .ready_fold( - (BTreeMap::new(), DeviceListUpdates::new()), - |(mut joined_rooms, mut all_updates), (room_id, joined_room, updates)| { - all_updates.merge(updates); + .ready_fold(BTreeMap::new(), |mut joined_rooms, (room_id, joined_room)| { + if !joined_room.is_empty() { + joined_rooms.insert(room_id, joined_room); + } - if !joined_room.is_empty() { - joined_rooms.insert(room_id, joined_room); - } + joined_rooms + }); - (joined_rooms, all_updates) - }, - ); + // a filtered out room still contributes its device list updates + let device_list_updates = services + .rooms + .state_cache + .rooms_joined(syncing_user) + .broad_filter_map(|room_id| async move { + load_device_list_updates(services, context, &room_id) + .await + .inspect_err(|err| error!(?err, %room_id, "error loading device list updates")) + .ok() + }) + .ready_fold(DeviceListUpdates::new(), |mut all_updates, updates| { + all_updates.merge(updates); + all_updates + }); let left_rooms = services .rooms .state_cache .rooms_left(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .broad_filter_map(|(room_id, leave_pdu)| async { let left_room = load_left_room(services, context, room_id.clone(), leave_pdu).await; @@ -317,6 +342,7 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_invited(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .wide_filter_map(async |(room_id, invite_state)| { if is_ignored_invite(services, syncing_user, &room_id).await { None @@ -347,6 +373,7 @@ pub(crate) async fn build_sync_events( .rooms .state_cache .rooms_knocked(syncing_user) + .ready_filter(|(room_id, _)| room_selected(&filter.room, room_id)) .fold_default(|mut knocked_rooms: BTreeMap<_, _>, (room_id, knock_state)| async move { let knock_count = services .rooms @@ -376,6 +403,13 @@ pub(crate) async fn build_sync_events( .account_data .changes_since(None, syncing_user, last_sync_end_count, Some(current_count)) .ready_filter_map(|e| extract_variant!(e, AnyRawAccountDataEvent::Global)) + .ready_filter(|event| { + event + .get_field::("type") + .ok() + .flatten() + .is_some_and(|event_type| type_selected(&filter.account_data, &event_type)) + }) .collect(); let to_device_events = services @@ -404,7 +438,8 @@ pub(crate) async fn build_sync_events( .list_unused_fallback_key_types(syncing_user, syncing_device); let ( - (joined_rooms, mut device_list_updates), + joined_rooms, + mut device_list_updates, left_rooms, invited_rooms, knocked_rooms, @@ -417,6 +452,7 @@ pub(crate) async fn build_sync_events( ) = async { futures::join!( joined_rooms, + device_list_updates, left_rooms, invited_rooms, knocked_rooms, @@ -465,6 +501,24 @@ pub(crate) async fn build_sync_events( Ok(response) } +fn room_selected(filter: &RoomFilter, room_id: &RoomId) -> bool { + !filter.not_rooms.iter().any(|not_room| not_room == room_id) + && filter + .rooms + .as_ref() + .is_none_or(|rooms| rooms.iter().any(|room| room == room_id)) +} + +fn type_selected(filter: &filter::Filter, event_type: &str) -> bool { + let matches = |pattern: &String| WildMatch::new(pattern).matches(event_type); + + !filter.not_types.iter().any(matches) + && filter + .types + .as_ref() + .is_none_or(|types| types.iter().any(matches)) +} + #[tracing::instrument(name = "presence", level = "debug", skip_all)] async fn process_presence_updates( services: &Services, @@ -528,3 +582,45 @@ async fn prepare_lazily_loaded_members( lazily_loaded_members } + +#[cfg(test)] +mod tests { + use ruma::{owned_room_id, room_id}; + + use super::*; + + #[test] + fn rooms_filter_selects_rooms() { + let room_id = room_id!("!a:example.com"); + let mut filter = RoomFilter::default(); + assert!(room_selected(&filter, room_id)); + + filter.rooms = Some(Vec::new()); + assert!(!room_selected(&filter, room_id)); + + filter.rooms = Some(vec![room_id.to_owned()]); + assert!(room_selected(&filter, room_id)); + + filter.not_rooms = vec![owned_room_id!("!a:example.com")]; + assert!(!room_selected(&filter, room_id)); + } + + #[test] + fn types_filter_selects_account_data() { + let mut filter = filter::Filter::default(); + assert!(type_selected(&filter, "m.direct")); + + filter.types = Some(Vec::new()); + assert!(!type_selected(&filter, "m.direct")); + + filter.types = Some(vec!["m.direct".to_owned()]); + assert!(type_selected(&filter, "m.direct")); + + filter.types = Some(vec!["m.*".to_owned()]); + assert!(type_selected(&filter, "m.direct")); + assert!(!type_selected(&filter, "im.ponies.user_emotes")); + + filter.not_types = vec!["m.direct".to_owned()]; + assert!(!type_selected(&filter, "m.direct")); + } +} diff --git a/src/api/client/sync/v5.rs b/src/api/client/sync/v5.rs index 7f8997aec..0285c8359 100644 --- a/src/api/client/sync/v5.rs +++ b/src/api/client/sync/v5.rs @@ -24,7 +24,7 @@ use conduwuit::{ use conduwuit_service::{ Services, rooms::read_receipt::pack_receipts, - sync::{SnakeConnectionsKey, into_snake_key}, + sync::{SnakeConnectionsKey, StickyDelivered, into_snake_key}, }; use futures::{ FutureExt, StreamExt, TryFutureExt, @@ -34,7 +34,7 @@ use futures::{ use ruma::{ DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, UInt, UserId, api::client::sync::sync_events::{ - self, DeviceLists, UnreadNotificationsCount, v5::request::ExtensionRoomConfig, + self, DeviceLists, UnreadNotificationsCount, msc4186::request::ExtensionRoomConfig, }, assign, directory::RoomTypeFilter, @@ -63,7 +63,7 @@ use crate::{ client_ip::ClientIp, }; -type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::v5::Request); +type SyncInfo<'a> = (&'a UserId, &'a DeviceId, u64, &'a sync_events::msc4186::Request); type TodoRooms = BTreeMap, usize, u64)>; type KnownRooms = BTreeMap>; type KnownRoomUpdates = BTreeMap>; @@ -86,8 +86,9 @@ fn num_live_events<'a>( } struct SyncCollection { - response: sync_events::v5::Response, + response: sync_events::msc4186::Response, known_room_updates: KnownRoomUpdates, + sticky_delivered: StickyDelivered, } /// `POST /_matrix/client/unstable/org.matrix.simplified_msc3575/sync` @@ -103,8 +104,8 @@ struct SyncCollection { pub(crate) async fn sync_events_v5_route( State(ref services): State, ClientIp(client_ip): ClientIp, // NOTE: Required for updating device metadata - body: Ruma, -) -> Result { + body: Ruma, +) -> Result { let sender_user = body.identity.expect_sender_user()?; let sender_device = body.identity.expect_sender_device()?; @@ -142,12 +143,12 @@ pub(crate) async fn sync_events_v5_route( } // Get sticky parameters from cache - let known_rooms = + let (known_rooms, sticky_delivered) = services .sync .update_snake_sync_request_with_cache(&snake_key, globalsince, &mut body); - let mut wake_receiver = services.sync.subscribe_to_wake(sender_user).await; + let mut wake_receiver = services.sync.subscribe_to_wake(sender_user); let mut collection = collect_sync_response( services, sender_user, @@ -155,6 +156,7 @@ pub(crate) async fn sync_events_v5_route( &body, globalsince, &known_rooms, + &sticky_delivered, ) .await?; @@ -173,6 +175,7 @@ pub(crate) async fn sync_events_v5_route( &body, globalsince, &known_rooms, + &sticky_delivered, ) .await?; } @@ -202,13 +205,13 @@ async fn collect_sync_response( services: &Services, sender_user: &UserId, sender_device: &DeviceId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, globalsince: u64, known_rooms: &KnownRooms, + sticky_delivered: &StickyDelivered, ) -> Result { // Bounds every read below and becomes the `pos` returned to the client. - // Zero would be echoed back as a request for an initial sync. - let next_batch = services.globals.current_count()?.max(1); + let next_batch = services.globals.next_count()?; let all_joined_rooms = services .rooms @@ -262,7 +265,6 @@ async fn collect_sync_response( let pos = next_batch.to_string(); let mut todo_rooms: TodoRooms = BTreeMap::new(); - let mut sticky_rooms = BTreeSet::new(); let sync_info: SyncInfo<'_> = (sender_user, sender_device, globalsince, body); @@ -277,16 +279,16 @@ async fn collect_sync_response( let (account_data, e2ee, to_device, receipts) = try_join4(account_data, e2ee, to_device, receipts).await?; - let extensions = assign!(sync_events::v5::response::Extensions::default(), { + let extensions = assign!(sync_events::msc4186::response::Extensions::default(), { account_data, e2ee, to_device, receipts, - typing: sync_events::v5::response::Typing::default(), - sticky_events: sync_events::v5::response::StickyEvents::default(), + typing: sync_events::msc4186::response::Typing::default(), + sticky_events: sync_events::msc4186::response::StickyEvents::default(), }); - let mut response = assign!(sync_events::v5::Response::new(pos), { + let mut response = assign!(sync_events::msc4186::Response::new(pos), { txn_id: body.txn_id.clone(), lists: BTreeMap::new(), rooms: BTreeMap::new(), @@ -319,7 +321,6 @@ async fn collect_sync_response( all_rooms, &direct_rooms, &mut todo_rooms, - &mut sticky_rooms, known_rooms, &mut response, ) @@ -329,7 +330,6 @@ async fn collect_sync_response( "subscriptions".to_owned(), fetch_subscriptions(services, body, known_rooms, &allowed_rooms, &mut todo_rooms).await, ); - sticky_rooms.extend(body.room_subscriptions.keys().cloned()); let mut timeline_event_ids = BTreeSet::new(); response.rooms = process_rooms( @@ -346,25 +346,31 @@ async fn collect_sync_response( ) .await?; - response.extensions.sticky_events = collect_sticky_events( + let (sticky_events, sticky_delivered) = collect_sticky_events( services, sender_user, body, - &sticky_rooms, + next_batch, + sticky_delivered, + &known_room_updates, &joined_room_ids, - &todo_rooms, &timeline_event_ids, ) - .await?; + .await; + response.extensions.sticky_events = sticky_events; response.extensions.typing = collect_typing_events(services, sender_user, body, &todo_rooms, &known_room_updates) .await?; - Ok(SyncCollection { response, known_room_updates }) + Ok(SyncCollection { + response, + known_room_updates, + sticky_delivered, + }) } -fn response_is_empty(response: &sync_events::v5::Response) -> bool { +fn response_is_empty(response: &sync_events::msc4186::Response) -> bool { let no_account_data = response.extensions.account_data.global.is_empty() && response .extensions @@ -395,7 +401,7 @@ async fn commit_sync_collection( services: &Services, sender_user: &UserId, sender_device: &DeviceId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, globalsince: u64, snake_key: &SnakeConnectionsKey, collection: &SyncCollection, @@ -408,9 +414,10 @@ async fn commit_sync_collection( .parse() .expect("generated sync position"), collection.known_room_updates.clone(), + collection.sticky_delivered.clone(), ); - if body.extensions.to_device.enabled.unwrap_or(false) { + if body.extensions.to_device.enabled { services .users .remove_to_device_events(sender_user, sender_device, globalsince) @@ -420,7 +427,7 @@ async fn commit_sync_collection( async fn fetch_subscriptions( services: &Services, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, known_rooms: &KnownRooms, allowed_rooms: &BTreeSet, todo_rooms: &mut TodoRooms, @@ -480,15 +487,14 @@ async fn fetch_subscriptions( async fn handle_lists<'a, Rooms, AllRooms>( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, all_invited_rooms: Rooms, all_joined_rooms: Rooms, all_rooms: AllRooms, direct_rooms: &HashSet, todo_rooms: &'a mut TodoRooms, - sticky_rooms: &mut BTreeSet, known_rooms: &'a KnownRooms, - response: &'_ mut sync_events::v5::Response, + response: &'_ mut sync_events::msc4186::Response, ) -> KnownRoomUpdates where Rooms: Iterator + Clone + Send + 'a, @@ -579,7 +585,6 @@ where .await; sort_rooms_by_activity(&mut active_rooms); let active_rooms: Vec<_> = active_rooms.into_iter().map(at!(0)).collect(); - sticky_rooms.extend(active_rooms.iter().map(|room_id| (*room_id).to_owned())); let mut new_known_rooms: BTreeSet = BTreeSet::new(); @@ -631,7 +636,7 @@ where } response.lists.insert( list_id.clone(), - assign!(sync_events::v5::response::List::default(), { + assign!(sync_events::msc4186::response::List::default(), { count: ruma_from_usize(active_rooms.len()), }), ); @@ -749,10 +754,10 @@ async fn process_rooms<'a, Rooms>( all_invited_rooms: Rooms, all_knocked_rooms: Rooms, todo_rooms: &TodoRooms, - response: &mut sync_events::v5::Response, - body: &sync_events::v5::Request, + response: &mut sync_events::msc4186::Response, + body: &sync_events::msc4186::Request, timeline_event_ids: &mut BTreeSet, -) -> Result> +) -> Result> where Rooms: Iterator + Clone + Send + 'a, { @@ -787,7 +792,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { initial: Some(roomsince == &0), invite_state, limited: true, @@ -821,7 +826,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { initial: Some(roomsince == &0), invite_state: Some(knock_state), limited: true, @@ -988,7 +993,7 @@ where .state_accessor .get_member(room_id, &user_id) .map_ok(|member_event| { - assign!(sync_events::v5::response::Hero::new(user_id.clone()), { + assign!(sync_events::msc4186::response::Hero::new(user_id.clone()), { name: member_event.displayname, avatar: member_event.avatar_url, }) @@ -1032,7 +1037,7 @@ where rooms.insert( room_id.clone(), - assign!(sync_events::v5::response::Room::new(), { + assign!(sync_events::msc4186::response::Room::new(), { name: services .rooms .state_accessor @@ -1103,64 +1108,61 @@ where Ok(rooms) } +#[expect(clippy::too_many_arguments)] async fn collect_sticky_events( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, - sticky_rooms: &BTreeSet, + body: &sync_events::msc4186::Request, + next_batch: u64, + sticky_delivered: &StickyDelivered, + known_room_updates: &KnownRoomUpdates, joined_room_ids: &BTreeSet, - todo_rooms: &TodoRooms, timeline_event_ids: &BTreeSet, -) -> Result { - if !services.config.allow_sticky_events - || !body.extensions.sticky_events.enabled.unwrap_or(false) - { - return Ok(sync_events::v5::response::StickyEvents::default()); +) -> (sync_events::msc4186::response::StickyEvents, StickyDelivered) { + let mut response = sync_events::msc4186::response::StickyEvents::default(); + let mut delivered = StickyDelivered::new(); + + let sticky_events = &body.extensions.sticky_events; + if !sticky_events.enabled.unwrap_or(false) { + return (response, delivered); } - let since = body - .extensions - .sticky_events - .since - .as_deref() - .and_then(|token| token.parse::().ok()) - .unwrap_or(0); - let limit = body - .extensions - .sticky_events + let scope = extension_scope( + sticky_events.lists.as_deref(), + sticky_events.rooms.as_deref(), + body.lists.keys().map(String::as_str), + known_room_updates, + ); + let limit = sticky_events .limit .map_or(DEFAULT_STICKY_LIMIT, usize_from_ruma) .clamp(1, DEFAULT_STICKY_LIMIT); let now = u64::from(MilliSecondsSinceUnixEpoch::now().get()); let oldest_sticky_ts = now.saturating_sub(sticky::MAX_DURATION_MS); - let mut backlog = Vec::new(); - let mut stream = Vec::new(); - for room_id in sticky_rooms - .iter() - .filter(|room_id| joined_room_ids.contains(*room_id)) - { - // a room the client has not seen before needs its whole backlog, which - // a single stream position cannot express - let initial = todo_rooms - .get(room_id) - .is_some_and(|&(_, _, roomsince)| roomsince == 0); + for room_id in scope.intersection(joined_room_ids) { + let since = sticky_delivered.get(room_id).copied(); + let mut pending = Vec::new(); let pdus = services.rooms.timeline.pdus_rev(room_id, None).ignore_err(); pin_mut!(pdus); while let Some((count, pdu)) = pdus.next().await { - // nothing older than this can still be sticky, and on the stream we - // have already delivered everything up to `since` - if u64::from(pdu.origin_server_ts) < oldest_sticky_ts - || (!initial && count <= PduCount::Normal(since)) - { - break; - } - let PduCount::Normal(count) = count else { continue; }; + if count > next_batch { + continue; + } + + // Nothing older than this can still be sticky, and everything up to + // `since` has already been delivered + if u64::from(pdu.origin_server_ts) < oldest_sticky_ts + || since.is_some_and(|since| count <= since) + { + break; + } + let is_sticky = pdu .sticky .as_deref() @@ -1177,38 +1179,26 @@ async fn collect_sticky_events( continue; } - if count > since { - stream.push((count, room_id.clone(), pdu)); - } else { - backlog.push((room_id.clone(), pdu)); - } + pending.push((count, pdu)); } - } - stream.sort_by_key(|(count, ..)| *count); - let mut response = sync_events::v5::response::StickyEvents::default(); + pending.reverse(); + let truncated = pending.len() > limit; + let mut last_count = next_batch; + for (count, pdu) in pending.into_iter().take(limit) { + push_sticky_event(services, &mut response, sender_user, room_id.clone(), pdu).await; + last_count = count; + } - // MSC4480 lets us ignore the limit for a newly visible room's backlog - for (room_id, pdu) in backlog { - push_sticky_event(services, &mut response, sender_user, room_id, pdu).await; + delivered.insert(room_id.clone(), if truncated { last_count } else { next_batch }); } - let mut next_batch = None; - for (count, room_id, pdu) in stream.into_iter().take(limit) { - push_sticky_event(services, &mut response, sender_user, room_id, pdu).await; - next_batch = Some(count); - } - - if !response.rooms.is_empty() { - response.next_batch = Some(next_batch.unwrap_or(since).to_string()); - } - - Ok(response) + (response, delivered) } async fn push_sticky_event( services: &Services, - response: &mut sync_events::v5::response::StickyEvents, + response: &mut sync_events::msc4186::response::StickyEvents, sender_user: &UserId, room_id: OwnedRoomId, mut pdu: PduEvent, @@ -1275,12 +1265,12 @@ async fn collect_required_state( async fn collect_typing_events( services: &Services, sender_user: &UserId, - body: &sync_events::v5::Request, + body: &sync_events::msc4186::Request, todo_rooms: &TodoRooms, known_room_updates: &KnownRoomUpdates, -) -> Result { +) -> Result { if !body.extensions.typing.enabled.unwrap_or(false) { - return Ok(sync_events::v5::response::Typing::default()); + return Ok(sync_events::msc4186::response::Typing::default()); } let typing = &body.extensions.typing; let scope = extension_scope( @@ -1290,10 +1280,10 @@ async fn collect_typing_events( known_room_updates, ); if scope.is_empty() { - return Ok(sync_events::v5::response::Typing::default()); + return Ok(sync_events::msc4186::response::Typing::default()); } - let mut typing_response = sync_events::v5::response::Typing::default(); + let mut typing_response = sync_events::msc4186::response::Typing::default(); for (room_id, (_, _, roomsince)) in todo_rooms { if !scope.contains(room_id) { continue; @@ -1373,12 +1363,17 @@ fn extension_scope<'a>( async fn collect_account_data( services: &Services, - (sender_user, _, globalsince, body): (&UserId, &DeviceId, u64, &sync_events::v5::Request), -) -> sync_events::v5::response::AccountData { - let mut account_data = sync_events::v5::response::AccountData::default(); + (sender_user, _, globalsince, body): ( + &UserId, + &DeviceId, + u64, + &sync_events::msc4186::Request, + ), +) -> sync_events::msc4186::response::AccountData { + let mut account_data = sync_events::msc4186::response::AccountData::default(); if !body.extensions.account_data.enabled.unwrap_or(false) { - return sync_events::v5::response::AccountData::default(); + return sync_events::msc4186::response::AccountData::default(); } account_data.global = services @@ -1413,15 +1408,15 @@ async fn collect_e2ee<'a, Rooms>( &UserId, &DeviceId, u64, - &sync_events::v5::Request, + &sync_events::msc4186::Request, ), all_joined_rooms: Rooms, -) -> Result +) -> Result where Rooms: Iterator + Send + 'a, { - if !body.extensions.e2ee.enabled.unwrap_or(false) { - return Ok(sync_events::v5::response::E2EE::default()); + if !body.extensions.e2ee.enabled { + return Ok(sync_events::msc4186::response::E2EE::default()); } let mut left_encrypted_users = HashSet::new(); // Users that have left any encrypted rooms the sender was in let mut device_list_changes = HashSet::new(); @@ -1608,7 +1603,7 @@ where } } - Ok(assign!(sync_events::v5::response::E2EE::default(), { + Ok(assign!(sync_events::msc4186::response::E2EE::default(), { device_unused_fallback_key_types: None, device_one_time_keys_count: services @@ -1627,12 +1622,12 @@ async fn collect_to_device( services: &Services, (sender_user, sender_device, globalsince, body): SyncInfo<'_>, next_batch: u64, -) -> Option { - if !body.extensions.to_device.enabled.unwrap_or(false) { +) -> Option { + if !body.extensions.to_device.enabled { return None; } - Some(assign!(sync_events::v5::response::ToDevice::default(), { + Some(assign!(sync_events::msc4186::response::ToDevice::default(), { next_batch: next_batch.to_string(), events: services .users @@ -1643,9 +1638,9 @@ async fn collect_to_device( })) } -async fn collect_receipts(_services: &Services) -> sync_events::v5::response::Receipts { +async fn collect_receipts(_services: &Services) -> sync_events::msc4186::response::Receipts { // TODO: get explicitly requested read receipts - sync_events::v5::response::Receipts::default() + sync_events::msc4186::response::Receipts::default() } #[cfg(test)] @@ -1658,23 +1653,25 @@ mod tests { fn custom_room_type() -> RoomTypeFilter { RoomTypeFilter::from(Some("com.example")) } - fn response() -> sync_events::v5::Response { sync_events::v5::Response::new("1".to_owned()) } + fn response() -> sync_events::msc4186::Response { + sync_events::msc4186::Response::new("1".to_owned()) + } - fn typing_scope_request() -> sync_events::v5::Request { - let mut request = sync_events::v5::Request::new(); + fn typing_scope_request() -> sync_events::msc4186::Request { + let mut request = sync_events::msc4186::Request::new(); request .lists - .insert("first".to_owned(), sync_events::v5::request::List::default()); + .insert("first".to_owned(), sync_events::msc4186::request::List::default()); request .lists - .insert("second".to_owned(), sync_events::v5::request::List::default()); + .insert("second".to_owned(), sync_events::msc4186::request::List::default()); request.room_subscriptions.insert( owned_room_id!("!subscription-a:example.com"), - sync_events::v5::request::RoomSubscription::default(), + sync_events::msc4186::request::RoomSubscription::default(), ); request.room_subscriptions.insert( owned_room_id!("!subscription-b:example.com"), - sync_events::v5::request::RoomSubscription::default(), + sync_events::msc4186::request::RoomSubscription::default(), ); request } @@ -1768,9 +1765,10 @@ mod tests { #[test] fn a_room_with_no_events_is_still_empty() { let mut response = response(); - response - .rooms - .insert(owned_room_id!("!a:example.com"), sync_events::v5::response::Room::default()); + response.rooms.insert( + owned_room_id!("!a:example.com"), + sync_events::msc4186::response::Room::default(), + ); assert!(response_is_empty(&response)); } @@ -1781,7 +1779,7 @@ mod tests { let mut response = response(); response .rooms - .insert(room_id.to_owned(), sync_events::v5::response::Room::default()); + .insert(room_id.to_owned(), sync_events::msc4186::response::Room::default()); response .extensions .receipts @@ -1846,7 +1844,7 @@ mod tests { #[test] fn to_device_without_events_is_empty() { let mut response = response(); - response.extensions.to_device = Some(sync_events::v5::response::ToDevice::default()); + response.extensions.to_device = Some(sync_events::msc4186::response::ToDevice::default()); assert!(response_is_empty(&response)); } diff --git a/src/api/client/unversioned.rs b/src/api/client/unversioned.rs index 814ee0d9e..39862673b 100644 --- a/src/api/client/unversioned.rs +++ b/src/api/client/unversioned.rs @@ -27,12 +27,7 @@ pub(crate) async fn get_supported_versions_route( State(services): State, _body: Ruma, ) -> Result { - let mut unstable_features = unstable_features(); - - if services.config.allow_sticky_events { - // sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) - unstable_features.insert("org.matrix.msc4354".to_owned(), true); - } + let unstable_features = unstable_features(&services.config.experiments); Ok(assign!(get_supported_versions::Response::new(versions()), { unstable_features @@ -64,7 +59,7 @@ pub(crate) async fn continuwuity_local_user_count( .stream_local_users() .filter_map(async |user_id| { if !services.users.status(&user_id).await.is_active() - || services.appservice.is_exclusive_user_id(&user_id).await + || services.appservice.is_exclusive_user_id(&user_id) { None } else { diff --git a/src/api/client/user_directory.rs b/src/api/client/user_directory.rs index 7d8a9a9c4..a8eb613d6 100644 --- a/src/api/client/user_directory.rs +++ b/src/api/client/user_directory.rs @@ -5,9 +5,7 @@ use conduwuit::{ }; use futures::{FutureExt, StreamExt, pin_mut}; use ruma::{ - api::client::user_directory::search_users::{self}, - assign, - events::room::join_rules::JoinRule, + api::client::user_directory::search_users, assign, events::room::join_rules::JoinRule, }; use crate::Ruma; diff --git a/src/api/client/well_known.rs b/src/api/client/well_known.rs index 749571f99..9e2552307 100644 --- a/src/api/client/well_known.rs +++ b/src/api/client/well_known.rs @@ -43,9 +43,9 @@ pub(crate) async fn well_known_client( /// homeserver, implementing MSC4143. pub(crate) async fn get_rtc_transports( State(services): State, - _body: Ruma, -) -> Result { - Ok(ruma::api::client::rtc::transports::v1::Response::new( + _body: Ruma, +) -> Result { + Ok(ruma::api::client::rtc::transports::msc4143::Response::new( services.config.matrix_rtc.foci.clone(), )) } diff --git a/src/api/mod.rs b/src/api/mod.rs index c2e71ba8c..df050e7be 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -16,6 +16,3 @@ pub mod client_ip; pub mod admin; pub(crate) use self::router::{Ruma, RumaResponse, State}; - -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} diff --git a/src/api/router.rs b/src/api/router.rs index ac0a2267b..e966939ba 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -8,9 +8,9 @@ use std::str::FromStr; use axum::{ Router, response::{IntoResponse, Redirect}, - routing::{any, get, post}, + routing::{any, get}, }; -use conduwuit::err; +use conduwuit::{config::experiments::ToggledExperiment, err}; pub(super) use conduwuit_service::state::State; use http::{Uri, uri}; @@ -52,6 +52,7 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::set_pushrule_actions_route) .ruma_route(&client::delete_pushrule_route) .ruma_route(&client::get_room_event_route) + .ruma_route(&client::get_event_by_timestamp_route) .ruma_route(&client::get_room_aliases_route) .ruma_route(&client::get_filter_route) .ruma_route(&client::create_filter_route) @@ -162,10 +163,6 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::update_device_route) .ruma_route(&client::delete_device_route) .ruma_route(&client::delete_devices_route) - .ruma_route(&client::put_dehydrated_device_route) - .ruma_route(&client::delete_dehydrated_device_route) - .ruma_route(&client::get_dehydrated_device_route) - .ruma_route(&client::get_dehydrated_events_route) .ruma_route(&client::get_tags_route) .ruma_route(&client::update_tag_route) .ruma_route(&client::delete_tag_route) @@ -193,11 +190,26 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&client::well_known_policy_server) .ruma_route(&client::get_rtc_transports) .ruma_route(&client::room_initial_sync_route) + .ruma_route(&client::discover_rendezvous_route) + .ruma_route(&client::create_rendezvous_session_route) + .ruma_route(&client::update_rendezvous_session_route) + .ruma_route(&client::get_rendezvous_session_route) + .ruma_route(&client::delete_rendezvous_session_route) .ruma_route(&client::get_authorization_server_metadata_route) .merge(client::oauth::router(state)) .route("/_continuwuity/server_version", get(client::continuwuity_server_version)) .ruma_route(&admin::rooms::ban::ban_room) .ruma_route(&admin::rooms::list::list_rooms); + if config.experiments.msc3814.is_enabled() { + router = router + .ruma_route(&client::put_dehydrated_device_route) + .ruma_route(&client::delete_dehydrated_device_route) + .ruma_route(&client::get_dehydrated_device_route) + .ruma_route(&client::get_dehydrated_events_route); + } + if config.experiments.msc4560.is_enabled() { + router = router.ruma_route(&client::get_stripped_state_route); + } if config.allow_prometheus_metrics { router = router.route("/_continuwuity/metrics", get(client::continuwuity_metrics)); @@ -236,6 +248,9 @@ pub fn build(router: Router, state: State) -> Router { .ruma_route(&server::get_content_route) .ruma_route(&server::get_content_thumbnail_route) .route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count)); + if config.experiments.msc4560.is_enabled() { + router = router.ruma_route(&server::get_stripped_state_route); + } } else { router = router .route("/_matrix/federation/{*path}", any(federation_disabled)) @@ -248,45 +263,16 @@ pub fn build(router: Router, state: State) -> Router { // and other functionality will continue to work router = router.ruma_route(&server::get_openid_userinfo_route); - if config.allow_legacy_media { - router = router - .ruma_route(&client::get_media_config_legacy_route) - .ruma_route(&client::get_media_preview_legacy_route) - .ruma_route(&client::get_content_legacy_route) - .ruma_route(&client::get_content_as_filename_legacy_route) - .ruma_route(&client::get_content_thumbnail_legacy_route) - .route("/_matrix/media/v1/config", get(client::get_media_config_legacy_legacy_route)) - .route("/_matrix/media/v1/upload", post(client::create_content_legacy_route)) - .route( - "/_matrix/media/v1/preview_url", - get(client::get_media_preview_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/download/{server_name}/{media_id}", - get(client::get_content_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/download/{server_name}/{media_id}/{file_name}", - get(client::get_content_as_filename_legacy_legacy_route), - ) - .route( - "/_matrix/media/v1/thumbnail/{server_name}/{media_id}", - get(client::get_content_thumbnail_legacy_legacy_route), - ); - } else { - router = router - .route("/_matrix/media/v1/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/config", any(legacy_media_disabled)) - .route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview)) - .route("/_matrix/media/r0/config", any(legacy_media_disabled)) - .route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled)) - .route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview)); - } - router + .route("/_matrix/media/v1/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/config", any(legacy_media_disabled)) + .route("/_matrix/media/v3/download/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/thumbnail/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/v3/preview_url", any(redirect_legacy_preview)) + .route("/_matrix/media/r0/config", any(legacy_media_disabled)) + .route("/_matrix/media/r0/download/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/r0/thumbnail/{*path}", any(legacy_media_disabled)) + .route("/_matrix/media/r0/preview_url", any(redirect_legacy_preview)) } async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse { @@ -307,7 +293,7 @@ async fn redirect_legacy_preview(uri: Uri) -> impl IntoResponse { } async fn legacy_media_disabled() -> impl IntoResponse { - err!(Request(Forbidden("Unauthenticated media is disabled."))) + err!(Request(NotFound("Unauthenticated media is disabled."))) } async fn federation_disabled() -> impl IntoResponse { diff --git a/src/api/router/args.rs b/src/api/router/args.rs index beee4a3d0..cc18438c0 100644 --- a/src/api/router/args.rs +++ b/src/api/router/args.rs @@ -1,18 +1,21 @@ -use std::ops::Deref; +use std::{ + net::{IpAddr, Ipv4Addr}, + ops::Deref, +}; use axum::{ RequestExt, RequestPartsExt, body::Body, extract::{FromRequest, Path, Query}, }; -use conduwuit::{Error, Result, err}; +use conduwuit::{Error, Result, err, error}; use ruma::{ CanonicalJsonObject, api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme}, }; use serde::Deserialize; -use crate::{State, router::auth::CheckAuth}; +use crate::{State, client_ip::ClientIp, router::auth::CheckAuth}; /// Query parameters needed to authenticate requests #[derive(Deserialize)] @@ -87,6 +90,11 @@ where let Path(path): Path> = parts.extract().await?; let borrowed_path: Vec<_> = path.iter().map(String::as_str).collect(); let Query(auth_query): Query = parts.extract().await?; + let ClientIp(ip) = parts + .extract_with_state(services) + .await + .inspect_err(|err| error!("Failed to extract client IP: {err:?}")) + .unwrap_or(ClientIp(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); // Assemble a new request from the read body and parts let request = hyper::Request::from_parts(parts, body.as_ref()); @@ -102,7 +110,8 @@ where })?; let identity = - R::Authentication::check::(services, &request, authentication, auth_query).await?; + R::Authentication::check::(services, &request, ip, authentication, auth_query) + .await?; // Deserialize the body let body = R::try_from_http_request(request, &borrowed_path) diff --git a/src/api/router/auth.rs b/src/api/router/auth.rs index cac270ee0..0569ebfbf 100644 --- a/src/api/router/auth.rs +++ b/src/api/router/auth.rs @@ -1,10 +1,13 @@ use std::{ any::{Any, TypeId}, collections::BTreeSet, + net::IpAddr, }; use conduwuit::{ - Err, Error, Result, err, + Err, Error, Result, + config::experiments::ToggledExperiment, + err, utils::{IterStream, millis_since_unix_epoch}, }; use http::StatusCode; @@ -18,7 +21,10 @@ use ruma::{ AuthScheme, NoAccessToken, NoAuthentication, }, client, - error::{ErrorKind, InsufficientUserAuthenticationErrorData, UnknownTokenErrorData}, + error::{ + ErrorKind, InsufficientUserAuthenticationErrorData, LimitExceededErrorData, + UnknownTokenErrorData, + }, federation::authentication::ServerSignatures, }, assign, @@ -90,6 +96,7 @@ pub(crate) trait CheckAuth: AuthScheme { fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> impl Future> + Send; @@ -101,6 +108,7 @@ impl CheckAuth for ServerSignatures { async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -161,6 +169,7 @@ impl CheckAuth for AccessToken { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -181,6 +190,7 @@ impl CheckAuth for AccessTokenOptional { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -195,6 +205,10 @@ impl CheckAuth for AccessTokenOptional { .await .map(Some) } else { + if R::RATE_LIMITED { + check_unauthenticated_request_ratelimiting(services, request_ip)?; + } + Ok(None) } } @@ -206,6 +220,7 @@ impl CheckAuth for AppserviceToken { async fn check( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -219,6 +234,7 @@ impl CheckAuth for AppserviceTokenOptional { async fn check + Any>( services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, authentication: Self::Output, _query: AuthQueryParams, ) -> Result { @@ -238,6 +254,7 @@ impl CheckAuth for NoAuthentication { fn check + Any>( _services: &Services, _incoming_request: &hyper::Request<&[u8]>, + _request_ip: IpAddr, _authentication: Self::Output, _query: AuthQueryParams, ) -> impl Future> + Send { @@ -251,6 +268,7 @@ impl CheckAuth for NoAccessToken { async fn check + Any>( services: &Services, incoming_request: &hyper::Request<&[u8]>, + request_ip: IpAddr, _authentication: Self::Output, query: AuthQueryParams, ) -> Result { @@ -267,6 +285,10 @@ impl CheckAuth for NoAccessToken { .await .map(Some) } else { + if R::RATE_LIMITED { + check_unauthenticated_request_ratelimiting(services, request_ip)?; + } + Ok(None) } } @@ -318,17 +340,19 @@ async fn check_access_token( .map(Box::new); // Make sure the user has the right scopes to use the route - let user_scopes = if let Some(session_info) = &session_info { + let mut user_scopes = if let Some(session_info) = &session_info { session_info.scopes() } else { - let mut scopes = BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]); - - if services.admin.user_is_admin(&sender_user).await { - scopes.insert(OAuthClientScope::ServerAdministration); - } - - scopes + BTreeSet::from_iter([OAuthClientScope::ApiFullAccess]) }; + if (!services.config.experiments.msc4484.is_enabled() || session_info.is_none()) + && services.admin.user_is_admin(&sender_user).await + { + // This is required to make sure admin APIs still work when msc4484 + // is disabled. + // https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2533#issuecomment-40042 + user_scopes.insert(OAuthClientScope::ServerAdministration); + } if !required_scopes .iter() @@ -346,7 +370,7 @@ async fn check_access_token( } Ok(ClientIdentity::User { sender_user, sender_device }) - } else if let Ok(appservice_info) = services.appservice.find_from_token(token).await { + } else if let Ok(appservice_info) = services.appservice.find_from_token(token) { let Ok(sender_user) = query.user_id.clone().map_or_else( || { UserId::parse_with_server_name( @@ -379,10 +403,7 @@ async fn check_access_token( .await .is_err() { - return Err!(Request(Forbidden( - "Device does not exist for user or appservice cannot masquerade as this \ - device." - ))); + return Err!(Request(UnknownDevice("Device does not exist for this user."))); } Some(device_id.to_owned()) @@ -405,9 +426,25 @@ async fn check_access_token( } async fn check_appservice_token(services: &Services, token: &str) -> Result { - let Ok(appservice_info) = services.appservice.find_from_token(token).await else { + let Ok(appservice_info) = services.appservice.find_from_token(token) else { return Err!(Request(Unauthorized("Invalid appservice token."))); }; Ok(appservice_info) } + +fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> { + if services + .config + .unauthenticated_request_ratelimit + .check_key(&ip) + .is_err() + { + return Err(Error::BadRequest( + ErrorKind::LimitExceeded(LimitExceededErrorData::new()), + "Rate limit exceeded.", + )); + } + + Ok(()) +} diff --git a/src/api/server/event_auth.rs b/src/api/server/event_auth.rs index 5cd49b834..f4ed82f6d 100644 --- a/src/api/server/event_auth.rs +++ b/src/api/server/event_auth.rs @@ -1,7 +1,10 @@ use std::{borrow::Borrow, iter::once}; use axum::extract::State; -use conduwuit::{Err, Event, Result, info, utils::stream::ReadyExt}; +use conduwuit::{ + Err, Event, Result, info, + utils::stream::{BroadbandExt, ReadyExt}, +}; use futures::StreamExt; use ruma::api::federation::authorization::get_event_authorization; @@ -64,7 +67,9 @@ pub(crate) async fn get_event_authorization_route( .auth_chain .event_ids_iter(&body.room_id, once(body.event_id.borrow())) .ready_filter_map(Result::ok) - .filter_map(|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() }) + .broad_filter_map( + |id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() }, + ) .then(|pdu| services.sending.convert_to_outgoing_federation_event(pdu)) .collect() .await; diff --git a/src/api/server/get_missing_events.rs b/src/api/server/get_missing_events.rs index 7c5b8799f..2842912db 100644 --- a/src/api/server/get_missing_events.rs +++ b/src/api/server/get_missing_events.rs @@ -1,7 +1,7 @@ use std::collections::{HashSet, VecDeque}; use axum::extract::State; -use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn}; +use conduwuit::{Err, Event, Result, debug, debug_warn, info, trace, utils::to_canonical_object}; use ruma::{OwnedEventId, api::federation::event::get_missing_events}; use serde_json::value::RawValue; use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE; @@ -44,6 +44,10 @@ pub(crate) async fn get_missing_events_route( .unwrap_or(10) .min(GET_MISSING_EVENTS_MAX_BATCH_SIZE); + if body.latest_events.len() > limit { + return Err!(Request(InvalidParam("Too many latest_events"))); + } + let room_version = services.rooms.state.get_room_version(&body.room_id).await?; let mut queue: VecDeque = VecDeque::from(body.latest_events.clone()); @@ -64,7 +68,9 @@ pub(crate) async fn get_missing_events_route( let mut pdu = match services.rooms.timeline.get_pdu(&next_event_id).await { | Ok(pdu) => pdu, | Err(e) => { - warn!("could not find event {next_event_id} while walking missing events: {e}"); + debug_warn!( + "could not find event {next_event_id} while walking missing events: {e}" + ); continue; }, }; @@ -74,6 +80,10 @@ pub(crate) async fn get_missing_events_route( body.room_id ))); } + if pdu.depth < body.min_depth { + debug!(%next_event_id, %pdu.depth, %body.min_depth, "event is below minimum depth, not traversing"); + continue; + } if services .rooms .pdu_metadata diff --git a/src/api/server/invite.rs b/src/api/server/invite.rs index 89069e050..a72aceac3 100644 --- a/src/api/server/invite.rs +++ b/src/api/server/invite.rs @@ -209,31 +209,35 @@ async fn create_invite( services.sync.wake(&recipient_user).await; - for appservice in services.appservice.read().await.values() { - if appservice.is_user_match(&recipient_user) { - let transaction_id = general_purpose::URL_SAFE_NO_PAD - .encode(sha256::hash(pdu.event_id.as_bytes())) - .into(); + let matching_appservices: Vec<_> = services + .appservice + .read() + .values() + .filter(|appservice| appservice.is_user_match(&recipient_user)) + .cloned() + .collect(); - let request = ruma::api::appservice::event::push_events::v1::Request::new( - transaction_id, - vec![pdu.to_format()], - ); + for appservice in matching_appservices { + let transaction_id = general_purpose::URL_SAFE_NO_PAD + .encode(sha256::hash(pdu.event_id.as_bytes())) + .into(); - services - .sending - .send_appservice_request(appservice.registration.clone(), request) - .await - .map_err(|e| { - error!( - "failed to notify appservice {} about incoming invite: {e}", - appservice.registration.id - ); - err!(BadServerResponse( - "Failed to notify appservice about incoming invite." - )) - })?; - } + let request = ruma::api::appservice::event::push_events::v1::Request::new( + transaction_id, + vec![pdu.to_format()], + ); + + services + .sending + .send_appservice_request(appservice.registration.clone(), request) + .await + .map_err(|e| { + error!( + "failed to notify appservice {} about incoming invite: {e}", + appservice.registration.id + ); + err!(BadServerResponse("Failed to notify appservice about incoming invite.")) + })?; } } @@ -417,7 +421,6 @@ async fn validate_invite_create_event( if !state_res::auth_check( room_version_rules, pdu, - None, |_, _| async { unreachable!("No state should be fetched when processing a lone create event"); }, diff --git a/src/api/server/key.rs b/src/api/server/key.rs index 19ee6594c..e817d1290 100644 --- a/src/api/server/key.rs +++ b/src/api/server/key.rs @@ -212,15 +212,15 @@ async fn acquire_keys_as_notary( if server_keys.notary_may_contact_origin(&remote) { debug_info!("Asking remote directly for verify keys"); if let Ok(res) = server_keys.origin_request(remote.clone(), start).await - && let Ok(ssk) = sign_ssk(&server_keys, res.clone(), &remote, &my_name).await + && let Ok(ssk) = sign_ssk(&server_keys, res.parsed.clone(), &remote, &my_name).await { let index = results.len(); results.push(ssk); - for key_id in res.verify_keys.keys().chain(res.old_verify_keys.keys()) { + for key_id in res.parsed.verify_keys.keys().chain(res.parsed.old_verify_keys.keys()) { if fetch_all || queries.get(key_id).is_some_and(|c| { c.minimum_valid_until_ts - .is_none_or(|m| res.valid_until_ts >= m) + .is_none_or(|m| res.parsed.valid_until_ts >= m) }) { queries.remove(key_id); keymap.insert(key_id.to_owned(), index); @@ -241,11 +241,11 @@ async fn acquire_keys_as_notary( let my_name = &my_name; let server_keys = &server_keys; async move { - if ssk.valid_until_ts > in_one_week() || ssk.valid_until_ts < start { + if ssk.parsed.valid_until_ts > in_one_week() || ssk.valid_until_ts < start { return None; } - sign_ssk(server_keys, ssk.clone(), server_name, my_name) + sign_ssk(server_keys, ssk.parsed.clone(), server_name, my_name) .await .map(|signed_ssk| (ssk, signed_ssk)) .ok() @@ -254,7 +254,7 @@ async fn acquire_keys_as_notary( .ready_for_each(|(ssk, signed_ssk)| { let idx = results.len(); results.push(signed_ssk); - for key_id in ssk.verify_keys.keys().chain(ssk.old_verify_keys.keys()) { + for key_id in ssk.parsed.verify_keys.keys().chain(ssk.old_verify_keys.keys()) { keymap.insert(key_id.to_owned(), idx); } }) @@ -346,7 +346,7 @@ pub(crate) async fn get_remote_server_keys_route( { return sign_ssk( &services.server_keys, - response, + response.parsed, &body.server_name, services.globals.server_name(), ) @@ -360,13 +360,13 @@ pub(crate) async fn get_remote_server_keys_route( .broad_filter_map(|ssk| { let server_name = body.server_name.clone(); async move { - if ssk.valid_until_ts > in_one_week() || ssk.valid_until_ts < min_valid_ts { + if ssk.parsed.valid_until_ts > in_one_week() || ssk.parsed.valid_until_ts < min_valid_ts { return None; } sign_ssk( &services.server_keys, - ssk, + ssk.parsed, server_name.as_ref(), services.globals.server_name(), ) diff --git a/src/api/server/make_join.rs b/src/api/server/make_join.rs index 411a322f5..aa0e99e37 100644 --- a/src/api/server/make_join.rs +++ b/src/api/server/make_join.rs @@ -1,29 +1,19 @@ -use std::{borrow::ToOwned, pin::pin}; - use axum::extract::State; -use conduwuit::{ - Err, Error, Result, debug, debug_info, info, matrix::pdu::PartialPdu, utils, warn, -}; -use conduwuit_service::Services; -use futures::StreamExt; +use conduwuit::{Err, Error, Result, info, matrix::pdu::PartialPdu, utils}; use ruma::{ - OwnedUserId, RoomId, UserId, + OwnedUserId, api::{ error::{ErrorKind, IncompatibleRoomVersionErrorData}, federation::membership::prepare_join_event, }, assign, - events::{ - StateEventType, - room::{ - join_rules::{AllowRule, JoinRule, RoomJoinRulesEventContent}, - member::{MembershipState, RoomMemberEventContent}, - }, + events::room::{ + join_rules::JoinRule, + member::{MembershipState, RoomMemberEventContent}, }, }; use serde_json::value::to_raw_value; -use service::rooms::state::RoomMutexGuard; -use tokio::join; +use service::rooms::membership::{JoinConditionEntity, JoinConditionResult}; use crate::Ruma; @@ -35,9 +25,6 @@ pub(crate) async fn create_join_event_template_route( State(services): State, body: Ruma, ) -> Result { - if !services.rooms.metadata.exists(&body.room_id).await { - return Err!(Request(NotFound("Room is unknown to this server."))); - } if !services .rooms .state_cache @@ -63,18 +50,6 @@ pub(crate) async fn create_join_event_template_route( .acl_check(&body.identity, &body.room_id) .await?; - if services - .moderation - .is_remote_server_forbidden(&body.identity) - { - warn!( - "Server {} for remote user {} tried joining room ID {} which has a server name that \ - is globally forbidden. Rejecting.", - body.identity, &body.user_id, &body.room_id, - ); - return Err!(Request(Forbidden("Server is banned on this homeserver."))); - } - let room_version = services.rooms.state.get_room_version(&body.room_id).await?; let room_version_rules = room_version.rules().unwrap(); if !body.ver.contains(&room_version) { @@ -87,41 +62,78 @@ pub(crate) async fn create_join_event_template_route( } let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await; - let (is_invited, is_joined) = join!( - services - .rooms - .state_cache - .is_invited(&body.user_id, &body.room_id), - services - .rooms - .state_cache - .is_joined(&body.user_id, &body.room_id) - ); + + let current_membership = services + .rooms + .state_accessor + .get_member(&body.room_id, &body.user_id) + .await + .ok() + .map_or(MembershipState::Leave, |content| content.membership); + let join_authorized_via_users_server: Option = { - if is_joined || is_invited { - // User is already joined or invited and consequently does not need - // an authorising user + if matches!( + current_membership, + MembershipState::Join | MembershipState::Invite | MembershipState::Knock + ) { + // User is already joined, invited, or knocked, and consequently + // does not need an authorising user None } else if !room_version_rules.authorization.restricted_join_rule { - // room version does not support restricted join rules + // Room version does not support restricted join rules None - } else if user_can_perform_restricted_join(&services, &body.user_id, &body.room_id) - .await? - { - Some( - select_authorising_user(&services, &body.room_id, &body.user_id, &state_lock) - .await?, - ) } else { - None + let join_rules = services + .rooms + .state_accessor + .get_join_rules(&body.room_id) + .await; + + if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + join_rules + { + match services + .rooms + .membership + .evaluate_join_conditions( + &body.room_id, + JoinConditionEntity::User(&body.user_id), + &conditions, + ) + .await + { + | JoinConditionResult::Satisfied => { + // Try to find an authorizing user + services + .rooms + .membership + .select_authorizing_user(&body.room_id, &body.user_id, &state_lock) + .await + .map(Some)? + }, + | JoinConditionResult::Unsatisfied => { + return Err!(Request(Forbidden( + "You do not satisfy this room's join conditions." + ))); + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + return Err!(Request(UnableToAuthorizeJoin( + "This server cannot check this room's join conditions." + ))); + }, + } + } else { + None + } } }; - if services.antispam.check_all_joins() && join_authorized_via_users_server.is_none() { + + if services.antispam.check_all_joins() { if services .antispam .meowlnir_accept_make_join(body.room_id.clone(), body.user_id.clone()) .await - .is_err() + != JoinConditionResult::Satisfied { return Err!(Request(Forbidden("Antispam rejected join request."))); } @@ -153,133 +165,3 @@ pub(crate) async fn create_join_event_template_route( }), ) } - -/// Attempts to find a user who is able to issue an invite in the target room. -pub(crate) async fn select_authorising_user<'a>( - services: &Services, - room_id: &'a RoomId, - user_id: &'a UserId, - state_lock: &'a RoomMutexGuard, -) -> Result { - let candidates = services.rooms.state_cache.local_users_in_room(room_id); - - let mut candidates = pin!(candidates); - - while let Some(candidate) = candidates.next().await { - if services - .rooms - .state_accessor - .user_can_invite(room_id, &candidate, user_id, state_lock) - .await - { - return Ok(candidate); - } - } - - Err!(Request(UnableToGrantJoin( - "No user on this server is able to assist in joining." - ))) -} - -/// Checks whether the given user can join the given room via a restricted join. -pub(crate) async fn user_can_perform_restricted_join( - services: &Services, - user_id: &UserId, - room_id: &RoomId, -) -> Result { - let Ok(join_rules_event_content) = services - .rooms - .state_accessor - .room_state_get_content::( - room_id, - &StateEventType::RoomJoinRules, - "", - ) - .await - else { - // No join rules means there's nothing to authorise (defaults to invite) - return Ok(false); - }; - - let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = - join_rules_event_content.join_rule - else { - // This is not a restricted room - return Ok(false); - }; - - if r.allow.is_empty() { - // This will never be authorisable, return forbidden. - return Err!(Request(Forbidden("You are not invited to this room."))); - } - - let mut could_satisfy = true; - for allow_rule in &r.allow { - match allow_rule { - | AllowRule::RoomMembership(membership) => { - if !services - .rooms - .state_cache - .server_in_room(services.globals.server_name(), &membership.room_id) - .await - { - // Since we can't check this room, mark could_satisfy as - // false so that we can return - // M_UNABLE_TO_AUTHORIZE_JOIN later. - could_satisfy = false; - continue; - } - - if services - .rooms - .state_cache - .is_joined(user_id, &membership.room_id) - .await - { - debug!( - "User {} is allowed to join room {} via membership in room {}", - user_id, room_id, membership.room_id - ); - return Ok(true); - } - }, - | other if other.rule_type() == "fi.mau.spam_checker" => - return match services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) - .await - { - | Ok(()) => Ok(true), - | Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))), - }, - | _ => { - // We don't recognise this join rule, so we cannot satisfy the - // request. - could_satisfy = false; - debug_info!( - "Unsupported allow rule in restricted join for room {}: {:?}", - room_id, - allow_rule - ); - }, - } - } - - if could_satisfy { - // We were able to check all the restrictions and can be certain that - // the prospective member is not permitted to join. - Err!(Request(Forbidden( - "You do not belong to any of the rooms or spaces required to join this room." - ))) - } else { - // We were unable to check all the restrictions. This usually means we - // aren't in one of the rooms this one is restricted to, ergo can't - // check its state for the user's membership, and consequently the - // user *might* be able to join if they ask another server. - Err!(Request(UnableToAuthorizeJoin( - "You do not belong to any of the recognised rooms or spaces required to join this \ - room, but this server is unable to verify every requirement. You may be able to \ - join via another server." - ))) - } -} diff --git a/src/api/server/mod.rs b/src/api/server/mod.rs index 5c1ff3f79..b115ccabb 100644 --- a/src/api/server/mod.rs +++ b/src/api/server/mod.rs @@ -18,6 +18,7 @@ pub(super) mod send_knock; pub(super) mod send_leave; pub(super) mod state; pub(super) mod state_ids; +pub(super) mod stripped_state; pub(super) mod user; pub(super) mod version; pub(super) mod well_known; @@ -42,6 +43,7 @@ pub(super) use send_knock::*; pub(super) use send_leave::*; pub(super) use state::*; pub(super) use state_ids::*; +pub(super) use stripped_state::*; pub(super) use user::*; pub(super) use version::*; pub(super) use well_known::*; diff --git a/src/api/server/send.rs b/src/api/server/send.rs index 0a384717f..979fada62 100644 --- a/src/api/server/send.rs +++ b/src/api/server/send.rs @@ -332,6 +332,7 @@ async fn handle_room( room_id: OwnedRoomId, pdus: impl Iterator + Send, ) -> std::result::Result, TransactionError> { + let arrived = millis_since_unix_epoch(); let _room_lock = services .rooms .event_handler @@ -392,7 +393,7 @@ async fn handle_room( .federation_incoming_pdu_duration .record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome)); if let (Ok(()), Some(ts)) = (&result, origin_server_ts) { - let lag = millis_since_unix_epoch().saturating_sub(ts); + let lag = arrived.saturating_sub(ts); instruments .federation_incoming_pdu_lag .record(Duration::from_millis(lag).as_secs_f64(), &[]); @@ -581,28 +582,20 @@ async fn handle_edu_receipt_room_user( } let data = &user_updates.data; - user_updates - .event_ids - .into_iter() - .stream() - .for_each_concurrent(automatic_width(), |event_id| async move { - let user_data = [(user_id.to_owned(), data.clone())]; - let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))]; - let content = [(event_id.clone(), BTreeMap::from(receipts))]; - services - .rooms - .read_receipt - .readreceipt_update( - user_id, - room_id, - ReceiptEvent::new( - room_id.to_owned(), - ReceiptEventContent::from_iter(content), - ), - ) - .await; - }) - .await; + for event_id in user_updates.event_ids { + let user_data = [(user_id.to_owned(), data.clone())]; + let receipts = [(ReceiptType::Read, BTreeMap::from(user_data))]; + let content = [(event_id, BTreeMap::from(receipts))]; + services + .rooms + .read_receipt + .readreceipt_update( + user_id, + room_id, + ReceiptEvent::new(room_id.to_owned(), ReceiptEventContent::from_iter(content)), + ) + .await; + } } async fn handle_edu_typing(services: &Services, origin: &ServerName, typing: TypingContent) { diff --git a/src/api/server/send_join.rs b/src/api/server/send_join.rs index dd9b12e14..d25fd8156 100644 --- a/src/api/server/send_join.rs +++ b/src/api/server/send_join.rs @@ -16,9 +16,11 @@ use ruma::{ TimelineEventType, room::member::{MembershipState, RoomMemberEventContent}, }, + room::JoinRule, room_version_rules::RoomVersionRules, }; use serde_json::value::to_raw_value; +use service::rooms::membership::{JoinConditionEntity, JoinConditionResult}; use crate::{Ruma, server::utils::validate_any_membership_event}; @@ -108,18 +110,56 @@ async fn create_join_event( they cannot authorise your join." ))); } - if !super::user_can_perform_restricted_join(services, &sender, room_id).await? { - return Err!(Request(UnableToAuthorizeJoin( - "Joining user did not pass restricted room's rules." + + // If the user is invited or joined we don't need to check the join + // conditions, but in that case the requesting server shouldn't + // have set `join_authorized_via_users_server` in the first place. + + let join_rules = services.rooms.state_accessor.get_join_rules(room_id).await; + + if let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + join_rules + { + match services + .rooms + .membership + .evaluate_join_conditions( + room_id, + JoinConditionEntity::User(&sender), + &conditions, + ) + .await + { + | JoinConditionResult::Satisfied => { + // Sign the join to prove that we checked the conditions. + + services + .server_keys + .hash_and_sign_event(&mut pdu, room_version_rules) + .map_err(|e| { + err!(Request(InvalidParam(warn!( + "Failed to sign send_join event: {e}" + )))) + })?; + }, + | JoinConditionResult::Unsatisfied => { + return Err!(Request(Forbidden( + "You do not satisfy this room's join conditions." + ))); + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + return Err!(Request(UnableToAuthorizeJoin( + "This server cannot check this room's join conditions." + ))); + }, + } + } else { + // We can't sign this, and if we don't sign it our event will fail + // the auth check, so we have to bail out here. + return Err!(Request(InvalidParam( + "join_authorized_via_users_server was supplied for a room that is not restricted" ))); } - - services - .server_keys - .hash_and_sign_event(&mut pdu, room_version_rules) - .map_err(|e| { - err!(Request(InvalidParam(warn!("Failed to sign send_join event: {e}")))) - })?; } let mutex_lock = services diff --git a/src/api/server/stripped_state.rs b/src/api/server/stripped_state.rs new file mode 100644 index 000000000..8fb0dc83d --- /dev/null +++ b/src/api/server/stripped_state.rs @@ -0,0 +1,54 @@ +use axum::extract::State; +use conduwuit::{Err, Result}; +use ruma::{ + api::federation::event::get_stripped_state, assign, events::ALLOWED_STRIPPED_STATE_EVENTS, +}; +use service::rooms::summary::{Accessibility, RoomStrippedState}; + +use crate::Ruma; + +/// # `POST /_matrix/federation/unstable/org.continuwuity.msc4560.stripped_state/{room_id}` ([MSC4560]) +/// +/// Returns a room's stripped state. +/// +/// [MSC4560]: https://github.com/matrix-org/matrix-spec-proposals/pull/4560 +pub(crate) async fn get_stripped_state_route( + State(services): State, + body: Ruma, +) -> Result { + if let Some(forbidden_type) = body + .state + .iter() + .find(|event_type| !ALLOWED_STRIPPED_STATE_EVENTS.contains(event_type)) + { + return Err!(Request(InvalidParam( + "Event type {forbidden_type} may not be requested as stripped state." + ))); + } + + if services.rooms.metadata.is_banned(&body.room_id).await { + return Err!(Request(Forbidden("This room is banned on this homeserver."))); + } + + match services + .rooms + .summary + .get_local_stripped_state_for_server( + &body.identity, + &body.room_id, + &body.state, + body.num_joined_members, + ) + .await + { + | Accessibility::Accessible(RoomStrippedState { state, num_joined_members, .. }) => Ok( + assign!(get_stripped_state::msc4560::Response::default(), { state, num_joined_members }), + ), + | Accessibility::Inaccessible => { + Err!(Request(Forbidden("You may not access this room's stripped state."))) + }, + | Accessibility::NotFound => { + Err!(Request(NotFound("This room is not known to this server."))) + }, + } +} diff --git a/src/build_metadata/build.rs b/src/build_metadata/build.rs index b605b7578..8e99a85e1 100644 --- a/src/build_metadata/build.rs +++ b/src/build_metadata/build.rs @@ -1,5 +1,10 @@ use std::{ - collections::BTreeMap, env, fmt::Write as FmtWrite, fs, io::Write, path::Path, + collections::BTreeMap, + env, + fmt::Write as FmtWrite, + fs, + io::Write, + path::{Path, PathBuf}, process::Command, }; @@ -130,18 +135,68 @@ fn main() { } // --- Rerun Triggers --- - // TODO: The git rerun triggers seem to always run - // // Rerun if the git HEAD changes - // println!("cargo:rerun-if-changed=.git/HEAD"); - // // Rerun if the ref pointed to by HEAD changes (e.g., new commit on - // branch) if let Some(ref_path) = run_git_command(&["symbolic-ref", - // "--quiet", "HEAD"]) { println!("cargo:rerun-if-changed=.git/{ref_path}" - // ); } + let resolve_git_path = |path_str: &str| -> PathBuf { + let p = Path::new(path_str); + if p.is_absolute() { + p.to_path_buf() + } else { + Path::new(&manifest_dir).join(p) + } + }; + + // If workspace root has a .git file (e.g., git worktree or submodule), + // watch it + let workspace_git = metadata.workspace_root.as_std_path().join(".git"); + if workspace_git.is_file() { + println!("cargo:rerun-if-changed={}", workspace_git.display()); + } + + // Rerun if the git HEAD changes + if let Some(git_head) = run_git_command(&["rev-parse", "--git-path", "HEAD"]) { + let head_path = resolve_git_path(&git_head); + if head_path.exists() { + println!("cargo:rerun-if-changed={}", head_path.display()); + } + } + + // Rerun if the ref pointed to by HEAD changes (e.g., new commit on branch) + if let Some(ref_name) = run_git_command(&["symbolic-ref", "--quiet", "HEAD"]) { + if let Some(git_ref) = run_git_command(&["rev-parse", "--git-path", &ref_name]) { + let ref_path = resolve_git_path(&git_ref); + if ref_path.exists() { + println!("cargo:rerun-if-changed={}", ref_path.display()); + } else { + // If the loose ref file does not exist (e.g. refs are packed), + // watch the nearest existing ancestor directory + // so newly created refs trigger rerun. + let mut dir = ref_path.parent(); + while let Some(d) = dir { + if d.exists() { + println!("cargo:rerun-if-changed={}", d.display()); + break; + } + dir = d.parent(); + } + } + } + } + + // If packed-refs exists, watch it so git pack-refs or updates to packed + // refs trigger rerun + if let Some(git_packed) = run_git_command(&["rev-parse", "--git-path", "packed-refs"]) { + let packed_path = resolve_git_path(&git_packed); + if packed_path.exists() { + println!("cargo:rerun-if-changed={}", packed_path.display()); + } + } println!("cargo:rerun-if-env-changed=GIT_COMMIT_HASH"); println!("cargo:rerun-if-env-changed=GIT_COMMIT_HASH_SHORT"); println!("cargo:rerun-if-env-changed=GIT_REMOTE_URL"); println!("cargo:rerun-if-env-changed=GIT_REMOTE_COMMIT_URL"); + println!("cargo:rerun-if-env-changed=CONTINUWUITY_VERSION_EXTRA"); + println!("cargo:rerun-if-env-changed=CONDUWUIT_VERSION_EXTRA"); + println!("cargo:rerun-if-env-changed=CONDUIT_VERSION_EXTRA"); } fn generate_features_code(features: &BTreeMap>) -> String { diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 109535949..72aae4312 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -20,20 +20,22 @@ crate-type = [ brotli_compression = [ "reqwest/brotli", ] -conduwuit_mods = [ - "dep:libloading" -] gzip_compression = [ "reqwest/gzip", ] -hardened_malloc = [ - "dep:hardened_malloc-rs" -] jemalloc = [ "dep:tikv-jemalloc-sys", "dep:tikv-jemalloc-ctl", "dep:tikv-jemallocator", ] +# Uses mimalloc for Rust allocations and, via `override`, exports +# malloc/free/etc. so C/C++ dependencies (RocksDB, zstd, lz4, ...) use it too. +# Mutually exclusive with `jemalloc` on non-MSVC targets. +mimalloc = [ + "dep:libmimalloc-sys", + "dep:mimalloc", + "libmimalloc-sys/override", +] jemalloc_conf = [] jemalloc_prof = [ "tikv-jemalloc-sys/profiling", @@ -47,8 +49,6 @@ perf_measurements = [] release_max_log_level = [ "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] sentry_telemetry = [] zstd_compression = [ @@ -77,13 +77,11 @@ cyborgtime.workspace = true either.workspace = true figment.workspace = true futures.workspace = true +governor.workspace = true http-body-util.workspace = true http.workspace = true ipaddress.workspace = true libc.workspace = true -libloading.workspace = true -libloading.optional = true -log.workspace = true lettre.workspace = true num-traits.workspace = true rand.workspace = true @@ -120,14 +118,14 @@ lock_api.workspace = true hyper-util.workspace = true resolvematrix.workspace = true openidconnect.workspace = true +libmimalloc-sys.optional = true +libmimalloc-sys.workspace = true +mimalloc.optional = true +mimalloc.workspace = true [target.'cfg(unix)'.dependencies] nix.workspace = true -[target.'cfg(all(not(target_env = "msvc"), target_os = "linux"))'.dependencies] -hardened_malloc-rs.workspace = true -hardened_malloc-rs.optional = true - [dev-dependencies] maplit.workspace = true opentelemetry_sdk.workspace = true diff --git a/src/core/alloc/default.rs b/src/core/alloc/default.rs index 7d6f94e34..23d56e5b2 100644 --- a/src/core/alloc/default.rs +++ b/src/core/alloc/default.rs @@ -1,5 +1,9 @@ //! Default allocator with no special features +use arrayvec::ArrayVec; + +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { None } + /// Always returns Ok pub fn trim>>(_: I) -> crate::Result { Ok(()) } @@ -12,4 +16,4 @@ pub fn memory_stats(_opts: &str) -> Option { None } pub fn memory_usage() -> Option { None } #[must_use] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +pub fn memory_usage_stats() -> Option> { None } diff --git a/src/core/alloc/hardened.rs b/src/core/alloc/hardened.rs deleted file mode 100644 index 69628ba7d..000000000 --- a/src/core/alloc/hardened.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! hmalloc allocator - -#[global_allocator] -static HMALLOC: hardened_malloc_rs::HardenedMalloc = hardened_malloc_rs::HardenedMalloc; - -pub fn trim>>(_: I) -> crate::Result { Ok(()) } - -#[must_use] -//TODO: get usage -pub fn memory_usage() -> Option { None } - -#[must_use] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } - -#[must_use] -pub fn memory_stats(_opts: &str) -> Option { - Some("Extended statistics are not available from hardened_malloc.".to_owned()) -} diff --git a/src/core/alloc/je.rs b/src/core/alloc/je.rs index 584cda823..dc92c1a1e 100644 --- a/src/core/alloc/je.rs +++ b/src/core/alloc/je.rs @@ -1,9 +1,12 @@ //! jemalloc allocator use std::{ - cell::OnceCell, - ffi::{CStr, c_char, c_void}, + any::Any, + ffi::{CStr, CString, c_char, c_uint, c_void}, fmt::Debug, + panic::{self, AssertUnwindSafe}, + ptr, + sync::OnceLock, }; use arrayvec::ArrayVec; @@ -12,26 +15,61 @@ use tikv_jemalloc_sys as ffi; use tikv_jemallocator as jemalloc; use crate::{ - Result, SyncRwLock, err, is_equal_to, is_nonzero, + Result, err, is_equal_to, is_nonzero, utils::{math, math::Tried}, }; #[cfg(feature = "jemalloc_conf")] -#[unsafe(no_mangle)] -pub static malloc_conf: &[u8] = const_str::concat_bytes!( +#[repr(transparent)] +struct MallocConf(*const c_char); + +// SAFETY: MallocConf points to static immutable NUL-terminated bytes. +#[cfg(feature = "jemalloc_conf")] +unsafe impl Sync for MallocConf {} + +#[cfg(feature = "jemalloc_conf")] +const MALLOC_CONF_BYTES: &[u8] = const_str::concat_bytes!( "lg_extent_max_active_fit:4", ",oversize_threshold:16777216", ",tcache_max:2097152", ",dirty_decay_ms:16000", ",muzzy_decay_ms:144000", - ",percpu_arena:percpu", - ",metadata_thp:always", - ",background_thread:true", - ",max_background_threads:-1", + MALLOC_CONF_PLATFORM, MALLOC_CONF_PROF, 0 ); +#[cfg(all(feature = "jemalloc_conf", target_os = "linux"))] +const MALLOC_CONF_PLATFORM: &str = + ",percpu_arena:percpu,metadata_thp:always,background_thread:true"; +#[cfg(all(feature = "jemalloc_conf", not(target_os = "linux")))] +const MALLOC_CONF_PLATFORM: &str = ""; + +// Targets match `NO_UNPREFIXED_MALLOC_TARGETS` in `tikv-jemalloc-sys` when +// `unprefixed_malloc_on_supported_platforms` is enabled. +#[cfg(feature = "jemalloc_conf")] +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr( + any( + target_vendor = "apple", + target_env = "musl", + target_os = "android", + target_os = "dragonfly", + ), + unsafe(export_name = "_rjem_malloc_conf") +)] +#[cfg_attr( + not(any( + target_vendor = "apple", + target_env = "musl", + target_os = "android", + target_os = "dragonfly", + )), + unsafe(no_mangle) +)] +static malloc_conf: MallocConf = MallocConf(MALLOC_CONF_BYTES.as_ptr().cast()); + #[cfg(all(feature = "jemalloc_conf", feature = "jemalloc_prof"))] const MALLOC_CONF_PROF: &str = ",prof_active:false"; #[cfg(all(feature = "jemalloc_conf", not(feature = "jemalloc_prof")))] @@ -39,37 +77,56 @@ const MALLOC_CONF_PROF: &str = ""; #[global_allocator] static JEMALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc; -static CONTROL: SyncRwLock<()> = SyncRwLock::new(()); type Name = ArrayVec; type Key = ArrayVec; const NAME_MAX: usize = 128; const KEY_SEGS: usize = 8; +const ARENA_LIMIT: usize = 4095; +const ARENAS_ALL: usize = 4096; #[ctor::ctor(unsafe)] fn _static_initialization() { - acq_epoch().expect("pre-initialization of jemalloc failed"); - acq_epoch().expect("pre-initialization of jemalloc failed"); + let mut epoch: u64 = 0; + let mut len = size_of::(); + // SAFETY: Pre-initialize jemalloc before main() without touching Rust TLS + // or unwinding across the constructor boundary. + unsafe { + ffi::mallctl( + c"epoch".as_ptr(), + ptr::from_mut(&mut epoch).cast::(), + &raw mut len, + ptr::null_mut(), + 0, + ); + } +} + +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { + Some(( + "continuwuity.jemalloc.memory", + "jemalloc memory statistics, when built with jemalloc_stats", + )) } #[must_use] #[cfg(feature = "jemalloc_stats")] pub fn memory_usage() -> Option { + use std::fmt::Write; + let mibs = |input: usize| { - let kibs = input / 1024; - let kibs = u32::try_from(kibs).unwrap_or_default(); - let kibs = f64::from(kibs); - kibs / 1024.0 + let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); + let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); + f64::from(whole) + f64::from(rem_kibs) / 1024.0 }; - let [allocated, active, mapped, metadata, resident, retained] = - memory_usage_stats()?.map(|(_, bytes)| mibs(bytes)); - Some(format!( - "allocated: {allocated:.2} MiB\nactive: {active:.2} MiB\nmapped: {mapped:.2} \ - MiB\nmetadata: {metadata:.2} MiB\nresident: {resident:.2} MiB\nretained: {retained:.2} \ - MiB\n" - )) + let mut out = String::new(); + for (name, bytes) in memory_usage_stats()? { + writeln!(out, "{name}: {:.2} MiB", mibs(bytes)).ok()?; + } + + Some(out) } #[must_use] @@ -78,184 +135,259 @@ pub fn memory_usage() -> Option { None } #[must_use] #[cfg(feature = "jemalloc_stats")] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { +pub fn memory_usage_stats() -> Option> { use mallctl::stats; - // Acquire the epoch; ensure latest stats are pulled in - acq_epoch().ok()?; + // Advance the epoch; ensure latest stats are pulled in + inc_epoch().ok()?; - Some([ + Some(ArrayVec::from([ ("allocated", stats::allocated::read().unwrap_or_default()), ("active", stats::active::read().unwrap_or_default()), ("mapped", stats::mapped::read().unwrap_or_default()), ("metadata", stats::metadata::read().unwrap_or_default()), ("resident", stats::resident::read().unwrap_or_default()), ("retained", stats::retained::read().unwrap_or_default()), - ]) + ])) } #[must_use] #[cfg(not(feature = "jemalloc_stats"))] -pub fn memory_usage_stats() -> Option<[(&'static str, usize); 6]> { None } +pub fn memory_usage_stats() -> Option> { None } + +struct StatsPrintState { + buf: String, + max_len: usize, + panic: Option>, +} pub fn memory_stats(opts: &str) -> Option { const MAX_LENGTH: usize = 1_048_576; - let mut str = String::new(); - let opaque = std::ptr::from_mut(&mut str).cast::(); - let opts_p: *const c_char = std::ffi::CString::new(opts) - .expect("cstring") - .into_raw() - .cast_const(); + let opts = CString::new(opts).ok()?; - // Acquire the epoch; ensure latest stats are pulled in - acq_epoch().ok()?; + let mut state = StatsPrintState { + buf: String::new(), + max_len: MAX_LENGTH, + panic: None, + }; + let opaque = ptr::from_mut(&mut state).cast::(); - // SAFETY: calls malloc_stats_print() with our string instance which must - // remain in this frame. https://docs.rs/tikv-jemalloc-sys/latest/tikv_jemalloc_sys/fn.malloc_stats_print.html - unsafe { ffi::malloc_stats_print(Some(malloc_stats_cb), opaque, opts_p) }; + // SAFETY: `state` and `opts` remain live in this frame for the duration of + // `malloc_stats_print()`, which invokes `malloc_stats_cb` synchronously. + unsafe { ffi::malloc_stats_print(Some(malloc_stats_cb), opaque, opts.as_ptr()) }; - str.truncate(MAX_LENGTH); + if let Some(payload) = state.panic { + panic::resume_unwind(payload); + } - Some(str) + Some(state.buf) } unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) { - // SAFETY: we have to trust the opaque points to our String - let res: &mut String = unsafe { - opaque - .cast::() - .as_mut() - .expect("failed to cast void* to &mut String") + // SAFETY: `opaque` points to `StatsPrintState` on the caller's stack. + let Some(state) = (unsafe { opaque.cast::().as_mut() }) else { + return; }; - // SAFETY: we have to trust the string is null terminated. + if state.panic.is_some() || msg.is_null() || state.buf.len() >= state.max_len { + return; + } + + // SAFETY: jemalloc guarantees `msg` is a valid NUL-terminated C string. let msg = unsafe { CStr::from_ptr(msg) }; - let msg = String::from_utf8_lossy(msg.to_bytes()); - res.push_str(msg.as_ref()); + if let Err(err) = panic::catch_unwind(AssertUnwindSafe(|| { + let msg = String::from_utf8_lossy(msg.to_bytes()); + let remaining = state.max_len.saturating_sub(state.buf.len()); + if msg.len() <= remaining { + state.buf.push_str(msg.as_ref()); + } else { + if let Some(prefix) = msg.get(..msg.floor_char_boundary(remaining)) { + state.buf.push_str(prefix); + } + state.max_len = state.buf.len(); + } + })) { + state.panic = Some(err); + } } macro_rules! mallctl { - ($name:expr_2021) => {{ - thread_local! { - static KEY: OnceCell = OnceCell::default(); - }; + ($name:literal) => {{ + static KEY: OnceLock = OnceLock::new(); - KEY.with(|once| { - once.get_or_init(move || key($name).expect("failed to translate name into mib key")) - .clone() - }) + KEY.get_or_init(|| key($name).expect("failed to translate name into mib key")) }}; } pub mod this_thread { - use super::{Debug, Key, OnceCell, Result, is_nonzero, key, math}; - - thread_local! { - static ALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; - static DEALLOCATED_BYTES: OnceCell<&'static u64> = const { OnceCell::new() }; - } + use super::{Debug, Key, OnceLock, Result, c_uint, is_nonzero, key, math}; pub fn trim() -> Result { decay().and_then(|()| purge()) } - pub fn purge() -> Result { notify(mallctl!("arena.0.purge")) } + pub fn purge() -> Result { + // SAFETY: `arena..purge` is an `arena..*` notification ctl. + unsafe { notify(mallctl!("arena.0.purge")) } + } - pub fn decay() -> Result { notify(mallctl!("arena.0.decay")) } + pub fn decay() -> Result { + // SAFETY: `arena..decay` is an `arena..*` notification ctl. + unsafe { notify(mallctl!("arena.0.decay")) } + } - pub fn idle() -> Result { super::notify(&mallctl!("thread.idle")) } + pub fn idle() -> Result { + // SAFETY: `thread.idle` is a non-indexed notification ctl. + unsafe { super::notify(mallctl!("thread.idle")) } + } - pub fn flush() -> Result { super::notify(&mallctl!("thread.tcache.flush")) } + pub fn flush() -> Result { + // SAFETY: `thread.tcache.flush` is a non-indexed notification ctl. + unsafe { super::notify(mallctl!("thread.tcache.flush")) } + } pub fn set_muzzy_decay(decay_ms: isize) -> Result { - set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms) + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + unsafe { set(mallctl!("arena.0.muzzy_decay_ms"), decay_ms) } } - pub fn get_muzzy_decay() -> Result { get(mallctl!("arena.0.muzzy_decay_ms")) } + pub fn get_muzzy_decay() -> Result { + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + unsafe { get(mallctl!("arena.0.muzzy_decay_ms")) } + } pub fn set_dirty_decay(decay_ms: isize) -> Result { - set(mallctl!("arena.0.dirty_decay_ms"), decay_ms) + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + unsafe { set(mallctl!("arena.0.dirty_decay_ms"), decay_ms) } } - pub fn get_dirty_decay() -> Result { get(mallctl!("arena.0.dirty_decay_ms")) } + pub fn get_dirty_decay() -> Result { + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + unsafe { get(mallctl!("arena.0.dirty_decay_ms")) } + } pub fn cache_enable(enable: bool) -> Result { - super::set::(&mallctl!("thread.tcache.enabled"), enable.into()).map(is_nonzero!()) + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on + // non-MSVC). + unsafe { super::set::(mallctl!("thread.tcache.enabled"), enable.into()) } + .map(is_nonzero!()) } pub fn is_cache_enabled() -> Result { - super::get::(&mallctl!("thread.tcache.enabled")).map(is_nonzero!()) + // SAFETY: `thread.tcache.enabled` has C type `bool` (1 byte on + // non-MSVC). + unsafe { super::get::(mallctl!("thread.tcache.enabled")) }.map(is_nonzero!()) } pub fn set_arena(id: usize) -> Result { - super::set::(&mallctl!("thread.arena"), id.try_into()?).and_then(math::try_into) + // SAFETY: `thread.arena` has C type `unsigned`. + unsafe { super::set::(mallctl!("thread.arena"), id.try_into()?) } + .and_then(math::try_into) } pub fn arena_id() -> Result { - super::get::(&mallctl!("thread.arena")).and_then(math::try_into) + // SAFETY: `thread.arena` has C type `unsigned`. + unsafe { super::get::(mallctl!("thread.arena")) }.and_then(math::try_into) } pub fn prof_enable(enable: bool) -> Result { - super::set::(&mallctl!("thread.prof.active"), enable.into()).map(is_nonzero!()) + // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { super::set::(mallctl!("thread.prof.active"), enable.into()) } + .map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { - super::get::(&mallctl!("thread.prof.active")).map(is_nonzero!()) + // SAFETY: `thread.prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { super::get::(mallctl!("thread.prof.active")) }.map(is_nonzero!()) } - pub fn reset_peak() -> Result { super::notify(&mallctl!("thread.peak.reset")) } + pub fn reset_peak() -> Result { + // SAFETY: `thread.peak.reset` is a non-indexed notification ctl. + unsafe { super::notify(mallctl!("thread.peak.reset")) } + } - pub fn peak() -> Result { super::get(&mallctl!("thread.peak.read")) } + pub fn peak() -> Result { + // SAFETY: `thread.peak.read` has C type `uint64_t`. + unsafe { super::get(mallctl!("thread.peak.read")) } + } #[inline] #[must_use] pub fn allocated() -> u64 { - *ALLOCATED_BYTES.with(|once| init_tls_cell(once, "thread.allocatedp")) + // SAFETY: `thread.allocated` has C type `uint64_t`. + unsafe { super::get(mallctl!("thread.allocated")) }.unwrap_or_default() } #[inline] #[must_use] pub fn deallocated() -> u64 { - *DEALLOCATED_BYTES.with(|once| init_tls_cell(once, "thread.deallocatedp")) + // SAFETY: `thread.deallocated` has C type `uint64_t`. + unsafe { super::get(mallctl!("thread.deallocated")) }.unwrap_or_default() } - fn notify(key: Key) -> Result { super::notify_by_arena(Some(arena_id()?), key) } + /// # Safety + /// Caller must ensure `key` is an `arena..*` notification MIB + /// (`key.len() >= 2`). + unsafe fn notify(key: &Key) -> Result { + let mut key = key.clone(); + // `arena_id()` returns this thread's own valid arena (< narenas < + // ARENA_LIMIT), so we skip `validate_arena_id()` to avoid locking + // `ctl_mtx` on hot paths like `decay()`. + key[1] = arena_id()?; + // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB + // and `arena_id()` returns a valid arena index. + unsafe { super::notify(&key) } + } - fn set(key: Key, val: T) -> Result + /// # Safety + /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its + /// exact C type. + unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, { - super::set_by_arena(Some(arena_id()?), key, val) + let mut key = key.clone(); + // `arena_id()` is already a valid arena index; skip + // `validate_arena_id()`. + key[1] = arena_id()?; + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { super::set(&key, val) } } - fn get(key: Key) -> Result + /// # Safety + /// Caller must ensure `key` is an `arena..*` MIB and `T` matches its + /// exact C type. + unsafe fn get(key: &Key) -> Result where T: Copy + Debug, { - super::get_by_arena(Some(arena_id()?), key) - } - - fn init_tls_cell(cell: &OnceCell<&'static u64>, name: &str) -> &'static u64 { - cell.get_or_init(|| { - let ptr: *const u64 = super::get(&mallctl!(name)).expect("failed to obtain pointer"); - - // SAFETY: ptr points directly to the internal state of jemalloc for - // this thread - unsafe { ptr.as_ref() }.expect("pointer must not be null") - }) + let mut key = key.clone(); + // `arena_id()` is already a valid arena index; skip + // `validate_arena_id()`. + key[1] = arena_id()?; + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { super::get(&key) } } } -pub fn stats_reset() -> Result { notify(&mallctl!("stats.mutexes.reset")) } +pub fn stats_reset() -> Result { + // SAFETY: `stats.mutexes.reset` is a non-indexed notification ctl. + unsafe { notify(mallctl!("stats.mutexes.reset")) } +} -pub fn prof_reset() -> Result { notify(&mallctl!("prof.reset")) } +pub fn prof_reset() -> Result { + // SAFETY: `prof.reset` is a non-indexed notification ctl. + unsafe { notify(mallctl!("prof.reset")) } +} pub fn prof_enable(enable: bool) -> Result { - set::(&mallctl!("prof.active"), enable.into()).map(is_nonzero!()) + // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { set::(mallctl!("prof.active"), enable.into()) }.map(is_nonzero!()) } pub fn is_prof_enabled() -> Result { - get::(&mallctl!("prof.active")).map(is_nonzero!()) + // SAFETY: `prof.active` has C type `bool` (1 byte on non-MSVC). + unsafe { get::(mallctl!("prof.active")) }.map(is_nonzero!()) } pub fn trim> + Copy>(arena: I) -> Result { @@ -263,31 +395,40 @@ pub fn trim> + Copy>(arena: I) -> Result { } pub fn purge>>(arena: I) -> Result { - notify_by_arena(arena.into(), mallctl!("arena.4096.purge")) + // SAFETY: `arena..purge` is an `arena..*` notification ctl. + unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.purge")) } } pub fn decay>>(arena: I) -> Result { - notify_by_arena(arena.into(), mallctl!("arena.4096.decay")) + // SAFETY: `arena..decay` is an `arena..*` notification ctl. + unsafe { notify_by_arena(arena.into(), mallctl!("arena.4096.decay")) } } pub fn set_muzzy_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => - set_by_arena(Some(arena), mallctl!("arena.4096.muzzy_decay_ms"), decay_ms), - | _ => set(&mallctl!("arenas.muzzy_decay_ms"), decay_ms), + // SAFETY: `arena..muzzy_decay_ms` has C type `ssize_t`. + | Some(arena) => unsafe { + set_by_arena(arena, mallctl!("arena.0.muzzy_decay_ms"), decay_ms) + }, + // SAFETY: `arenas.muzzy_decay_ms` has C type `ssize_t`. + | _ => unsafe { set(mallctl!("arenas.muzzy_decay_ms"), decay_ms) }, } } pub fn set_dirty_decay>>(arena: I, decay_ms: isize) -> Result { match arena.into() { - | Some(arena) => - set_by_arena(Some(arena), mallctl!("arena.4096.dirty_decay_ms"), decay_ms), - | _ => set(&mallctl!("arenas.dirty_decay_ms"), decay_ms), + // SAFETY: `arena..dirty_decay_ms` has C type `ssize_t`. + | Some(arena) => unsafe { + set_by_arena(arena, mallctl!("arena.0.dirty_decay_ms"), decay_ms) + }, + // SAFETY: `arenas.dirty_decay_ms` has C type `ssize_t`. + | _ => unsafe { set(mallctl!("arenas.dirty_decay_ms"), decay_ms) }, } } pub fn background_thread_enable(enable: bool) -> Result { - set::(&mallctl!("background_thread"), enable.into()).map(is_nonzero!()) + // SAFETY: `background_thread` has C type `bool` (1 byte on non-MSVC). + unsafe { set::(mallctl!("background_thread"), enable.into()) }.map(is_nonzero!()) } #[inline] @@ -303,83 +444,138 @@ pub fn is_percpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("percp pub fn is_phycpu_arena() -> bool { percpu_arenas().is_ok_and(is_equal_to!("phycpu")) } pub fn percpu_arenas() -> Result<&'static str> { - let ptr = get::<*const c_char>(&mallctl!("opt.percpu_arena"))?; - //SAFETY: ptr points to a null-terminated string returned for - // opt.percpu_arena. + // SAFETY: `opt.percpu_arena` has C type `const char *`. + let ptr = unsafe { get::<*const c_char>(mallctl!("opt.percpu_arena")) }?; + if ptr.is_null() { + return Err(err!("mallctl: opt.percpu_arena returned NULL")); + } + + // SAFETY: `ptr` is non-null and points to a static NUL-terminated string + // returned by jemalloc for `opt.percpu_arena`. let cstr = unsafe { CStr::from_ptr(ptr) }; cstr.to_str().map_err(Into::into) } pub fn arenas() -> Result { - get::(&mallctl!("arenas.narenas")).and_then(math::try_into) + // SAFETY: `arenas.narenas` has C type `unsigned`. + unsafe { get::(mallctl!("arenas.narenas")) }.and_then(math::try_into) } -pub fn inc_epoch() -> Result { xchg(&mallctl!("epoch"), 1_u64) } - -pub fn acq_epoch() -> Result { xchg(&mallctl!("epoch"), 0_u64) } - -fn notify_by_arena(id: Option, mut key: Key) -> Result { - key[1] = id.unwrap_or(4096); - notify(&key) +pub fn inc_epoch() -> Result { + // SAFETY: `epoch` has C type `uint64_t`. + unsafe { xchg(mallctl!("epoch"), 1_u64) } } -fn set_by_arena(id: Option, mut key: Key, val: T) -> Result +pub fn acq_epoch() -> Result { + // SAFETY: `epoch` has C type `uint64_t`. + unsafe { get(mallctl!("epoch")) } +} + +fn validate_arena_id(id: usize, allow_all: bool) -> Result { + if allow_all && id == ARENAS_ALL { + return Ok(id); + } + + let narenas = arenas()?.min(ARENA_LIMIT); + if id < narenas { + Ok(id) + } else { + Err(err!("mallctl: invalid arena index {id} (narenas: {narenas})")) + } +} + +/// # Safety +/// Caller must ensure `key` is an `arena..*` notification MIB +/// (`key.len() >= 2`). +unsafe fn notify_by_arena(id: Option, key: &Key) -> Result { + let mut key = key.clone(); + key[1] = match id { + | Some(id) => validate_arena_id(id, true)?, + | None => ARENAS_ALL, + }; + // SAFETY: Caller guarantees `key` is an `arena..*` notification MIB and + // `key[1]` has been validated above. + unsafe { notify(&key) } +} + +/// # Safety +/// Caller must ensure `key` is an `arena..*` MIB (`key.len() >= 2`) and `T` +/// matches its exact C type. +unsafe fn set_by_arena(id: usize, key: &Key, val: T) -> Result where T: Copy + Debug, { - key[1] = id.unwrap_or(4096); - set(&key, val) + let mut key = key.clone(); + key[1] = validate_arena_id(id, false)?; + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { set(&key, val) } } -fn get_by_arena(id: Option, mut key: Key) -> Result +/// # Safety +/// Caller must ensure `key` is a valid notification MIB and any indexed arena +/// component is within bounds. +unsafe fn notify(key: &Key) -> Result { + // SAFETY: jemalloc notification ctls require `oldp`, `oldlenp`, and `newp` + // to be NULL and `newlen` to be 0 (otherwise `EPERM` is returned). + let ret = unsafe { + ffi::mallctlbymib( + key.as_ptr(), + key.len(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + 0, + ) + }; + if ret == 0 { + Ok(()) + } else { + Err(err!("mallctl: {}", std::io::Error::from_raw_os_error(ret))) + } +} + +/// Does not advance `epoch`; callers reading cached `stats.*` must call +/// `inc_epoch()` explicitly. +/// +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. +unsafe fn set(key: &Key, val: T) -> Result where T: Copy + Debug, { - key[1] = id.unwrap_or(4096); - get(&key) -} - -fn notify(key: &Key) -> Result { xchg(key, ()) } - -fn set(key: &Key, val: T) -> Result -where - T: Copy + Debug, -{ - let _lock = CONTROL.write(); - let res = xchg(key, val)?; - inc_epoch()?; - - Ok(res) + // SAFETY: Caller guarantees `T` matches `key`. + unsafe { xchg(key, val) } } +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. #[tracing::instrument( name = "get", level = "trace", skip_all, fields(?key) )] -fn get(key: &Key) -> Result +unsafe fn get(key: &Key) -> Result where T: Copy + Debug, { - acq_epoch()?; - acq_epoch()?; - - // SAFETY: T must be perfectly valid to receive value. + // SAFETY: Caller guarantees `T` matches the C type returned for `key`. unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err) } +/// # Safety +/// Caller must ensure `T` matches the exact C type expected by `key`. #[tracing::instrument( name = "xchg", level = "trace", skip_all, fields(?key, ?val) )] -fn xchg(key: &Key, val: T) -> Result +unsafe fn xchg(key: &Key, val: T) -> Result where T: Copy + Debug, { - // SAFETY: T must be the exact expected type. + // SAFETY: Caller guarantees `T` matches the C type expected by `key`. unsafe { mallctl::raw::update_mib(key.as_slice(), val) }.map_err(map_err) } @@ -387,6 +583,9 @@ fn key(name: &str) -> Result { // tikv asserts the output buffer length is tight to the number of required // mibs so we slice that down here. let segs = name.chars().filter(is_equal_to!(&'.')).count().try_add(1)?; + if segs > KEY_SEGS { + return Err(err!("mallctl: key has too many segments ({segs} > {KEY_SEGS})")); + } let name = self::name(name)?; let mut buf = [0_usize; KEY_SEGS]; @@ -396,6 +595,10 @@ fn key(name: &str) -> Result { } fn name(name: &str) -> Result { + if name.as_bytes().contains(&0) { + return Err(err!("mallctl: key contains interior NUL byte")); + } + let mut buf = Name::new(); buf.try_extend_from_slice(name.as_bytes())?; buf.try_extend_from_slice(b"\0")?; @@ -406,3 +609,100 @@ fn name(name: &str) -> Result { fn map_err(error: tikv_jemalloc_ctl::Error) -> crate::Error { err!("mallctl: {}", error.to_string()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notify_ctls_succeed() { + this_thread::flush().expect("thread.tcache.flush"); + this_thread::decay().expect("arena..decay"); + this_thread::purge().expect("arena..purge"); + this_thread::trim().expect("this_thread::trim"); + trim(None).expect("trim(None)"); + } + + #[test] + #[cfg(feature = "jemalloc_stats")] + fn allocated_and_deallocated_do_not_alias() { + let a0 = this_thread::allocated(); + let d0 = this_thread::deallocated(); + + let buf = std::hint::black_box(vec![0_u8; 64 * 1024]); + let a1 = this_thread::allocated(); + assert!(a1 > a0, "expected allocated to increase: {a0} -> {a1}"); + + drop(buf); + let d1 = this_thread::deallocated(); + assert!(d1 > d0, "expected deallocated to increase: {d0} -> {d1}"); + } + + #[test] + fn memory_stats_handles_valid_and_nul_opts() { + assert!(memory_stats("invalid\0opts").is_none()); + let stats = memory_stats("gmal").expect("memory_stats"); + assert!(!stats.is_empty()); + } + + #[test] + fn key_too_many_segments_returns_err() { key("a.b.c.d.e.f.g.h.i").unwrap_err(); } + + #[test] + fn key_interior_nul_returns_err() { key("a.b\0.c").unwrap_err(); } + + #[test] + fn arena_index_bounds_rejected() { + purge(Some(ARENAS_ALL)).expect("purge(MALLCTL_ARENAS_ALL)"); + decay(Some(ARENAS_ALL)).expect("decay(MALLCTL_ARENAS_ALL)"); + + let narenas = arenas().expect("arenas.narenas"); + purge(Some(narenas)).unwrap_err(); + decay(Some(narenas)).unwrap_err(); + set_dirty_decay(Some(narenas), -1).unwrap_err(); + set_muzzy_decay(Some(narenas), -1).unwrap_err(); + + purge(Some(4097)).unwrap_err(); + decay(Some(4097)).unwrap_err(); + trim(Some(4097)).unwrap_err(); + purge(Some(usize::MAX)).unwrap_err(); + + set_dirty_decay(Some(ARENAS_ALL), -1).unwrap_err(); + set_muzzy_decay(Some(ARENAS_ALL), -1).unwrap_err(); + set_dirty_decay(Some(4097), -1).unwrap_err(); + set_muzzy_decay(Some(4097), -1).unwrap_err(); + } + + #[test] + #[cfg(feature = "jemalloc_conf")] + fn malloc_conf_is_applied() { + if std::env::var_os("MALLOC_CONF").is_some() + || std::env::var_os("_RJEM_MALLOC_CONF").is_some() + { + return; + } + + // SAFETY: `opt.dirty_decay_ms` and `opt.muzzy_decay_ms` have C type + // `ssize_t`. + let dirty = + unsafe { get::(mallctl!("opt.dirty_decay_ms")) }.expect("opt.dirty_decay_ms"); + // SAFETY: Same as above + let muzzy = + unsafe { get::(mallctl!("opt.muzzy_decay_ms")) }.expect("opt.muzzy_decay_ms"); + assert_eq!(dirty, 16_000, "expected malloc_conf dirty_decay_ms:16000"); + assert_eq!(muzzy, 144_000, "expected malloc_conf muzzy_decay_ms:144000"); + } + + #[test] + fn percpu_arenas_returns_valid_mode() { + let mode = percpu_arenas().expect("opt.percpu_arena"); + assert!(matches!(mode, "disabled" | "percpu" | "phycpu"), "unexpected mode: {mode}"); + } + + #[test] + fn epoch_read_and_advance() { + let e0 = acq_epoch().expect("acq_epoch"); + let e1 = inc_epoch().expect("inc_epoch"); + assert!(e1 > e0, "expected inc_epoch to advance epoch: {e0} -> {e1}"); + } +} diff --git a/src/core/alloc/mimalloc.rs b/src/core/alloc/mimalloc.rs new file mode 100644 index 000000000..495fc0879 --- /dev/null +++ b/src/core/alloc/mimalloc.rs @@ -0,0 +1,234 @@ +//! mimalloc allocator + +use std::{ + any::Any, + ffi::{CStr, c_void}, + panic::{self, AssertUnwindSafe}, + ptr, +}; + +use arrayvec::ArrayVec; +use libmimalloc_sys as ffi; +use mimalloc::MiMalloc; +use serde::Deserialize; + +#[global_allocator] +static MIMALLOC: MiMalloc = MiMalloc; + +#[derive(Deserialize)] +struct StatCount { + current: i64, + peak: i64, +} + +#[derive(Deserialize)] +struct Stats { + reserved: StatCount, + committed: StatCount, + purged: i64, + reset: i64, +} + +trait OutputFnChar { + type Char; +} + +impl OutputFnChar for Option { + type Char = C; +} + +type MiChar = ::Char; + +struct StatsPrintState { + buf: String, + max_len: usize, + panic: Option>, +} + +pub(crate) fn metric() -> Option<(&'static str, &'static str)> { + Some(("continuwuity.mimalloc.memory", "mimalloc memory statistics")) +} + +pub fn trim>>(_: I) -> crate::Result { + // SAFETY: `mi_collect` is thread-safe and takes a single boolean flag. + unsafe { ffi::mi_collect(true) }; + + Ok(()) +} + +fn read_stats() -> Option { + let stats = MiMalloc::stats_json().ok()?; + let json = stats.to_str().ok()?; + serde_json::from_str(json).ok() +} + +fn non_neg_usize(value: i64) -> usize { usize::try_from(value.max(0)).unwrap_or(usize::MAX) } + +fn mibs(input: usize) -> f64 { + let whole = u32::try_from(input / (1024 * 1024)).unwrap_or(u32::MAX); + let rem_kibs = u32::try_from((input / 1024) % 1024).unwrap_or_default(); + f64::from(whole) + f64::from(rem_kibs) / 1024.0 +} + +#[must_use] +pub fn memory_usage() -> Option { + let stats = read_stats()?; + + Some(format!( + "reserved: {:.2} MiB\nreserved_peak: {:.2} MiB\ncommitted: {:.2} MiB\ncommitted_peak: \ + {:.2} MiB\npurged_total: {:.2} MiB\nreset_total: {:.2} MiB\n", + mibs(non_neg_usize(stats.reserved.current)), + mibs(non_neg_usize(stats.reserved.peak)), + mibs(non_neg_usize(stats.committed.current)), + mibs(non_neg_usize(stats.committed.peak)), + mibs(non_neg_usize(stats.purged)), + mibs(non_neg_usize(stats.reset)), + )) +} + +#[must_use] +pub fn memory_usage_stats() -> Option> { + let stats = read_stats()?; + let mut out = ArrayVec::new(); + out.extend([ + ("reserved", non_neg_usize(stats.reserved.current)), + ("reserved_peak", non_neg_usize(stats.reserved.peak)), + ("committed", non_neg_usize(stats.committed.current)), + ("committed_peak", non_neg_usize(stats.committed.peak)), + ]); + + Some(out) +} + +#[must_use] +pub fn memory_stats(opts: &str) -> Option { + const MAX_LENGTH: usize = 1_048_576; + + if opts.contains('\0') { + return None; + } + + if opts.contains('J') { + let stats = MiMalloc::stats_json().ok()?; + let json = String::from_utf8_lossy(stats.to_bytes()); + let end = json.floor_char_boundary(json.len().min(MAX_LENGTH)); + return json.get(..end).map(str::to_owned); + } + + let mut state = StatsPrintState { + buf: String::new(), + max_len: MAX_LENGTH, + panic: None, + }; + let opaque = ptr::from_mut(&mut state).cast::(); + + // SAFETY: `state` remains live in this frame for the duration of + // `mi_stats_print_out()`, which invokes `mi_stats_cb` synchronously. + unsafe { ffi::mi_stats_print_out(Some(mi_stats_cb), opaque) }; + + if let Some(payload) = state.panic { + panic::resume_unwind(payload); + } + + Some(state.buf) +} + +unsafe extern "C" fn mi_stats_cb(msg: *const MiChar, arg: *mut c_void) { + // SAFETY: `arg` points to `StatsPrintState` on the caller's stack. + let Some(state) = (unsafe { arg.cast::().as_mut() }) else { + return; + }; + + if state.panic.is_some() || msg.is_null() || state.buf.len() >= state.max_len { + return; + } + + // SAFETY: mimalloc guarantees `msg` is a valid NUL-terminated C string. + let msg = unsafe { CStr::from_ptr(msg.cast()) }; + + if let Err(err) = panic::catch_unwind(AssertUnwindSafe(|| { + let msg = String::from_utf8_lossy(msg.to_bytes()); + let remaining = state.max_len.saturating_sub(state.buf.len()); + if msg.len() <= remaining { + state.buf.push_str(msg.as_ref()); + } else { + if let Some(prefix) = msg.get(..msg.floor_char_boundary(remaining)) { + state.buf.push_str(prefix); + } + state.max_len = state.buf.len(); + } + })) { + state.panic = Some(err); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_succeeds() { trim(None).expect("trim(None)"); } + + #[test] + fn non_neg_usize_clamps_negative_values() { + assert_eq!(non_neg_usize(-1), 0, "expected -1 to clamp to 0"); + assert_eq!(non_neg_usize(i64::MIN), 0, "expected i64::MIN to clamp to 0"); + assert_eq!(non_neg_usize(0), 0, "expected 0 to remain 0"); + assert_eq!(non_neg_usize(4096), 4096, "expected positive value unchanged"); + } + + #[test] + fn memory_usage_stats_reports_allocator_bytes() { + let buf = std::hint::black_box(vec![0_u8; 64 * 1024]); + let stats = memory_usage_stats().expect("memory_usage_stats"); + drop(buf); + + let keys: Vec<_> = stats.iter().map(|&(key, _)| key).collect(); + assert_eq!( + keys, + ["reserved", "reserved_peak", "committed", "committed_peak"], + "unexpected stat keys" + ); + + for (key, bytes) in stats { + assert!(bytes > 0, "expected {key} > 0, got {bytes}"); + } + } + + #[test] + fn memory_usage_returns_allocator_summary() { + let usage = memory_usage().expect("memory_usage"); + for expected in [ + "reserved:", + "reserved_peak:", + "committed:", + "committed_peak:", + "purged_total:", + "reset_total:", + "MiB", + ] { + assert!(usage.contains(expected), "missing {expected:?} in usage:\n{usage}"); + } + assert!(!usage.contains("current_rss:"), "unexpected current_rss in usage:\n{usage}"); + assert!(!usage.contains("peak_rss:"), "unexpected peak_rss in usage:\n{usage}"); + } + + #[test] + fn memory_stats_supports_text_json_and_rejects_nul() { + assert!(memory_stats("invalid\0opts").is_none(), "expected NUL opts to return None"); + + for opts in ["", "abcdefghijklmnopqrstuvwxyz"] { + let stats = memory_stats(opts).expect("memory_stats text"); + assert!(!stats.is_empty(), "expected non-empty stats for opts={opts:?}"); + assert!(!stats.starts_with('{'), "expected formatted text, got JSON:\n{stats}"); + assert!(stats.contains("reserved"), "missing reserved in stats:\n{stats}"); + assert!(stats.contains("committed"), "missing committed in stats:\n{stats}"); + } + + let json = memory_stats("J").expect("memory_stats JSON"); + assert!(json.starts_with('{'), "expected JSON object, got:\n{json}"); + let parsed: serde_json::Value = + serde_json::from_str(&json).expect("expected valid JSON from memory_stats(\"J\")"); + assert!(parsed.get("committed").is_some(), "expected committed field in JSON"); + } +} diff --git a/src/core/alloc/mod.rs b/src/core/alloc/mod.rs index a34809412..c7e8dd49d 100644 --- a/src/core/alloc/mod.rs +++ b/src/core/alloc/mod.rs @@ -4,24 +4,24 @@ #[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub mod je; #[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] +pub(crate) use je::metric; +#[cfg(all(not(target_env = "msvc"), feature = "jemalloc"))] pub use je::{memory_stats, memory_usage, memory_usage_stats, trim}; -#[cfg(all(not(target_env = "msvc"), feature = "hardened_malloc", not(feature = "jemalloc")))] -pub mod hardened; -#[cfg(all( - not(target_env = "msvc"), - feature = "hardened_malloc", - not(feature = "jemalloc") -))] -pub use hardened::{memory_stats, memory_usage, memory_usage_stats, trim}; +// mimalloc +#[cfg(all(feature = "mimalloc", feature = "jemalloc", not(target_env = "msvc")))] +compile_error!("the `mimalloc` and `jemalloc` features are mutually exclusive"); +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +pub mod mimalloc; +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +pub(crate) use mimalloc::metric; +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +pub use mimalloc::{memory_stats, memory_usage, memory_usage_stats, trim}; -#[cfg(any( - target_env = "msvc", - all(not(feature = "hardened_malloc"), not(feature = "jemalloc")) -))] +// default +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub mod default; -#[cfg(any( - target_env = "msvc", - all(not(feature = "hardened_malloc"), not(feature = "jemalloc")) -))] +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] +pub(crate) use default::metric; +#[cfg(all(not(feature = "mimalloc"), any(target_env = "msvc", not(feature = "jemalloc"))))] pub use default::{memory_stats, memory_usage, memory_usage_stats, trim}; diff --git a/src/core/config/check.rs b/src/core/config/check.rs index 1e3efdb5e..146e149e7 100644 --- a/src/core/config/check.rs +++ b/src/core/config/check.rs @@ -5,7 +5,7 @@ use figment::Figment; use ruma::{OwnedServerName, events::room::server_acl::RoomServerAclEventContent}; use super::DEPRECATED_KEYS; -use crate::{Config, Err, Result, Server, debug, debug_info, debug_warn, error, warn}; +use crate::{Config, Err, Result, Server, debug, debug_info, error, warn}; /// Performs check() with additional checks specific to reloading old config /// with new config. @@ -43,13 +43,6 @@ pub fn check(config: &Config) -> Result { )); } - if cfg!(all(feature = "hardened_malloc", feature = "jemalloc", not(target_env = "msvc"))) { - debug_warn!( - "hardened_malloc and jemalloc compile-time features are both enabled, this causes \ - jemalloc to be used." - ); - } - if cfg!(not(unix)) && config.unix_socket_path.is_some() { return Err!(Config( "unix_socket_path", diff --git a/src/core/config/experiments.rs b/src/core/config/experiments.rs new file mode 100644 index 000000000..5d67ef994 --- /dev/null +++ b/src/core/config/experiments.rs @@ -0,0 +1,194 @@ +use conduwuit_macros::config_example_generator; +use serde::Deserialize; + +/// Configuration for experimental features. +#[derive(Debug, Deserialize, Default, Clone)] +#[config_example_generator( + filename = "conduwuit-example.toml", + section = "global.experiments", + subheader = r##"# Continuwuity's experimental features are frequently updated. +# If you got this configuration via a package manager, chances are it's outdated. +# Check out the configuration reference online to see a fresh version: +# https://continuwuity.org/reference/config.html#:~:text=global.experiments +# +# Please keep in mind that experiments are used to enable unstable features. +# You probably don't need to enable any of these unless you know what they are, +# and consequently know why you should enable them."## +)] +pub struct Experiments { + /// MSC2815: Proposal to allow room moderators to view redacted event + /// content + /// + /// See [`MSC2815`] for details. + /// + /// display: nested + #[serde(default)] + pub msc2815: Option, + /// MSC3814: Dehydrated devices with SSSS + /// + /// Enables server-side support for "dehydrated devices", which are + /// server-side devices (created by supporting clients) that can collect + /// encryption keys when there are no online devices, which supporting + /// clients can then "hydrate" to download any encryption keys that were + /// sent while they were offline. + /// + /// Important: this is NOT required to receive encrypted messages while you + /// are offline. Devices can still receive encrypted messages while they are + /// offline, but to share those keys with new devices, they have to be + /// online. Dehydrated devices work around this by providing a "shared" + /// device new sessions can bootstrap from, to receive keys from before they + /// logged in that haven't been uploaded to the server-side key backup yet. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/3814 + /// + /// default: false + #[serde(default)] + pub msc3814: SimpleExperiment, + /// MSC4155: Invite filtering + /// + /// Provides advanced invite filtering rules for users, allowing complex + /// configurations that can allow, ignore, and reject invites from users and + /// servers broadly. + /// + /// Requires a supporting client to set up on an account. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4155 + /// + /// default: false + #[serde(default)] + pub msc4155: SimpleExperiment, + /// MSC4174: Web push + /// + /// Adds server-side support for web push, allowing web clients to receive + /// push notifications directly without the need for an intermediary push + /// gateway like Sygnal. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4174 + /// + /// default: false + #[serde(default)] + pub msc4174: SimpleExperiment, + /// MSC4406: `M_SENDER_IGNORED` error code + /// + /// Introduces a new error code that explicitly informs clients the reason + /// they cannot access an event if it is sent by an ignored user. Without + /// this proposal, clients will simply get a "not found" or "forbidden" + /// error when requesting events sent by users that have been ignored, which + /// leads to replies being shown as "this message could not be found". + /// The new error code allows clients to distinguish unknown/forbidden + /// events from ignored senders, allowing them to display an error message + /// like "you have blocked this sender" instead. + /// + /// Requires a supporting client to be useful. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4406 + /// + /// default: false + #[serde(default)] + pub msc4406: SimpleExperiment, + /// MSC4484: Server Administration OAuth Scope + /// + /// Adds a new OAuth2 scope that explicitly grants a token temporary + /// homeserver administrator privileges, granting temporary token access + /// to administrator endpoints like locking & suspension. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4484 + /// + /// default: false + #[serde(default)] + pub msc4484: SimpleExperiment, + /// MSC4494: Membership-based invite blocking + /// + /// Adds a new invite blocking action that will reject all invites coming + /// from users who do not share a room with the invitee that is not `public` + /// (the join rule). + /// + /// This is not related to MSC4155, this proposal instead builds on the + /// "invite blocking" proposal that landed in the specification in v1.17, + /// which simply allows enabling or disabling invites altogether. + /// + /// MSC4494 is a good middle-ground between the allowlisting possible with + /// MSC4155, and the general desire to block invites from users you may not + /// know. + /// + /// Requires a supporting client to enable on an account. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4494 + /// + /// default: false + #[serde(default)] + pub msc4494: SimpleExperiment, + /// MSC4560: Stripped state requests over federation + /// + /// Implements a more efficient way for servers to acquire and serve + /// "stripped state" to clients, which is typically only used for displaying + /// rooms. The display of space hierarchies and room summaries is + /// significantly faster when this proposal is enabled and used. + /// + /// https://github.com/matrix-org/matrix-spec-proposals/pull/4560 + /// + /// default: false + #[serde(default)] + pub msc4560: SimpleExperiment, +} + +/// Represents a "simple" experiment, which is either disabled or enabled. +/// +/// More complex experiments that require configuration should define their own +/// type and implement `ToggledExperiment` instead. +#[derive(Debug, Deserialize, Default, Clone, Copy)] +pub struct SimpleExperiment(Option); + +pub trait ToggledExperiment { + /// Returns true if this experiment is explicitly enabled. + #[must_use] + fn is_enabled(&self) -> bool; +} + +impl ToggledExperiment for SimpleExperiment { + #[inline] + fn is_enabled(&self) -> bool { self.0.is_some_and(crate::is_true!()) } +} + +/// Configuration for [MSC2815]: Proposal to allow room moderators to view +/// redacted event content +/// +/// MSC2815: https://github.com/matrix-org/matrix-spec-proposals/pull/2815 +#[derive(Debug, Deserialize, Default, Clone, Copy)] +#[config_example_generator( + filename = "conduwuit-example.toml", + section = "global.experiments.msc2815", + optional = "true", + subheader = r#"# MSC2815: Proposal to allow room moderators to view redacted event content +# +# Allows the server to retain unredacted copies of events that have been +# redacted for a limited period of time, which allows room moderators and +# server administrators to reveal redacted contents. Useful for moderation +# and investigating reports. +# +# Requires a supporting client to use. +# +# https://github.com/matrix-org/matrix-spec-proposals/pull/2815"# +)] +pub struct MSC2815 { + /// Whether to enable MSC2815. + /// + /// default: false + #[serde(default)] + pub enabled: bool, + + /// How long, in seconds, to retain the original content of redacted + /// events before it is permanently erased. Defaults to 90 days. + /// + /// default: 7776000 + #[serde(default = "default_unredacted_content_max_age_secs")] + pub unredacted_content_max_age_secs: u64, +} + +#[inline] +fn default_unredacted_content_max_age_secs() -> u64 { 7_776_000 } + +impl ToggledExperiment for Option { + #[inline] + fn is_enabled(&self) -> bool { self.is_some_and(|config| config.enabled) } +} diff --git a/src/core/config/manager.rs b/src/core/config/manager.rs index b7bbf0f3e..a44388e7a 100644 --- a/src/core/config/manager.rs +++ b/src/core/config/manager.rs @@ -1,8 +1,6 @@ use std::{ - cell::{Cell, RefCell}, ops::Deref, - ptr, - ptr::null_mut, + ptr::NonNull, sync::{ Arc, atomic::{AtomicPtr, Ordering}, @@ -10,119 +8,178 @@ use std::{ }; use super::Config; -use crate::Result; +use crate::{Result, SyncMutex}; /// The configuration manager is an indirection to reload the configuration for /// the server while it is running. In order to not burden or clutter the many /// callsites which query for configuration items, this object implements Deref /// for the actively loaded configuration. +/// +/// Every installed `Arc` is kept at a stable heap address in `retired` +/// for the entire lifetime of `Manager` (intentionally retaining prior configs +/// across the rare, admin-triggered reloads until shutdown). Because +/// `Deref::deref(&self)` ties the returned `&Arc` lifetime to `&self`, +/// readers can perform a single `Acquire` load with no locking, no TLS, and no +/// risk of dangling or aliasing UB across reloads. pub struct Manager { - active: AtomicPtr, + active: AtomicPtr>, + /// Append-only owner of every `Box>` ever published to + /// `active` (including the currently active config). Entries are only + /// freed when `Manager` itself is dropped (`&mut self`), guaranteeing that + /// any `&Arc` returned by `Deref::deref` remains valid and + /// immutable for the lifetime of `self`. + retired: SyncMutex>, } -thread_local! { - static INDEX: Cell = 0.into(); - static HANDLE: RefCell = const { - RefCell::new([const { None }; HISTORY]) - }; +/// Heap-pinned `Arc` stored as a raw `NonNull` rather than `Box` so +/// moving it (e.g., when `Vec` reallocates) never retags or invalidates raw +/// pointers previously published to `Manager::active`. +struct PinnedConfig(NonNull>); + +// SAFETY: `Arc` is `Send + Sync`, and `PinnedConfig` uniquely owns the +// `Box>` allocation until it is dropped in `Manager::drop`. +unsafe impl Send for PinnedConfig {} + +impl PinnedConfig { + fn new(config: Config) -> Self { + let ptr = Box::into_raw(Box::new(Arc::new(config))); + Self(NonNull::new(ptr).expect("Box::into_raw returned null")) + } + + #[inline] + const fn as_ptr(&self) -> *mut Arc { self.0.as_ptr() } } -type Handle = Option>; -type Handles = [Handle; HISTORY]; - -const HISTORY: usize = 8; +impl Drop for PinnedConfig { + fn drop(&mut self) { + // SAFETY: `self.0` was created via `Box::into_raw` in + // `PinnedConfig::new` and is only dropped when `Manager` itself is + // dropped (`&mut self`), after all borrows derived from `Deref::deref` + // have ended. + unsafe { + drop(Box::from_raw(self.0.as_ptr())); + } + } +} impl Manager { pub(crate) fn new(config: Config) -> Self { - let config = Arc::new(config); + let pinned = PinnedConfig::new(config); + let ptr = pinned.as_ptr(); Self { - active: AtomicPtr::new(Arc::into_raw(config).cast_mut()), + active: AtomicPtr::new(ptr), + retired: SyncMutex::new(vec![pinned]), } } /// Update the active configuration, returning prior configuration. #[tracing::instrument(skip_all, level = "info")] pub fn update(&self, config: Config) -> Result> { - let config = Arc::new(config); - let new = Arc::into_raw(config); - let old = self.active.swap(new.cast_mut(), Ordering::AcqRel); + let pinned = PinnedConfig::new(config); + let new_ptr = pinned.as_ptr(); - // SAFETY: The old active pointer was set using an Arc::into_raw(). - // We're obliged to reconstitute that into Arc otherwise it will leak. - Ok(unsafe { Arc::from_raw(old) }) - } + let mut retired = self.retired.lock(); + // Push before publishing to `active` so ownership is recorded even if + // `Vec::push` were to unwind. + retired.push(pinned); - fn load(&self, handle: &mut [Option>]) -> &'static Arc { - let config = self.active.load(Ordering::Acquire); + // `Release` publishes the initialized `Box>` to readers + // performing `Acquire` loads in `Deref::deref`. + let old_ptr = self.active.swap(new_ptr, Ordering::AcqRel); - // Branch taken after config reload or first access by this thread. - if handle[INDEX.get()] - .as_ref() - .is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle))) - { - INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY)); - return load_miss(handle, INDEX.get(), config); - } + // SAFETY: `old_ptr` points to a `PinnedConfig` still owned by `retired` + // and cannot be freed until `Manager` is dropped. + let old = unsafe { Arc::clone(&*old_ptr) }; - let config: &Arc = handle[INDEX.get()] - .as_ref() - .expect("handle was already cached for this thread"); - - // SAFETY: The caller should not hold multiple references at a time - // directly into Config, as a subsequent reference might invalidate - // the thread's cache causing another reference to dangle. - // - // This is a highly unusual pattern as most config values are copied by - // value or used immediately without running overlap with another - // value. Even if it does actually occur somewhere, the window of - // danger is limited to the config being reloaded while the reference - // is held and another access is made by the same thread into a - // different config value. This is mitigated by creating a buffer - // of old configs rather than discarding at the earliest opportunity; - // the odds of this scenario are thus astronomical. - unsafe { std::mem::transmute(config) } - } -} - -impl Drop for Manager { - fn drop(&mut self) { - let config = self.active.swap(null_mut(), Ordering::AcqRel); - - // SAFETY: The active pointer was set using an Arc::into_raw(). We're - // obliged to reconstitute that into Arc otherwise it will leak. - unsafe { Arc::from_raw(config) }; + Ok(old) } } impl Deref for Manager { type Target = Arc; - fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) } + #[inline] + fn deref(&self) -> &Self::Target { + let ptr = self.active.load(Ordering::Acquire); + + // SAFETY: `ptr` was initialized in `Manager::new` or published via + // `Ordering::AcqRel` in `Manager::update` and points to a + // `PinnedConfig` in `self.retired`. Entries in `self.retired` are never + // removed or mutated until `Manager` is dropped (`&mut self`), so the + // returned `&'self Arc` remains valid and immutable for the + // entire borrow of `self`. + unsafe { &*ptr } + } } -#[tracing::instrument( - name = "miss", - level = "trace", - skip_all, - fields(%index, ?config) -)] -#[allow(clippy::transmute_ptr_to_ptr)] -fn load_miss( - handle: &mut [Option>], - index: usize, - config: *const Config, -) -> &'static Arc { - // SAFETY: The active pointer was set prior and always remains valid. We're - // reconstituting the Arc here but as a new reference, so the count is - // incremented. This instance will be cached in the thread-local. - let config = unsafe { - Arc::increment_strong_count(config); - Arc::from_raw(config) - }; +#[cfg(test)] +mod tests { + use std::thread; - // SAFETY: See the note on the transmute above. The caller should not hold - // more than one reference at a time directly into Config, as the second - // access might invalidate the thread's cache, dangling the reference to - // the first. - unsafe { std::mem::transmute(handle[index].insert(config)) } + use super::*; + + fn test_config(server_name: &str) -> Config { + use figment::{ + Figment, + providers::{Format, Toml}, + }; + + let raw = format!("server_name = \"{server_name}\"\ndatabase_path = \"/tmp\"\n"); + Figment::new() + .merge(Toml::string(&raw)) + .extract() + .expect("valid test config") + } + + #[test] + fn deref_survives_many_reloads() { + let manager = Manager::new(test_config("initial.example")); + let first: &Arc = &manager; + let first_name: &str = first.server_name.as_str(); + + for i in 0..32 { + let prev = manager + .update(test_config(&format!("reload-{i}.example"))) + .expect("update succeeds"); + if i == 0 { + assert_eq!(prev.server_name.as_str(), "initial.example"); + } + } + + // Original reference remains valid and unchanged after > HISTORY + // reloads. + assert_eq!(first_name, "initial.example"); + assert_eq!(manager.server_name.as_str(), "reload-31.example"); + } + + #[test] + fn concurrent_reads_and_updates() { + let manager = Manager::new(test_config("start.example")); + + thread::scope(|s| { + for _ in 0..4 { + s.spawn(|| { + for _ in 0..200 { + let cfg: &Arc = &manager; + assert!(cfg.server_name.as_str().ends_with(".example")); + } + }); + } + + s.spawn(|| { + for i in 0..32 { + let _ = manager + .update(test_config(&format!("iter-{i}.example"))) + .expect("update succeeds"); + } + }); + }); + } + + #[test] + fn reference_outlives_scoped_thread() { + let manager = Manager::new(test_config("scoped.example")); + let cfg_ref: &Arc = thread::scope(|s| s.spawn(|| &*manager).join().unwrap()); + assert_eq!(cfg_ref.server_name.as_str(), "scoped.example"); + } } diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index 679b8e09c..54bb40e80 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -5,7 +5,10 @@ pub mod proxy; use std::{ collections::{BTreeMap, BTreeSet, HashMap}, + hash::Hash, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + num::NonZero, + ops::Deref, path::PathBuf, time::Duration, }; @@ -15,8 +18,10 @@ use either::{ Either, Either::{Left, Right}, }; +pub use experiments::Experiments; use figment::providers::{Env, Format, Toml}; pub use figment::{Figment, value::Value as FigmentValue}; +use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; use lettre::message::Mailbox; use openidconnect::{Audience, ClientId, ClientSecret, Scope}; use regex::RegexSet; @@ -40,7 +45,7 @@ use crate::{Result, err, error::Error, utils::sys}; /// All the config options for continuwuity. #[allow(clippy::struct_excessive_bools)] #[allow(rustdoc::broken_intra_doc_links, rustdoc::bare_urls)] -#[derive(Clone, Debug, Deserialize)] +#[derive(Debug, Deserialize)] #[config_example_generator( filename = "conduwuit-example.toml", section = "global", @@ -65,8 +70,8 @@ use crate::{Result, err, error::Error, utils::sys}; ignore = "config_paths catchall" )] pub struct Config { - // Paths to config file(s). Not supposed to be set manually in the config file, - // only updated dynamically from the --config option given at runtime. + // Paths to config file(s). Not supposed to be set manually in the config + // file, only updated dynamically from the --config option given at runtime. pub config_paths: Option>, /// The server_name is the pretty name of this server. It is used as a @@ -190,7 +195,7 @@ pub struct Config { /// announcements or major updates. This is not an update check endpoint. /// /// default: true - #[serde(alias = "allow_check_for_updates", default = "true_fn")] + #[serde(default = "true_fn")] pub allow_announcements_check: bool, /// Set this to any float value to multiply continuwuity's in-memory LRU @@ -485,7 +490,7 @@ pub struct Config { #[serde(default = "default_ip_lookup_strategy")] pub ip_lookup_strategy: u8, - /// The preferred source to use for getting the real client IP. + /// DEPRECATED: The preferred source to use for getting the real client IP. /// /// Takes any of the following options: /// @@ -504,9 +509,10 @@ pub struct Config { /// to set this header" check; if the header selected is present, it is /// used. /// - /// Ignored if `accepted_ip_sources` is set. + /// Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is + /// the preferred alternative. /// - /// If not set set, `direct` is used. Additionally, `direct` is used + /// If not set, `direct` is used. Additionally, `direct` is used /// as a fallback if the chosen header is not found. #[serde(default)] pub request_ip_source: Option, @@ -790,6 +796,14 @@ pub struct Config { #[serde(default = "default_sender_shutdown_timeout")] pub sender_shutdown_timeout: u64, + /// Maximum number of requests per minute that unauthenticated clients + /// may make to ratelimited client-server API routes. This ratelimit is + /// global across all endpoints for each IP. + /// + /// default: 30 + #[serde(default = "default_unauthenticated_request_ratelimit")] + pub unauthenticated_request_ratelimit: PerMinuteRatelimiter, + /// Enables registration. If set to false, no users can register on this /// server. /// @@ -906,14 +920,34 @@ pub struct Config { #[serde(default)] pub forget_forced_upon_leave: bool, - /// Set this to true to require authentication on the normally - /// unauthenticated profile retrieval endpoints (GET) - /// "/_matrix/client/v3/profile/{userId}". + /// Set this to true to require authentication when looking up user profiles + /// through this server. /// - /// This can prevent profile scraping. + /// By default this is false, allowing tools such as matrix.to to access + /// profiles of users on this server and on other servers. + /// Setting this to true will block those tools, and may block automated + /// crawlers from scraping users' profiles, although it will not block + /// other homeservers from accessing users' profiles. + /// + /// default: false #[serde(default)] pub require_auth_for_profile_requests: bool, + /// Set this to true to require authentication to create a rendezvous + /// session. Rendezvous sessions are used for QR code login. + /// + /// For QR code login, the device that shows the QR code is the one that + /// creates the rendezvous session. Therefore, this must be false to let + /// a logged-out device show a QR code. + /// + /// By default this is false to allow logged-out desktop devices (which may + /// not have a camera) to show a QR code. Setting this to true will + /// require logged-out devices to scan the QR code instead. + /// + /// default: false + #[serde(default)] + pub require_auth_for_rendezvous: bool, + /// Set this to true to allow your server's public room directory to be /// federated. Set this to false to protect against /publicRooms spiders, /// but will forbid external users from viewing your server's public room @@ -1753,14 +1787,6 @@ pub struct Config { #[serde(default = "true_fn")] pub allow_incoming_typing: bool, - /// Allow the use of unstable persistent "sticky events" ([MSC4354]) - /// - /// MSC4354: https://c10y.cc/MSC4354 - /// - /// default: false - #[serde(default)] - pub allow_sticky_events: bool, - /// Maximum time federation user can indicate typing. /// /// default: 30 @@ -1811,31 +1837,6 @@ pub struct Config { #[serde(default)] pub brotli_compression: bool, - /// Enable the legacy unauthenticated Matrix media repository endpoints. - /// These endpoints consist of: - /// - /_matrix/media/*/config - /// - /_matrix/media/*/upload - /// - /_matrix/media/*/preview_url - /// - /_matrix/media/*/download/* - /// - /_matrix/media/*/thumbnail/* - /// - /// The authenticated equivalent endpoints are always enabled. - /// - /// Defaults to false, as unauthenticated media has been sunsetted. - /// - /// default: false - #[serde(default)] - pub allow_legacy_media: bool, - - /// If set to true, prevents fetching new legacy remote media. - /// - /// Legacy media may still be accessible if it was already fetched - /// previously and allow_legacy_media is true. - /// - /// default: true - #[serde(default = "true_fn")] - pub freeze_legacy_media: bool, - /// Check consistency of the media directory at startup: /// 1. When `media_compat_file_link` is enabled, this check will upgrade /// media when switching back and forth between Conduit and conduwuit. @@ -2463,6 +2464,12 @@ pub struct Config { #[serde(default)] pub matrix_rtc: MatrixRtcConfig, + /// Configuration for unstable features. + /// + /// display: nested + #[serde(default)] + pub experiments: Experiments, + #[serde(flatten)] #[allow(clippy::zero_sized_map_values)] // this is a catchall, the map shouldn't be zero at runtime @@ -2957,12 +2964,43 @@ impl TrustedServerConfig { } } +#[derive(Debug)] +pub struct PerMinuteRatelimiter { + ratelimiter: DefaultKeyedRateLimiter, +} + +impl PerMinuteRatelimiter { + fn new(quota: Quota) -> Self { Self { ratelimiter: RateLimiter::keyed(quota) } } +} + +impl Deref for PerMinuteRatelimiter { + type Target = DefaultKeyedRateLimiter; + + fn deref(&self) -> &Self::Target { &self.ratelimiter } +} + +impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter { + fn deserialize(deserializer: D) -> std::prelude::v1::Result + where + D: serde::Deserializer<'de>, + { + let max_burst = NonZero::::deserialize(deserializer)?; + + Ok(Self::new(Quota::per_minute(max_burst))) + } +} + const DEPRECATED_KEYS: &[&str] = &[ + "allow_check_for_updates", + "allow_moderators_to_view_redacted_content", + "allow_sticky_events", "cache_capacity", "conduit_cache_capacity_modifier", "max_concurrent_requests", "otlp_protocol", + "request_ip_source", "roomid_spacehierarchy_cache_capacity", + "unredacted_content_max_age_secs", "well_known_client", "well_known_server", "well_known_support_page", @@ -3399,3 +3437,13 @@ fn default_preferred_username_claim() -> String { "preferred_username".to_owned( fn default_profile_key_map() -> HashMap { HashMap::from_iter([(ProfileFieldName::DisplayName.to_string(), "name".to_owned())]) } + +fn default_unauthenticated_request_ratelimit() -> PerMinuteRatelimiter { + PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) +} + +// NOTE: This must be declared *after* every config struct in this file. The +// example config generator writes sections in macro expansion order, and the +// `global` section truncates the file, so declaring this module any earlier +// causes its sections to be wiped from the generated example config. +pub mod experiments; diff --git a/src/core/matrix/event.rs b/src/core/matrix/event.rs index 1b44b4ac1..18372e171 100644 --- a/src/core/matrix/event.rs +++ b/src/core/matrix/event.rs @@ -16,7 +16,12 @@ use ruma::{ use serde::Deserialize; use serde_json::{Value as JsonValue, value::RawValue as RawJsonValue}; -pub use self::{filter::Matches, id::*, relation::RelationTypeEqual, type_ext::TypeExt}; +pub use self::{ + filter::Matches, + id::*, + relation::{RelationTypeEqual, relation_type}, + type_ext::TypeExt, +}; use super::{pdu::Pdu, state_key::StateKey}; use crate::{Result, utils}; diff --git a/src/core/matrix/event/relation.rs b/src/core/matrix/event/relation.rs index 58324e863..7766433c2 100644 --- a/src/core/matrix/event/relation.rs +++ b/src/core/matrix/event/relation.rs @@ -8,7 +8,7 @@ pub trait RelationTypeEqual { } #[derive(Clone, Debug, Deserialize)] -struct ExtractRelatesToEventId { +struct ExtractRelatesToRelType { #[serde(rename = "m.relates_to")] relates_to: ExtractRelType, } @@ -18,11 +18,16 @@ struct ExtractRelType { rel_type: RelationType, } +/// The type of an event's relation, if it has one +pub fn relation_type(event: &E) -> Option { + event + .get_content() + .map(|c: ExtractRelatesToRelType| c.relates_to.rel_type) + .ok() +} + impl RelationTypeEqual for RelationType { fn relation_type_equal(&self, event: &E) -> bool { - event - .get_content() - .map(|c: ExtractRelatesToEventId| c.relates_to.rel_type) - .is_ok_and(|r| r == *self) + relation_type(event).is_some_and(|r| r == *self) } } diff --git a/src/core/matrix/pdu/count.rs b/src/core/matrix/pdu/count.rs index 7fb125745..8429db9ac 100644 --- a/src/core/matrix/pdu/count.rs +++ b/src/core/matrix/pdu/count.rs @@ -105,6 +105,16 @@ impl Count { } } + /// Whether this comes after `other` when going in the direction of `dir` + #[inline] + #[must_use] + pub fn is_after(self, other: Self, dir: Direction) -> bool { + match dir { + | Direction::Forward => self > other, + | Direction::Backward => self < other, + } + } + #[inline] #[must_use] pub fn saturating_add(self, add: u64) -> Self { diff --git a/src/core/matrix/state_res/event_auth.rs b/src/core/matrix/state_res/event_auth.rs index e5693cf78..b5d719742 100644 --- a/src/core/matrix/state_res/event_auth.rs +++ b/src/core/matrix/state_res/event_auth.rs @@ -5,17 +5,21 @@ use futures::{ future::{OptionFuture, join, join3}, }; use ruma::{ - Int, OwnedUserId, RoomVersionId, UserId, + AnyKeyName, CanonicalJsonObject, Int, OwnedUserId, RoomVersionId, SigningKeyId, UserId, events::room::{ join_rules::{JoinRule, RoomJoinRulesEventContent}, - member::{MembershipState, ThirdPartyInvite}, + member::MembershipState, power_levels::{RoomPowerLevelsEventContent, UserPowerLevel}, + third_party_invite::PublicKey, }, int, room_version_rules::{RoomIdFormatVersion, RoomVersionRules}, - serde::Raw, + serde::{Raw, base64, base64::Standard}, + signatures, + signatures::to_canonical_json_string_for_signing, + third_party_invite::IdentityServerBase64PublicKey, }; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{from_str as from_json_str, value::RawValue as RawJsonValue}; use super::{ @@ -25,7 +29,7 @@ use super::{ deserialize_power_levels_content_redact, }, }; -use crate::{debug, error, trace, warn}; +use crate::{debug, err, error, trace, warn}; // FIXME: field extracting could be bundled for `content` #[derive(Deserialize)] @@ -48,6 +52,40 @@ struct RoomCreateContentFields { federate: bool, } +// Workaround for https://github.com/matrix-org/matrix-spec/issues/2471 +#[derive(Deserialize, Debug)] +struct RoomThirdPartyInviteContentFields { + public_key: Option, + public_keys: Option>, +} + +// same here sort of (maintainers see https://forgejo.ellis.link/continuwuation/continuwuity-sec/issues/41) +#[derive(Deserialize, Debug)] +struct MemberThirdPartyInviteSignedContent { + signed: ThirdPartyInviteSignedObject, +} + +#[derive(Serialize, Deserialize, Debug)] +struct ThirdPartyInviteSignedObject(CanonicalJsonObject); + +impl ThirdPartyInviteSignedObject { + #[inline] + fn mxid(&self) -> Option { + self.0 + .get("mxid")? + .as_str() + .and_then(|raw| UserId::parse(raw).ok()) + } + + #[inline] + fn token(&self) -> Option<&str> { self.0.get("token")?.as_str() } + + #[inline] + fn signatures(&self) -> Option { + self.0.get("signatures")?.as_object().map(ToOwned::to_owned) + } +} + /// For the given event `kind` what are the relevant auth events that are needed /// to authenticate this `content`. /// @@ -61,7 +99,7 @@ pub fn auth_types_for_event( state_key: Option<&str>, content: &RawJsonValue, room_version: &RoomVersionRules, -) -> serde_json::Result> { +) -> crate::Result> { if kind == &TimelineEventType::RoomCreate { return Ok(vec![]); } @@ -84,7 +122,7 @@ pub fn auth_types_for_event( #[allow(unused)] struct RoomMemberContentFields { membership: Option>, - third_party_invite: Option>, + third_party_invite: Option>, join_authorised_via_users_server: Option>, } @@ -116,16 +154,24 @@ pub fn auth_types_for_event( auth_types.push(key); } - // TODO: restore this once 3pid support isn't broken - // if membership == MembershipState::Invite { - // if let Some(Ok(t_id)) = content.third_party_invite.map(|t| - // t.deserialize()) { let key = - // (StateEventType::RoomThirdPartyInvite, - // t_id.signed.token.into()); if !auth_types.contains(& - // key) { auth_types.push(key); - // } - // } - // } + if membership == MembershipState::Invite { + if let Some(Ok(t_id)) = content.third_party_invite.map(|t| t.deserialize()) { + let key = ( + StateEventType::RoomThirdPartyInvite, + t_id.signed + .token() + .ok_or_else(|| { + err!(Request(BadJson( + "Third party invite content missing a token" + ))) + })? + .into(), + ); + if !auth_types.contains(&key) { + auth_types.push(key); + } + } + } } } } @@ -179,12 +225,11 @@ fn get_user_power_level( pub async fn auth_check( room_version: &RoomVersionRules, incoming_event: &E, - current_third_party_invite: Option<&E>, fetch_state: F, create_event: &E, ) -> Result where - F: Fn(&StateEventType, &str) -> Fut + Send, + F: Fn(&StateEventType, &str) -> Fut + Send + Copy, Fut: Future> + Send, E: Event + Send + Sync, for<'a> &'a E: Event + Send, @@ -444,13 +489,15 @@ where sender, sender_member_event.as_ref(), incoming_event, - current_third_party_invite, + fetch_state, power_levels_event.as_ref(), join_rules_event.as_ref(), user_for_join_auth.as_deref(), &user_for_join_auth_membership, &room_create_event, - )? { + ) + .await? + { return Ok(false); } @@ -639,14 +686,14 @@ where /// event and the current State. #[allow(clippy::too_many_arguments)] #[allow(clippy::cognitive_complexity)] -fn valid_membership_change( +async fn valid_membership_change( room_version: &RoomVersionRules, target_user: &UserId, target_user_membership_event: Option<&E>, sender: &UserId, sender_membership_event: Option<&E>, current_event: &E, - current_third_party_invite: Option<&E>, + fetch_state: F, power_levels_event: Option<&E>, join_rules_event: Option<&E>, user_for_join_auth: Option<&UserId>, @@ -655,11 +702,13 @@ fn valid_membership_change( ) -> Result where E: Event + Send + Sync, + F: Fn(&StateEventType, &str) -> Fut + Send + Copy, + Fut: Future> + Send, for<'a> &'a E: Event + Send, { #[derive(Deserialize)] struct GetThirdPartyInvite { - third_party_invite: Option>, + third_party_invite: Option>, } let create_content = from_json_str::(create_room.content().get())?; let creator = if room_version.authorization.use_room_create_sender { @@ -901,22 +950,18 @@ where | MembershipState::Invite => { // If content has third_party_invite key trace!("starting target_membership=invite check"); - match third_party_invite.and_then(|i| i.deserialize().ok()) { - | Some(tp_id) => + match third_party_invite { + | Some(raw_tp_id) => if target_user_current_membership == MembershipState::Ban { warn!(?target_user_membership_event_id, "Can't invite banned user"); false } else { - let allow = verify_third_party_invite( - Some(target_user), - sender, - &tp_id, - current_third_party_invite, - ); - if !allow { - warn!("Third party invite invalid"); - } - allow + let Ok(tp_id) = raw_tp_id.deserialize() else { + warn!("Invite third party content is invalid"); + return Ok(false); + }; + verify_third_party_invite(Some(target_user), sender, &tp_id, fetch_state) + .await }, | _ => if !sender_is_joined { @@ -1435,14 +1480,133 @@ fn get_send_level( .unwrap_or_else(|| if state_key.is_some() { int!(50) } else { int!(0) }) } -fn verify_third_party_invite( - _target_user: Option<&UserId>, - _sender: &UserId, - _tp_id: &ThirdPartyInvite, - _current_third_party_invite: Option<&impl Event>, -) -> bool { - // TODO: implement proper verification here - true +async fn verify_third_party_invite( + target_user: Option<&UserId>, + sender: &UserId, + tp_id: &MemberThirdPartyInviteSignedContent, + fetch_state: F, +) -> bool +where + F: Fn(&StateEventType, &str) -> Fut + Send, + Fut: Future> + Send, + E: Event + Send + Sync, +{ + // If content.third_party_invite does not have a signed property, reject. + // ^ This would be a deserialization error before this function call, which + // equates to a rejection + let signed = &tp_id.signed; + // If signed does not have mxid and token properties, reject. + let Some(mxid) = signed.mxid() else { + warn!("Invite third party signed content is missing or has invalid `mxid` property"); + return false; + }; + let Some(token) = signed.token() else { + warn!("Invite third party signed content is missing or has invalid `token` property"); + return false; + }; + if let Err(e) = mxid.validate_historical() { + warn!(error=?e, ?mxid, "Invite third party signed content has invalid `mxid` property"); + return false; + } + // If mxid does not match state_key, reject. + // N.B. target_user is the state_key + if target_user.is_none_or(|u| u != mxid) { + warn!(?target_user, %mxid, "Invite third party mxid does not match membership state key"); + return false; + } + // If there is no m.room.third_party_invite event in the current room state + // with state_key matching token, reject. + let Some(current_third_party_invite) = + fetch_state(&StateEventType::RoomThirdPartyInvite, token).await + else { + warn!("No third party invite associated with the invite's third party invite found"); + return false; + }; + let Ok(tpi_content) = current_third_party_invite + .get_content::() + .inspect_err( + |e| warn!(error=?e, "Third party invite event content is invalid (cannot deserialize)"), + ) + else { + return false; + }; + if current_third_party_invite.state_key() != Some(token) { + warn!( + state_key=?current_third_party_invite.state_key(), + %token, + "Third party invite state key mismatch with signed invite token" + ); + return false; + } + // If sender does not match sender of the m.room.third_party_invite, reject. + if sender != current_third_party_invite.sender() { + warn!( + ?sender, + third_party_invite_sender=%current_third_party_invite.sender(), + "Third party invite sender does not match invite membership sender" + ); + return false; + } + // If any signature in signed matches any public key in the + // m.room.third_party_invite event, allow. The public keys are in content of + // m.room.third_party_invite as: + // + // A single public key in the public_key property. + // A list of public keys in the public_keys property. + + // NOTE: Technically the two below operations shouldn't be fallible at this + // point in execution, but if we can't de/serialize them now, we won't be + // able to in the future, so rejecting the event is the right way to go. + // We log an error though since this is unexpected. + let Ok(signed_json) = to_canonical_json_string_for_signing(&signed.0).inspect_err( + |e| error!(error=?e, "Canonical signed object cannot be cast to a signing string"), + ) else { + return false; + }; + let signatures = signed + .signatures() + .unwrap_or_default() // Empty sigs object will never pass so this is fine + .values() + .filter_map(|signatures| signatures.as_object()) + .flat_map(|signatures| { + signatures.iter().map(|(key, sig)| { + let key_id = SigningKeyId::::parse(key).ok()?; + base64::Base64::::parse(sig.as_str()?) + .map(|parsed| (key_id.algorithm(), parsed)) + .ok() + }) + }) + .flatten() + .collect::>(); + + for public_key_bytes in tpi_content + .public_key + .into_iter() + .chain( + tpi_content + .public_keys + .unwrap_or_default() + .iter() + .map(|pk| pk.public_key.clone()), + ) + .filter_map(|pk| pk.decode().ok()) + { + for (algorithm, signature) in &signatures { + if signatures::verify_canonical_json_bytes( + algorithm, + &public_key_bytes, + signature.as_bytes(), + signed_json.as_bytes(), + ) + .is_ok() + { + return true; + } + } + } + + warn!("Invite via third party was not signed by any associated public keys"); + false } #[cfg(test)] @@ -1461,7 +1625,7 @@ mod tests { use serde_json::value::to_raw_value as to_raw_json_value; use crate::{ - matrix::{Event, EventTypeExt, Pdu as PduEvent}, + matrix::{Event, EventTypeExt}, state_res::{ StateMap, event_auth::valid_membership_change, @@ -1472,8 +1636,8 @@ mod tests { }, }; - #[test] - fn test_ban_pass() { + #[tokio::test] + async fn test_ban_pass() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1495,6 +1659,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = charlie(); let sender = alice(); @@ -1506,19 +1672,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_join_non_creator() { + #[tokio::test] + async fn test_join_non_creator() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1540,6 +1707,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = charlie(); let sender = charlie(); @@ -1551,19 +1720,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_join_creator() { + #[tokio::test] + async fn test_join_creator() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1585,6 +1755,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = alice(); let sender = alice(); @@ -1596,19 +1768,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_ban_fail() { + #[tokio::test] + async fn test_ban_fail() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1630,6 +1803,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = alice(); let sender = charlie(); @@ -1641,19 +1816,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_restricted_join_rule() { + #[tokio::test] + async fn test_restricted_join_rule() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1692,6 +1868,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = ella(); let sender = ella(); @@ -1703,13 +1881,14 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), Some(alice()), &MembershipState::Join, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); @@ -1721,19 +1900,20 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), Some(ella()), &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } - #[test] - fn test_knock() { + #[tokio::test] + async fn test_knock() { let _ = tracing::subscriber::set_default( tracing_subscriber::fmt().with_test_writer().finish(), ); @@ -1764,6 +1944,8 @@ mod tests { ); let fetch_state = |ty, key| auth_events.get(&(ty, key)).cloned(); + let async_fetch_state = + |t: &StateEventType, k: &str| std::future::ready(fetch_state(t.to_owned(), k.into())); let target_user = ella(); let sender = ella(); @@ -1775,13 +1957,14 @@ mod tests { sender, fetch_state(StateEventType::RoomMember, sender.as_str().into()).as_ref(), &requester, - None::<&PduEvent>, + &async_fetch_state, fetch_state(StateEventType::RoomPowerLevels, "".into()).as_ref(), fetch_state(StateEventType::RoomJoinRules, "".into()).as_ref(), None, &MembershipState::Leave, &fetch_state(StateEventType::RoomCreate, "".into()).unwrap(), ) + .await .unwrap() ); } diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index 77948c323..96a953ade 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -39,7 +39,7 @@ use crate::{ debug, debug_error, err, matrix::{Event, StateKey}, trace, - utils::stream::{BroadbandExt, IterStream, ReadyExt, TryBroadbandExt, WidebandExt}, + utils::stream::{BroadbandExt, IterStream, ReadyExt, TryWidebandExt, WidebandExt}, warn, }; @@ -590,8 +590,8 @@ where .find(|aev| is_type_and_key(*aev, &TimelineEventType::RoomPowerLevels, "")); let content: PowerLevelsContentFields = match pl { - // With no m.room.power_levels in scope the create event's defaults apply, - // under which the room creator holds 100 and everyone else 0. + // With no m.room.power_levels in scope the create event's defaults + // apply, under which the room creator holds 100 and everyone else 0. | None => return Ok(if sender_is_creator { int!(100) } else { int!(0) }), | Some(ev) => from_json_str(ev.content().get())?, }; @@ -706,7 +706,7 @@ where let events_to_check: Vec<_> = events_to_check .map(Result::Ok) - .broad_and_then(async |event_id| { + .wide_and_then(async |event_id| { fetch_event(event_id.to_owned()) .await .ok_or_else(|| Error::NotFound(format!("Failed to find {event_id}"))) @@ -757,7 +757,8 @@ where Some(state_key), event.content(), room_version, - )?; + ) + .map_err(|e| Error::InvalidPdu(e.to_string()))?; trace!(list = ?auth_types, event_id = event.event_id().as_str(), "auth types for event"); let mut auth_state = StateMap::new(); @@ -830,12 +831,6 @@ where debug!(event_id = event.event_id().as_str(), "Running auth checks"); - // The key for this is (eventType + a state_key of the signed token not - // sender) so search for it - let current_third_party = auth_state.iter().find_map(|(_, pdu)| { - (*pdu.event_type() == TimelineEventType::RoomThirdPartyInvite).then_some(pdu) - }); - let fetch_state = |ty: &StateEventType, key: &str| { future::ready( auth_state @@ -847,7 +842,6 @@ where let auth_result = auth_check( room_version, &event, - current_third_party, fetch_state, &fetch_state(&StateEventType::RoomCreate, "") .await @@ -1123,6 +1117,68 @@ mod tests { utils::stream::IterStream, }; + #[tokio::test] + async fn iterative_auth_check_keeps_event_order() { + let mut events = INITIAL_EVENTS(); + let initial_state = ["CREATE", "IPOWER", "IJR", "IMB"] + .into_iter() + .map(|id| { + let event = &events[&event_id(id)]; + ( + event + .event_type() + .with_state_key(event.state_key().unwrap()), + event.event_id.clone(), + ) + }) + .collect(); + let leave = to_pdu_event( + "LEAVE", + bob(), + TimelineEventType::RoomMember, + Some(bob().as_str()), + to_raw_json_value(&json!({ "membership": "leave" })).unwrap(), + &["CREATE", "IPOWER", "IMB"], + &["IMB"], + ); + let rejoin = to_pdu_event( + "REJOIN", + bob(), + TimelineEventType::RoomMember, + Some(bob().as_str()), + member_content_join(), + &["CREATE", "IPOWER", "IJR", "LEAVE"], + &["LEAVE"], + ); + let ordered_events = [leave.event_id.clone(), rejoin.event_id.clone()]; + for event in [leave, rejoin] { + events.insert(event.event_id.clone(), event); + } + let fetcher = |id: OwnedEventId| { + let events = &events; + async move { + // Let the rejoin fetch finish before the leave. + if id == event_id("LEAVE") { + tokio::task::yield_now().await; + } + events.get(&id).cloned() + } + }; + let resolved = super::iterative_auth_check( + &RoomVersionRules::V6, + ordered_events.iter().map(AsRef::as_ref).stream(), + initial_state, + &fetcher, + ) + .await + .unwrap(); + + assert_eq!( + resolved[&StateEventType::RoomMember.with_state_key(bob().as_str())], + event_id("REJOIN"), + ); + } + /// Events at the start of a room have no `m.room.power_levels` in their /// auth events, so the sender's power for sort ordering comes from the /// create event instead. diff --git a/src/core/matrix/versions.rs b/src/core/matrix/versions.rs index ae681e3ca..8db196e1f 100644 --- a/src/core/matrix/versions.rs +++ b/src/core/matrix/versions.rs @@ -1,5 +1,7 @@ use std::collections::BTreeMap; +use crate::config::{Experiments, experiments::ToggledExperiment}; + #[must_use] pub fn versions() -> Vec { vec![ @@ -25,30 +27,29 @@ pub fn versions() -> Vec { "v1.16".to_owned(), "v1.17".to_owned(), "v1.18".to_owned(), + "v1.19".to_owned(), ] } #[must_use] -pub fn unstable_features() -> BTreeMap { +pub fn unstable_features(experiments: &Experiments) -> BTreeMap { BTreeMap::from_iter([ // MatrixRTC (https://github.com/matrix-org/matrix-spec-proposals/pull/4143) + // Expected for spec v1.20/v2.0 ("org.matrix.msc4143".to_owned(), true), - // query mutual rooms (https://github.com/matrix-org/matrix-spec-proposals/pull/2666) - // Expected for spec v1.19 - ("uk.half-shot.msc2666.query_mutual_rooms".to_owned(), true), - ("uk.half-shot.msc2666.query_mutual_rooms.stable".to_owned(), true), // Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186) - // Expected for spec v1.19 + // Expected for spec v1.20/v2.0 ("org.matrix.simplified_msc3575".to_owned(), true), - // invite filtering (https://github.com/matrix-org/matrix-spec-proposals/pull/4155) - ("org.matrix.msc4155".to_owned(), true), + ("org.matrix.msc4155".to_owned(), experiments.msc4155.is_enabled()), // profile change propagation (https://github.com/matrix-org/matrix-spec-proposals/pull/4466) ("computer.gingershaped.msc4466".to_owned(), true), - // web push (https://github.com/matrix-org/matrix-spec-proposals/pull/4174) - ("org.matrix.msc4174".to_owned(), true), - // Membership-based invite blocking (https://github.com/matrix-org/matrix-spec-proposals/pull/4494) - ("uk.timedout.msc4494".to_owned(), true), - // server administration OAuth scope (https://github.com/matrix-org/matrix-spec-proposals/pull/4484) - ("org.continuwuity.msc4484.unstable".to_owned(), true), + ("org.matrix.msc4174".to_owned(), experiments.msc4174.is_enabled()), + ("uk.timedout.msc4494".to_owned(), experiments.msc4494.is_enabled()), + ("org.continuwuity.msc4484.unstable".to_owned(), experiments.msc4484.is_enabled()), + ("org.continuwuity.msc4560".to_owned(), experiments.msc4560.is_enabled()), + ("fi.mau.msc2815".to_owned(), experiments.msc2815.is_enabled()), + // Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) + // Proposal merged, expected for spec v1.20/v2.0 + ("org.matrix.msc4354".to_owned(), true), ]) } diff --git a/src/core/metrics/instruments.rs b/src/core/metrics/instruments.rs index b9ba973b2..e1583d056 100644 --- a/src/core/metrics/instruments.rs +++ b/src/core/metrics/instruments.rs @@ -21,6 +21,7 @@ pub struct Instruments { pub sender_transaction_duration: Histogram, pub sender_events: Counter, pub sender_events_queued: Counter, + pub sender_panics: Counter, pub media_write_size: Histogram, pub media_read_size: Histogram, @@ -45,6 +46,14 @@ impl Instruments { .with_boundaries(duration_buckets()) .build() }; + let long_duration = |name: &'static str, description: &'static str| { + meter + .f64_histogram(name) + .with_description(description) + .with_unit("s") + .with_boundaries(long_duration_buckets()) + .build() + }; let size = |name: &'static str, description: &'static str| { meter .u64_histogram(name) @@ -55,11 +64,11 @@ impl Instruments { }; Self { - federation_outgoing_request_duration: duration( + federation_outgoing_request_duration: long_duration( "continuwuity.federation.outgoing.request.duration", "Duration of outgoing federation requests", ), - federation_incoming_transaction_duration: duration( + federation_incoming_transaction_duration: long_duration( "continuwuity.federation.incoming.transaction.duration", "Time taken to process incoming federation transactions", ), @@ -75,11 +84,13 @@ impl Instruments { federation_incoming_pdu_lag: meter .f64_histogram("continuwuity.federation.incoming.pdu.lag") .with_description( - "Time between an accepted incoming PDU's origin_server_ts and its arrival", + "Time between an accepted incoming PDU's origin_server_ts and its \ + transaction arriving", ) .with_unit("s") .with_boundaries(vec![ 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 900.0, 3600.0, + 21600.0, 86400.0, ]) .build(), federation_incoming_edus: meter @@ -92,7 +103,7 @@ impl Instruments { "Time taken to handle an incoming federation EDU", ), - sender_transaction_duration: duration( + sender_transaction_duration: long_duration( "continuwuity.sender.transaction.duration", "Duration of outgoing transactions by destination type and outcome", ), @@ -106,6 +117,11 @@ impl Instruments { .with_description("PDUs and EDUs queued for sending") .with_unit("{event}") .build(), + sender_panics: meter + .u64_counter("continuwuity.sender.panics") + .with_description("Panics caught in outgoing transactions and sender workers") + .with_unit("{panic}") + .build(), media_write_size: size( "continuwuity.media.write.size", @@ -130,6 +146,12 @@ impl Instruments { #[must_use] pub fn duration_buckets() -> Vec { (0..16).map(|i| 0.001 * f64::from(1_u32 << i)).collect() } +/// Federation requests and transactions can run past the 60s default +/// `federation_timeout`. +fn long_duration_buckets() -> Vec { + (0..18).map(|i| 0.001 * f64::from(1_u32 << i)).collect() +} + fn size_buckets() -> Vec { (0..11).map(|i| 1024.0 * f64::from(4_u32.pow(i))).collect() } fn register_process(meter: &Meter) { @@ -196,9 +218,13 @@ fn register_process(meter: &Meter) { } fn register_allocator(meter: &Meter) { + let Some((name, description)) = crate::alloc::metric() else { + return; + }; + meter - .u64_observable_gauge("continuwuity.jemalloc.memory") - .with_description("jemalloc memory statistics, when built with jemalloc_stats") + .u64_observable_gauge(name) + .with_description(description) .with_unit("By") .with_callback(|observer| { for (kind, bytes) in crate::alloc::memory_usage_stats().into_iter().flatten() { diff --git a/src/core/metrics/mod.rs b/src/core/metrics/mod.rs index d3f1a1da2..bb06368a8 100644 --- a/src/core/metrics/mod.rs +++ b/src/core/metrics/mod.rs @@ -14,6 +14,8 @@ use tokio_metrics::TaskMonitor; use tokio_metrics::{RuntimeIntervals, RuntimeMonitor}; pub use self::instruments::{Instruments, duration_buckets}; +#[cfg(tokio_unstable)] +use crate::SyncMutex; use crate::{Err, Result}; pub struct Metrics { @@ -27,7 +29,7 @@ pub struct Metrics { _runtime_monitor: Option, #[cfg(tokio_unstable)] - runtime_intervals: std::sync::Mutex>, + runtime_intervals: SyncMutex>, // TODO: move stats pub requests_handle_active: AtomicU32, @@ -69,7 +71,7 @@ impl Metrics { _runtime_monitor: runtime_monitor, #[cfg(tokio_unstable)] - runtime_intervals: std::sync::Mutex::new(runtime_intervals), + runtime_intervals: SyncMutex::new(runtime_intervals), requests_handle_active: AtomicU32::new(0), requests_handle_finished: AtomicU32::new(0), @@ -81,7 +83,6 @@ impl Metrics { pub fn runtime_interval(&self) -> Option { self.runtime_intervals .lock() - .expect("locked") .as_mut() .map(Iterator::next) .expect("next interval") diff --git a/src/core/metrics/tests.rs b/src/core/metrics/tests.rs index fdbe52c9d..3f13d8bd5 100644 --- a/src/core/metrics/tests.rs +++ b/src/core/metrics/tests.rs @@ -38,3 +38,23 @@ async fn renders_prometheus_names() { } assert!(!body.contains("otel_scope_name")); } + +#[tokio::test] +#[cfg(all(feature = "mimalloc", any(target_env = "msvc", not(feature = "jemalloc"))))] +async fn renders_mimalloc_memory_metric() { + let (metrics, _provider) = metrics(); + let body = metrics.render().unwrap(); + + for expected in [ + "continuwuity_mimalloc_memory_bytes{kind=\"reserved\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"reserved_peak\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"committed\"}", + "continuwuity_mimalloc_memory_bytes{kind=\"committed_peak\"}", + ] { + assert!(body.contains(expected), "missing {expected:?} in:\n{body}"); + } + assert!( + !body.contains("continuwuity_jemalloc_memory_bytes"), + "unexpected jemalloc metric in mimalloc build:\n{body}" + ); +} diff --git a/src/core/mod.rs b/src/core/mod.rs index 20d49fc50..f0388be62 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -8,19 +8,6 @@ pub mod info; pub mod log; pub mod matrix; pub mod metrics; -pub mod mods; - -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] -pub mod mods { - #[macro_export] - macro_rules! mod_ctor { - () => {}; - } - #[macro_export] - macro_rules! mod_dtor { - () => {}; - } -} pub mod server; pub mod utils; @@ -36,7 +23,11 @@ pub use config::Config; pub use error::Error; pub use info::version::*; pub use matrix::{Event, EventTypeExt, Pdu, PduCount, PduEvent, PduId, pdu, state_res}; -pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock}; +pub use parking_lot::{ + MappedMutexGuard as SyncMappedMutexGuard, Mutex as SyncMutex, MutexGuard as SyncMutexGuard, + RwLock as SyncRwLock, RwLockReadGuard as SyncRwLockReadGuard, + RwLockWriteGuard as SyncRwLockWriteGuard, +}; pub use server::Server; pub use utils::{result, result::Result}; diff --git a/src/core/mods/canary.rs b/src/core/mods/canary.rs deleted file mode 100644 index 6095608c6..000000000 --- a/src/core/mods/canary.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::sync::atomic::{AtomicI32, Ordering}; - -const ORDERING: Ordering = Ordering::Relaxed; -static STATIC_DTORS: AtomicI32 = AtomicI32::new(0); - -/// Called by Module::unload() to indicate module is about to be unloaded and -/// static destruction is intended. This will allow verifying it actually took -/// place. -pub(crate) fn prepare() { - let count = STATIC_DTORS.fetch_sub(1, ORDERING); - debug_assert!(count <= 0, "STATIC_DTORS should not be greater than zero."); -} - -/// Called by static destructor of a module. This call should only be found -/// inside a mod_fini! macro. Do not call from anywhere else. -#[inline(always)] -pub fn report() { let _count = STATIC_DTORS.fetch_add(1, ORDERING); } - -/// Called by Module::unload() (see check()) with action in case a check() -/// failed. This can allow a stuck module to be noted while allowing for other -/// independent modules to be diagnosed. -pub(crate) fn check_and_reset() -> bool { STATIC_DTORS.swap(0, ORDERING) == 0 } - -/// Called by Module::unload() after unload to verify static destruction took -/// place. A call to prepare() must be made prior to Module::unload() and making -/// this call. -#[allow(dead_code)] -pub(crate) fn check() -> bool { STATIC_DTORS.load(ORDERING) == 0 } diff --git a/src/core/mods/macros.rs b/src/core/mods/macros.rs deleted file mode 100644 index 1f3b7f5fa..000000000 --- a/src/core/mods/macros.rs +++ /dev/null @@ -1,44 +0,0 @@ -#[macro_export] -macro_rules! mod_ctor { - ( $($body:block)? ) => { - $crate::mod_init! {{ - $crate::debug_info!("Module loaded"); - $($body)? - }} - } -} - -#[macro_export] -macro_rules! mod_dtor { - ( $($body:block)? ) => { - $crate::mod_fini! {{ - $crate::debug_info!("Module unloading"); - $($body)? - $crate::mods::canary::report(); - }} - } -} - -#[macro_export] -macro_rules! mod_init { - ($body:block) => { - #[used] - #[cfg_attr(target_family = "unix", unsafe(link_section = ".init_array"))] - static MOD_INIT: unsafe extern "C" fn() = { _mod_init }; - - #[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))] - unsafe extern "C" fn _mod_init() -> () $body - }; -} - -#[macro_export] -macro_rules! mod_fini { - ($body:block) => { - #[used] - #[cfg_attr(target_family = "unix", unsafe(link_section = ".fini_array"))] - static MOD_FINI: unsafe extern "C" fn() = { _mod_fini }; - - #[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))] - unsafe extern "C" fn _mod_fini() -> () $body - }; -} diff --git a/src/core/mods/mod.rs b/src/core/mods/mod.rs deleted file mode 100644 index b8f06f29f..000000000 --- a/src/core/mods/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -pub(crate) use libloading::os::unix::{Library, Symbol}; - -pub mod canary; -pub mod macros; -pub mod module; -pub mod new; -pub mod path; - -pub use module::Module; diff --git a/src/core/mods/module.rs b/src/core/mods/module.rs deleted file mode 100644 index 3c8183962..000000000 --- a/src/core/mods/module.rs +++ /dev/null @@ -1,75 +0,0 @@ -use std::{ - ffi::{CString, OsString}, - time::SystemTime, -}; - -use super::{Library, Symbol, canary, new, path}; -use crate::{Result, error}; - -pub struct Module { - handle: Option, - loaded: SystemTime, - path: OsString, -} - -impl Module { - pub fn from_name(name: &str) -> Result { Self::from_path(path::from_name(name)?) } - - pub fn from_path(path: OsString) -> Result { - Ok(Self { - handle: Some(new::from_path(&path)?), - loaded: SystemTime::now(), - path, - }) - } - - pub fn unload(&mut self) { - canary::prepare(); - self.close(); - if !canary::check_and_reset() { - let name = self.name().expect("Module is named"); - error!("Module {name:?} is stuck and failed to unload."); - } - } - - pub(crate) fn close(&mut self) { - if let Some(handle) = self.handle.take() { - handle.close().expect("Module handle closed"); - } - } - - pub fn get(&self, name: &str) -> Result> { - let cname = CString::new(name.to_owned()).expect("terminated string from provided name"); - let handle = self - .handle - .as_ref() - .expect("backing library loaded by this instance"); - - // SAFETY: Calls dlsym(3) on unix platforms. This might not have to be - // unsafe if wrapped in libloading with_dlerror(). - let sym = unsafe { handle.get::(cname.as_bytes()) }; - let sym = sym.expect("symbol found; binding successful"); - - Ok(sym) - } - - pub fn deleted(&self) -> Result { - let mtime = path::mtime(self.path())?; - let res = mtime > self.loaded; - - Ok(res) - } - - pub fn name(&self) -> Result { path::to_name(self.path()) } - - #[must_use] - pub fn path(&self) -> &OsString { &self.path } -} - -impl Drop for Module { - fn drop(&mut self) { - if self.handle.is_some() { - self.unload(); - } - } -} diff --git a/src/core/mods/new.rs b/src/core/mods/new.rs deleted file mode 100644 index 41eec89ef..000000000 --- a/src/core/mods/new.rs +++ /dev/null @@ -1,23 +0,0 @@ -use std::ffi::OsStr; - -use super::{Library, path}; -use crate::{Err, Result}; - -const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL; - -pub fn from_name(name: &str) -> Result { - let path = path::from_name(name)?; - from_path(&path) -} - -pub fn from_path(path: &OsStr) -> Result { - //SAFETY: Calls dlopen(3) on unix platforms. This might not have to be - // unsafe if wrapped in with_dlerror. - let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) }; - if let Err(e) = lib { - let name = path::to_name(path)?; - return Err!("Loading module {name:?} failed: {e}"); - } - - Ok(lib.expect("module loaded")) -} diff --git a/src/core/mods/path.rs b/src/core/mods/path.rs deleted file mode 100644 index b792890b9..000000000 --- a/src/core/mods/path.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::{ - env::current_exe, - ffi::{OsStr, OsString}, - path::{Path, PathBuf}, - time::SystemTime, -}; - -use libloading::library_filename; - -use crate::Result; - -pub fn from_name(name: &str) -> Result { - let root = PathBuf::new(); - let exe_path = current_exe()?; - let exe_dir = exe_path.parent().unwrap_or(&root); - let mut mod_path = exe_dir.to_path_buf(); - let mod_file = library_filename(name); - mod_path.push(mod_file); - - Ok(mod_path.into_os_string()) -} - -pub fn to_name(path: &OsStr) -> Result { - let path = Path::new(path); - let name = path - .file_stem() - .expect("path file stem") - .to_str() - .expect("name string"); - - let name = name.strip_prefix("lib").unwrap_or(name).to_owned(); - - Ok(name) -} - -pub fn mtime(path: &OsStr) -> Result { - let meta = std::fs::metadata(path)?; - let mtime = meta.modified()?; - - Ok(mtime) -} diff --git a/src/core/server.rs b/src/core/server.rs index c84936478..328eb50ae 100644 --- a/src/core/server.rs +++ b/src/core/server.rs @@ -27,10 +27,6 @@ pub struct Server { /// observable used on shutdown and should not be modified. pub stopping: AtomicBool, - /// Reload/shutdown desired indicator; when false, shutdown is desired. This - /// is an observable used on shutdown and modifying is not recommended. - pub reloading: AtomicBool, - /// Restart desired; when true, restart it desired after shutdown. pub restarting: AtomicBool, @@ -60,7 +56,6 @@ impl Server { config: config::Manager::new(config), started: SystemTime::now(), stopping: AtomicBool::new(false), - reloading: AtomicBool::new(false), restarting: AtomicBool::new(false), runtime, signal: broadcast::channel::<&'static str>(1).0, @@ -69,25 +64,6 @@ impl Server { } } - pub fn reload(&self) -> Result<()> { - if cfg!(any(not(conduwuit_mods), not(feature = "conduwuit_mods"))) { - return Err!("Reloading not enabled"); - } - - if self.reloading.swap(true, Ordering::AcqRel) { - return Err!("Reloading already in progress"); - } - - if self.stopping.swap(true, Ordering::AcqRel) { - return Err!("Shutdown already in progress"); - } - - self.signal("SIGINT").inspect_err(|_| { - self.stopping.store(false, Ordering::Release); - self.reloading.store(false, Ordering::Release); - }) - } - pub fn restart(&self) -> Result { if self.restarting.swap(true, Ordering::AcqRel) { return Err!("Restart already in progress"); @@ -146,9 +122,6 @@ impl Server { #[inline] pub fn is_stopping(&self) -> bool { self.stopping.load(Ordering::Relaxed) } - #[inline] - pub fn is_reloading(&self) -> bool { self.reloading.load(Ordering::Relaxed) } - #[inline] pub fn is_restarting(&self) -> bool { self.restarting.load(Ordering::Relaxed) } diff --git a/src/core/utils/future/bool_ext.rs b/src/core/utils/future/bool_ext.rs index 24f239ff8..16b4b5678 100644 --- a/src/core/utils/future/bool_ext.rs +++ b/src/core/utils/future/bool_ext.rs @@ -1,10 +1,8 @@ //! Extended external extensions to futures::FutureExt -use std::marker::Unpin; - use futures::{ Future, FutureExt, - future::{select_ok, try_join, try_join_all, try_select}, + future::{try_join, try_join_all}, }; pub trait BoolExt @@ -18,8 +16,8 @@ where fn or(self, b: B) -> impl Future + Send where - B: Future + Send + Unpin, - Self: Sized + Unpin; + B: Future + Send, + Self: Sized; } impl BoolExt for Fut @@ -44,20 +42,20 @@ where #[inline] fn or(self, b: B) -> impl Future + Send where - B: Future + Send + Unpin, - Self: Sized + Unpin, + B: Future + Send, + Self: Sized, { type Result = crate::Result<(), ()>; - let a = self.map(|a| a.then_some(()).ok_or(Result::Err(()))); + let a = self.map(|a| (!a).then_some(()).ok_or(Result::Err(()))); - let b = b.map(|b| b.then_some(()).ok_or(Result::Err(()))); + let b = b.map(|b| (!b).then_some(()).ok_or(Result::Err(()))); - try_select(a, b).map(|result| result.is_ok()) + try_join(a, b).map(|result| result.is_err()) } } -pub async fn and(args: I) -> impl Future + Send +pub fn and(args: I) -> impl Future + Send where I: Iterator + Send, F: Future + Send, @@ -69,14 +67,80 @@ where try_join_all(args).map(|result| result.is_ok()) } -pub async fn or(args: I) -> impl Future + Send +pub fn or(args: I) -> impl Future + Send where I: Iterator + Send, - F: Future + Send + Unpin, + F: Future + Send, { type Result = crate::Result<(), ()>; - let args = args.map(|a| a.map(|a| a.then_some(()).ok_or(Result::Err(())))); + let args = args.map(|a| a.map(|a| (!a).then_some(()).ok_or(Result::Err(())))); - select_ok(args).map(|result| result.is_ok()) + try_join_all(args).map(|result| result.is_err()) +} + +#[cfg(test)] +mod tests { + use std::pin::pin; + + use futures::future; + + use super::{BoolExt, and, or}; + + #[tokio::test] + async fn bool_ext_truth_tables() { + for a in [false, true] { + for b in [false, true] { + assert_eq!(future::ready(a).and(future::ready(b)).await, a && b, "and({a}, {b})"); + assert_eq!(future::ready(a).or(future::ready(b)).await, a || b, "or({a}, {b})"); + } + } + + assert!( + future::ready(false) + .or(future::ready(false)) + .or(future::ready(true)) + .await, + "chained or with trailing true must return true" + ); + assert!( + !future::ready(false) + .or(future::ready(false)) + .or(future::ready(false)) + .await, + "chained or with all false must return false" + ); + } + + #[tokio::test] + async fn bool_ext_short_circuits() { + let pend = pin!(future::pending::()); + assert!( + future::ready(true).or(pend).await, + "or must short-circuit on true without polling pending" + ); + + let pend = pin!(future::pending::()); + assert!( + !future::ready(false).and(pend).await, + "and must short-circuit on false without polling pending" + ); + } + + #[tokio::test] + async fn free_and_or() { + assert!(and(std::iter::empty::>()).await, "empty and is true"); + assert!(!or(std::iter::empty::>()).await, "empty or is false"); + + assert!(and([future::ready(true), future::ready(true)].into_iter()).await, "all true"); + assert!( + !and([future::ready(true), future::ready(false)].into_iter()).await, + "and with false" + ); + assert!( + or([future::ready(false), future::ready(true)].into_iter()).await, + "or with true" + ); + assert!(!or([future::ready(false), future::ready(false)].into_iter()).await, "all false"); + } } diff --git a/src/core/utils/math.rs b/src/core/utils/math.rs index 9316731c5..e11d0302a 100644 --- a/src/core/utils/math.rs +++ b/src/core/utils/math.rs @@ -62,14 +62,28 @@ macro_rules! validated { } #[inline] -#[allow(clippy::as_conversions)] +#[allow(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)] pub fn usize_from_f64(val: f64) -> Result { + // Exclusive upper bound for values whose truncation fits in `usize`. + // Note that `usize::MAX as f64` rounds up to 2^64 on 64-bit targets, so a + // strict `<` check against 2^(usize::BITS) rejects all out-of-range values + // on both 32-bit and 64-bit targets. + #[allow(clippy::cast_precision_loss)] + const MAX_USIZE_EXCLUSIVE: f64 = (1_u128 << usize::BITS) as f64; + + if !val.is_finite() { + return Err!(Arithmetic("Converting non-finite float to unsigned integer")); + } + if val < 0.0 { return Err!(Arithmetic("Converting negative float to unsigned integer")); } - //SAFETY: - Ok(unsafe { val.to_int_unchecked::() }) + if val >= MAX_USIZE_EXCLUSIVE { + return Err!(Arithmetic("Converting out-of-range float to unsigned integer")); + } + + Ok(val as usize) } #[inline] @@ -111,3 +125,33 @@ fn try_into_err, Src>(e: >::Error) -> Erro #[inline] pub fn clamp(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn usize_from_f64_valid() { + assert_eq!(usize_from_f64(0.0).unwrap(), 0); + assert_eq!(usize_from_f64(-0.0).unwrap(), 0); + assert_eq!(usize_from_f64(42.9).unwrap(), 42); + assert_eq!(usize_from_f64(1_048_576.0).unwrap(), 1_048_576); + } + + #[test] + fn usize_from_f64_rejects_invalid() { + usize_from_f64(-1.0).unwrap_err(); + usize_from_f64(-0.5).unwrap_err(); + usize_from_f64(f64::NAN).unwrap_err(); + usize_from_f64(f64::INFINITY).unwrap_err(); + usize_from_f64(f64::NEG_INFINITY).unwrap_err(); + usize_from_f64(1e30).unwrap_err(); + #[cfg(target_pointer_width = "64")] + { + // `usize::MAX as f64` rounds up to 2^64, which is out of range. + #[allow(clippy::as_conversions, clippy::cast_precision_loss)] + let rounded_max = usize::MAX as f64; + usize_from_f64(rounded_max).unwrap_err(); + } + } +} diff --git a/src/core/utils/result/inspect_log.rs b/src/core/utils/result/inspect_log.rs deleted file mode 100644 index e9f32663c..000000000 --- a/src/core/utils/result/inspect_log.rs +++ /dev/null @@ -1,62 +0,0 @@ -use std::fmt; - -use tracing::Level; - -use super::Result; -use crate::error; - -pub trait ErrLog -where - E: fmt::Display, -{ - fn log_err(self, level: Level) -> Self; - - #[inline] - fn err_log(self) -> Self - where - Self: Sized, - { - self.log_err(Level::ERROR) - } -} - -pub trait ErrDebugLog -where - E: fmt::Debug, -{ - fn log_err_debug(self, level: Level) -> Self; - - #[inline] - fn err_debug_log(self) -> Self - where - Self: Sized, - { - self.log_err_debug(Level::ERROR) - } -} - -impl ErrLog for Result -where - E: fmt::Display, -{ - #[inline] - fn log_err(self, level: Level) -> Self - where - Self: Sized, - { - self.inspect_err(|error| error::inspect_log_level(&error, level)) - } -} - -impl ErrDebugLog for Result -where - E: fmt::Debug, -{ - #[inline] - fn log_err_debug(self, level: Level) -> Self - where - Self: Sized, - { - self.inspect_err(|error| error::inspect_debug_log_level(&error, level)) - } -} diff --git a/src/core/utils/result/unwrap_infallible.rs b/src/core/utils/result/unwrap_infallible.rs index 99309e025..0baf87b66 100644 --- a/src/core/utils/result/unwrap_infallible.rs +++ b/src/core/utils/result/unwrap_infallible.rs @@ -1,7 +1,6 @@ use std::convert::Infallible; -use super::{DebugInspect, Result}; -use crate::error; +use super::Result; pub trait UnwrapInfallible { fn unwrap_infallible(self) -> T; @@ -10,8 +9,7 @@ pub trait UnwrapInfallible { impl UnwrapInfallible for Result { #[inline] fn unwrap_infallible(self) -> T { - // SAFETY: Branchless unwrap for errors that can never happen. In debug - // mode this is asserted. - unsafe { self.debug_inspect_err(error::infallible).unwrap_unchecked() } + let Ok(val) = self; + val } } diff --git a/src/core/utils/string/unquoted.rs b/src/core/utils/string/unquoted.rs index abf7bbc16..a23f49539 100644 --- a/src/core/utils/string/unquoted.rs +++ b/src/core/utils/string/unquoted.rs @@ -32,11 +32,12 @@ impl<'a> From<&'a str> for &'a Unquoted { fn from(s: &'a str) -> &'a Unquoted { let s: &'a str = s.unquote_infallible(); - //SAFETY: This is a pattern I lifted from ruma-identifiers for - // strong-type strs by wrapping in a tuple-struct. - #[allow(clippy::transmute_ptr_to_ptr)] + // SAFETY: `Unquoted` is `#[repr(transparent)]` over `str`, so + // `*const str` and `*const Unquoted` have identical layout and + // metadata, and the returned reference preserves lifetime `'a`. + #[allow(clippy::as_conversions)] unsafe { - std::mem::transmute(s) + &*(std::ptr::from_ref::(s) as *const Unquoted) } } } diff --git a/src/core/utils/sys/compute.rs b/src/core/utils/sys/compute.rs index 91abddc28..76795be04 100644 --- a/src/core/utils/sys/compute.rs +++ b/src/core/utils/sys/compute.rs @@ -120,21 +120,13 @@ pub fn cores_available() -> impl Iterator { from_mask(*CORES_AVAILABL pub fn getcpu() -> Result { use crate::{Error, utils::math}; - // SAFETY: This is part of an interface with many low-level calls taking - // many raw params, but it's unclear why this specific call is unsafe. - // Nevertheless the value obtained here is semantically unsafe because it - // can change on the instruction boundary trailing its own acquisition and - // also any other time. + // SAFETY: `sched_getcpu(2)` takes no pointers and has no preconditions. + // Note that it may still return -1 with errno set (e.g. under seccomp + // filters or kernels without getcpu support), so the error branch below + // must remain live. let ret: i32 = unsafe { libc::sched_getcpu() }; - #[cfg(target_os = "linux")] - // SAFETY: On modern linux systems with a vdso if we can optimize away the branch checking - // for error (see getcpu(2)) then this system call becomes a memory access. - unsafe { - std::hint::assert_unchecked(ret >= 0); - }; - - if ret == -1 { + if ret < 0 { return Err(Error::from_errno()); } diff --git a/src/database/Cargo.toml b/src/database/Cargo.toml index 6b04c624d..8512c1362 100644 --- a/src/database/Cargo.toml +++ b/src/database/Cargo.toml @@ -34,8 +34,6 @@ jemalloc_stats = [ ] release_max_log_level = [ "conduwuit-core/release_max_log_level", - "log/max_level_trace", - "log/release_max_level_info", "tracing/max_level_trace", "tracing/release_max_level_info", ] @@ -60,7 +58,6 @@ const-str.workspace = true ctor.workspace = true dtor.workspace = true futures.workspace = true -log.workspace = true minicbor.workspace = true minicbor-serde.workspace = true rust-rocksdb.workspace = true diff --git a/src/database/de.rs b/src/database/de.rs index 9ff209f0f..0e9d5f5bb 100644 --- a/src/database/de.rs +++ b/src/database/de.rs @@ -472,17 +472,5 @@ impl<'a, 'de: 'a> de::MapAccess<'de> for &'a mut Deserializer<'de> { } } -// activate when stable; too soon now -//#[cfg(debug_assertions)] #[inline] fn deserialize_str(input: &[u8]) -> Result<&str> { string::str_from_bytes(input) } - -//#[cfg(not(debug_assertions))] -#[cfg(disable)] -#[inline] -fn deserialize_str(input: &[u8]) -> Result<&str> { - // SAFETY: Strings were written by the serializer to the database. Assuming - // no database corruption, the string will be valid. Database corruption is - // detected via rocksdb checksums. - unsafe { std::str::from_utf8_unchecked(input) } -} diff --git a/src/database/engine/backup.rs b/src/database/engine/backup.rs index 9c6d899c7..ca874e7e9 100644 --- a/src/database/engine/backup.rs +++ b/src/database/engine/backup.rs @@ -76,8 +76,7 @@ impl super::Engine { .config .database_backup_path .clone() - .map(PathBuf::into_os_string) - .unwrap_or_default(); + .map_or_default(PathBuf::into_os_string); if path.is_empty() { return Err!(Config("database_backup_path", "Configure path to enable backups")); diff --git a/src/database/map.rs b/src/database/map.rs index ed38e1fc3..067e3c263 100644 --- a/src/database/map.rs +++ b/src/database/map.rs @@ -46,6 +46,10 @@ use crate::{Engine, watchers::Watchers}; pub struct Map { name: &'static str, watchers: Watchers, + /// SAFETY / DROP ORDER: `cf` holds a lifetime-erased RocksDB column family + /// handle (see `open::open`) and MUST be declared before `db` so that the + /// handle is destroyed before `Engine` (and the underlying RocksDB `DB`) + /// can be dropped. cf: Arc, db: Arc, read_options: ReadOptions, diff --git a/src/database/map/open.rs b/src/database/map/open.rs index 97c505159..a81e501c2 100644 --- a/src/database/map/open.rs +++ b/src/database/map/open.rs @@ -1,10 +1,24 @@ use std::sync::Arc; -use rocksdb::ColumnFamily; +use rocksdb::{BoundColumnFamily, ColumnFamily}; use crate::Engine; pub(super) fn open(db: &Arc, name: &str) -> Arc { + // Compile-time guard: `BoundColumnFamily` and `ColumnFamily` are both + // `#[repr(Rust)]` in `rust-rocksdb`, so fail compilation if their size or + // alignment ever diverge. + const { + assert!( + size_of::>() == size_of::(), + "BoundColumnFamily and ColumnFamily must have identical size" + ); + assert!( + align_of::>() == align_of::(), + "BoundColumnFamily and ColumnFamily must have identical alignment" + ); + } + let bounded_arc = db.cf(name); let bounded_ptr = Arc::into_raw(bounded_arc); let cf_ptr = bounded_ptr.cast::(); diff --git a/src/database/map/stream.rs b/src/database/map/stream.rs index b2da4743e..bf82f489c 100644 --- a/src/database/map/stream.rs +++ b/src/database/map/stream.rs @@ -12,6 +12,17 @@ impl super::Map { /// Iterate key-value entries in the map from the beginning. /// /// - Result is deserialized + /// + /// # Unsoundness + /// Because Rust's `Stream` trait does not support lending items tied to + /// `&mut self`, `stream::slice_longevity` unsafely extends the lifetime of + /// raw RocksDB iterator slices to `'a` (the borrow of `Arc`). As a + /// consequence, borrowed deserialized types (e.g. `&str`, `&UserId`, + /// `&[u8]`) reference the underlying RocksDB cursor buffer and are + /// invalidated on the next poll of the stream. Do not hold borrowed items + /// across polls (e.g. via `collect()`, `ready_chunks()`, `peekable()`, + /// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband`) without + /// converting them to owned values first. pub fn stream<'a, K, V>( self: &'a Arc, ) -> impl Stream>> + Send diff --git a/src/database/maps.rs b/src/database/maps.rs index 013fc9270..35bc75f5e 100644 --- a/src/database/maps.rs +++ b/src/database/maps.rs @@ -153,6 +153,11 @@ pub(super) static MAPS: &[Descriptor] = &[ index_size: 512, ..descriptor::SEQUENTIAL }, + Descriptor { + name: "pduid_unredactedcontent", + key_size_hint: Some(16), + ..descriptor::SEQUENTIAL + }, Descriptor { name: "publicroomids", ..descriptor::RANDOM_SMALL @@ -227,6 +232,10 @@ pub(super) static MAPS: &[Descriptor] = &[ name: "roomsynctoken_shortstatehash", ..descriptor::DROPPED }, + Descriptor { + name: "roomts_pduid", + ..descriptor::SEQUENTIAL_SMALL + }, Descriptor { name: "roomuserdataid_accountdata", ..descriptor::RANDOM_SMALL diff --git a/src/database/mod.rs b/src/database/mod.rs index fcc4f4df7..020530219 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -5,9 +5,6 @@ extern crate rust_rocksdb as rocksdb; conduwuit_macros::introspect_crate! {} -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - #[cfg(test)] mod benches; mod cork; diff --git a/src/database/pool.rs b/src/database/pool.rs index f13de6272..87859c859 100644 --- a/src/database/pool.rs +++ b/src/database/pool.rs @@ -54,8 +54,14 @@ pub(crate) struct Get { /// Note: only initial seek is supported at this time on the assumption rocksdb /// prefetching prevents mid-iteration polls from blocking on I/O. pub(crate) struct Seek { - pub(crate) map: Arc, + /// SAFETY / DROP ORDER: `state` wraps a RocksDB + /// `DBRawIteratorWithThreadMode` referencing `map.db.db` whose lifetime has + /// been erased to `'static`. `state` MUST be declared before `map` so the + /// iterator is destroyed before `map` (and potentially the last + /// `Arc`) can be dropped if `Seek` is dropped early (e.g. on + /// cancellation or queue closure). pub(crate) state: stream::State<'static>, + pub(crate) map: Arc, pub(crate) dir: Direction, pub(crate) key: Option, pub(crate) res: Option>>, @@ -416,24 +422,30 @@ impl Drop for Pool { } fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> { - // SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice) - // through the channel. The lifetime on the handle is a device by - // rust-rocksdb to associate a database lifetime with its assets. The - // Handle must be dropped before the database is dropped. + // SAFETY: Necessary to send `Handle` (which wraps + // `rocksdb::DBPinnableSlice`) through the oneshot channel. The lifetime on + // `Handle` ties it to the RocksDB `DB` instance; callers of `execute_get` + // borrow `&self.db.pool` (which is owned by `Engine`), ensuring the + // received `BatchResult<'_>` cannot outlive the database. unsafe { std::mem::transmute(result) } } fn into_recv_get<'a>(result: BatchResult<'static>) -> BatchResult<'a> { - // SAFETY: This is to receive the Handle from the channel. + // SAFETY: Shrinking the erased `'static` lifetime back to `'a` (borrowed + // from `&self.db.pool`). `SmallVec` is invariant over `A`, so this + // cannot be done via implicit covariance. unsafe { std::mem::transmute(result) } } pub(crate) fn into_send_seek(result: stream::State<'_>) -> stream::State<'static> { - // SAFETY: Necessary to send the State through the channel; see above. + // SAFETY: Necessary to send `stream::State` through the pool channel. + // While in flight on the queue, `Seek` owns an `Arc` (declared after + // `state` so `state` drops first on early cancellation); once received back + // from `execute_iter`, the lifetime is shrunk via `into_recv_seek` to the + // caller's borrow of `&self.db.pool` (and `&'a Arc`), ensuring the + // returned `stream::State<'_>` cannot outlive the database. unsafe { std::mem::transmute(result) } } -fn into_recv_seek(result: stream::State<'static>) -> stream::State<'static> { - // SAFETY: This is to receive the State from the channel; see above. - unsafe { std::mem::transmute(result) } -} +#[inline] +const fn into_recv_seek<'a>(result: stream::State<'static>) -> stream::State<'a> { result } diff --git a/src/database/stream.rs b/src/database/stream.rs index ddcaa32c8..1cf690000 100644 --- a/src/database/stream.rs +++ b/src/database/stream.rs @@ -133,22 +133,20 @@ fn keyval_longevity<'a, 'b: 'a>(item: KeyVal<'a>) -> KeyVal<'b> { } fn slice_longevity<'a, 'b: 'a>(item: &'a Slice) -> &'b Slice { - // SAFETY: The lifetime of the data returned by the rocksdb cursor is only - // valid between each movement of the cursor. It is hereby unsafely - // extended to match the lifetime of the cursor itself. This is due to the - // limitation of the Stream trait where the Item is incapable of conveying - // a lifetime; this is due to GAT's being unstable during its development. - // This unsafety can be removed as soon as this limitation is addressed by - // an upcoming version. + // SAFETY: the lifetime of the data returned by + // the RocksDB cursor is only valid until the next movement of the cursor, + // but is unsafely extended here to match the lifetime `'b` of the `Map` + // borrow because `futures::Stream` is not a lending stream. // - // We have done our best to mitigate the implications of this in conjunction - // with the deserialization API such that borrows being held across - // movements of the cursor do not happen accidentally. The compiler will - // still error when values herein produced try to leave a closure passed to - // a StreamExt API. But escapes can happen if you explicitly and - // intentionally attempt it, and there will be no compiler error or - // warning. This is primarily the case with calling collect() without a - // preceding map(ToOwned::to_owned). A collection of references here is - // illegal, but this will not be enforced by the compiler. + // Callers MUST NOT hold borrowed items (or borrowed deserialized views such + // as `&str`, `&UserId`, or `&[u8]`) across subsequent polls of the stream — + // in particular, never call `collect()`, `ready_chunks()`, `peekable()`, + // `buffered()`, `buffer_unordered()`, `broadband`, or `wideband` on a + // stream yielding borrowed references without first converting items to + // owned values (e.g. `map(ToOwned::to_owned)`). The compiler does NOT + // reject such escapes when items borrow from `'b`. + // + // TODO: Fix this, it is old code and language changes may have made it + // unnecessary unsafe { std::mem::transmute(item) } } diff --git a/src/database/util.rs b/src/database/util.rs index bcefa2867..a04f0b0af 100644 --- a/src/database/util.rs +++ b/src/database/util.rs @@ -1,28 +1,12 @@ use conduwuit::Result; use rocksdb::{Direction, ErrorKind, IteratorMode}; -//#[cfg(debug_assertions)] macro_rules! unhandled { ($msg:literal) => { unimplemented!($msg) }; } -// activate when stable; we're not ready for this yet -#[cfg(disable)] // #[cfg(not(debug_assertions))] -macro_rules! unhandled { - ($msg:literal) => { - // SAFETY: Eliminates branches for serializing and deserializing types never - // encountered in the codebase. This can promote optimization and reduce - // codegen. The developer must verify for every invoking callsite that the - // unhandled type is in no way involved and could not possibly be - // encountered. - unsafe { - std::hint::unreachable_unchecked(); - } - }; -} - pub(crate) use unhandled; #[inline] diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index 3fbcbe3b4..40162bd5c 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -70,14 +70,12 @@ standard = [ ] full = [ "standard", - # "hardened_malloc", # Conflicts with jemalloc "jemalloc_prof", "perf_measurements", "tokio_console", ] brotli_compression = [ - "conduwuit-api/brotli_compression", "conduwuit-core/brotli_compression", "conduwuit-router/brotli_compression", "conduwuit-service/brotli_compression", @@ -89,34 +87,33 @@ direct_tls = [ "conduwuit-router/direct_tls" ] element_hacks = [ - "conduwuit-api/element_hacks", "conduwuit-service/element_hacks", + "conduwuit-router/element_hacks", ] gzip_compression = [ - "conduwuit-api/gzip_compression", "conduwuit-core/gzip_compression", "conduwuit-router/gzip_compression", "conduwuit-service/gzip_compression", ] -hardened_malloc = [ - "conduwuit-core/hardened_malloc", -] http3 = [ - "reqwest/http3" + "conduwuit-service/http3" ] ring = [ - "rustls/ring" + "rustls/ring", ] + aws_lc_rs = [ "rustls/aws_lc_rs", - "dep:aws-lc-rs" ] io_uring = [ - "conduwuit-database/io_uring", + "conduwuit-service/io_uring", ] jemalloc = [ "conduwuit-core/jemalloc", - "conduwuit-database/jemalloc", + "conduwuit-service/jemalloc", +] +mimalloc = [ + "conduwuit-core/mimalloc", ] jemalloc_prof = [ "conduwuit-core/jemalloc_prof", @@ -145,19 +142,13 @@ perf_measurements = [ release_max_log_level = [ "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", - "conduwuit-admin/release_max_log_level", - "conduwuit-api/release_max_log_level", "conduwuit-core/release_max_log_level", - "conduwuit-database/release_max_log_level", "conduwuit-router/release_max_log_level", "conduwuit-service/release_max_log_level", ] sentry_telemetry = [ "dep:sentry", "dep:sentry-tracing", - "dep:sentry-tower", "conduwuit-core/sentry_telemetry", "conduwuit-router/sentry_telemetry", ] @@ -180,22 +171,17 @@ url_preview = [ "conduwuit-service/url_preview", ] zstd_compression = [ - "conduwuit-api/zstd_compression", "conduwuit-core/zstd_compression", - "conduwuit-database/zstd_compression", "conduwuit-router/zstd_compression", "conduwuit-service/zstd_compression", ] -conduwuit_mods = [ - "conduwuit-core/conduwuit_mods", -] bindgen-static = [ # "bindgen/static" # "clang-sys/static" - "conduwuit-database/bindgen-static" + "conduwuit-service/bindgen-static" ] bindgen-runtime = [ - "conduwuit-database/bindgen-runtime" + "conduwuit-service/bindgen-runtime" ] [build-dependencies] @@ -203,10 +189,7 @@ bindgen-runtime = [ # clang-sys = {version = "1", default-features = false} [dependencies] -conduwuit-admin.workspace = true -conduwuit-api.workspace = true conduwuit-core.workspace = true -conduwuit-database.workspace = true conduwuit-router.workspace = true conduwuit-service.workspace = true conduwuit-build-metadata.workspace = true @@ -218,7 +201,6 @@ dtor.workspace = true console-subscriber.optional = true console-subscriber.workspace = true const-str.workspace = true -log.workspace = true opentelemetry.workspace = true opentelemetry-otlp.optional = true opentelemetry-otlp.workspace = true @@ -226,14 +208,10 @@ opentelemetry-prometheus.workspace = true opentelemetry-semantic-conventions.workspace = true opentelemetry_sdk.workspace = true prometheus.workspace = true -sentry-tower.optional = true -sentry-tower.workspace = true sentry-tracing.optional = true sentry-tracing.workspace = true sentry.optional = true sentry.workspace = true -tokio-metrics.optional = true -tokio-metrics.workspace = true tokio.workspace = true tracing-flame.optional = true tracing-flame.workspace = true @@ -243,14 +221,7 @@ tracing-subscriber.workspace = true tracing.workspace = true tracing-journald = { workspace = true, optional = true } parking_lot.workspace = true -reqwest = { workspace = true, default-features = false } rustls = { workspace = true, default-features = false } -aws-lc-rs = { version = "1.16.3", default-features = false, optional = true } - - -[target.'cfg(all(not(target_env = "msvc"), target_os = "linux"))'.dependencies] -hardened_malloc-rs.workspace = true -hardened_malloc-rs.optional = true [lints] workspace = true diff --git a/src/main/logging.rs b/src/main/logging.rs index c882fcb7f..8d54b1064 100644 --- a/src/main/logging.rs +++ b/src/main/logging.rs @@ -60,10 +60,18 @@ pub(crate) fn init( #[cfg(feature = "sentry_telemetry")] let subscriber = { + use tracing::Level; + use tracing_subscriber::filter::{LevelFilter, filter_fn}; + let sentry_filter = EnvFilter::try_new(&config.sentry_filter) .map_err(|e| err!(Config("sentry_filter", "{e}.")))?; - let sentry_layer = sentry_tracing::layer(); + let sentry_layer = sentry_tracing::SpanLayer::new() + .with_filter(LevelFilter::INFO) + .and_then(sentry_tracing::BreadcrumbLayer::new().with_filter(filter_fn(|metadata| { + matches!(*metadata.level(), Level::WARN | Level::INFO) + }))) + .and_then(sentry_tracing::ErrorLayer::new().with_filter(LevelFilter::ERROR)); let (sentry_reload_filter, sentry_reload_handle) = reload::Layer::new(sentry_filter); reload_handles.add("sentry", Box::new(sentry_reload_handle)); diff --git a/src/main/metrics.rs b/src/main/metrics.rs index 0e818c32c..370b790a8 100644 --- a/src/main/metrics.rs +++ b/src/main/metrics.rs @@ -26,18 +26,15 @@ pub(crate) fn init( let mut builder = SdkMeterProvider::builder() .with_resource(resource) - .with_view(|instrument: &Instrument| { - (instrument.name() == metric::HTTP_SERVER_REQUEST_DURATION) - .then(|| { - Stream::builder() - .with_aggregation(Aggregation::ExplicitBucketHistogram { - boundaries: duration_buckets(), - record_min_max: true, - }) - .build() - .ok() + .with_view(|instrument: &Instrument| match instrument.name() { + | metric::HTTP_SERVER_REQUEST_DURATION => Stream::builder() + .with_aggregation(Aggregation::ExplicitBucketHistogram { + boundaries: duration_buckets(), + record_min_max: true, }) - .flatten() + .build() + .ok(), + | _ => None, }); let registry = config diff --git a/src/main/mod.rs b/src/main/mod.rs index cdc8e27ce..7c5bbe200 100644 --- a/src/main/mod.rs +++ b/src/main/mod.rs @@ -10,7 +10,6 @@ mod clap; mod deadlock; mod logging; mod metrics; -mod mods; mod panic; mod restart; mod runtime; @@ -63,9 +62,8 @@ pub fn run_with_args(args: &Args) -> Result<()> { Ok(()) } -/// Operate the server normally in release-mode static builds. This will start, -/// run and stop the server within the asynchronous runtime. -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] +/// Operate the server. This will start, run and stop the server within the +/// asynchronous runtime. #[tracing::instrument( name = "main", parent = None, @@ -114,37 +112,3 @@ async fn async_main(server: &Arc) -> Result<(), Error> { debug_info!("Exit runtime"); Ok(()) } - -/// Operate the server in developer-mode dynamic builds. This will start, run, -/// and hot-reload portions of the server as-needed before returning for an -/// actual shutdown. This is not available in release-mode or static builds. -#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] -async fn async_main(server: &Arc) -> Result<(), Error> { - let mut starts = true; - let mut reloads = true; - while reloads { - if let Err(error) = mods::open(server).await { - error!("Loading router: {error}"); - return Err(error); - } - - let result = mods::run(server, starts).await; - if let Ok(result) = result { - (starts, reloads) = result; - } - - let force = !reloads || result.is_err(); - if let Err(error) = mods::close(server, force).await { - error!("Unloading router: {error}"); - return Err(error); - } - - if let Err(error) = result { - error!("{error}"); - return Err(error); - } - } - - debug_info!("Exit runtime"); - Ok(()) -} diff --git a/src/main/mods.rs b/src/main/mods.rs deleted file mode 100644 index 6140cc6e3..000000000 --- a/src/main/mods.rs +++ /dev/null @@ -1,160 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -#[unsafe(no_link)] -extern crate conduwuit_service; - -use std::{ - future::Future, - pin::Pin, - sync::{Arc, atomic::Ordering}, -}; - -use conduwuit_core::{Error, Result, debug, error, mods}; -use conduwuit_service::Services; - -use crate::Server; - -type StartFuncResult = Pin>> + Send>>; -type StartFuncProto = fn(&Arc) -> StartFuncResult; - -type RunFuncResult = Pin> + Send>>; -type RunFuncProto = fn(&Arc) -> RunFuncResult; - -type StopFuncResult = Pin> + Send>>; -type StopFuncProto = fn(Arc) -> StopFuncResult; - -const RESTART_THRESH: &str = "conduwuit_service"; -const MODULE_NAMES: &[&str] = &[ - //"conduwuit_core", - "conduwuit_database", - "conduwuit_service", - "conduwuit_api", - "conduwuit_admin", - "conduwuit_router", -]; - -#[cfg(panic_trap)] -conduwuit_core::mod_init! {{ - conduwuit_core::debug::set_panic_trap(); -}} - -pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, bool), Error> { - let main_lock = server.mods.read().await; - let main_mod = (*main_lock).last().expect("main module loaded"); - if starts { - let start = main_mod.get::("start")?; - match start(&server.server).await { - | Ok(services) => server.services.lock().await.insert(services), - | Err(error) => { - error!("Starting server: {error}"); - return Err(error); - }, - }; - } - - server.server.stopping.store(false, Ordering::Release); - - let run = main_mod.get::("run")?; - if let Err(error) = run(server - .services - .lock() - .await - .as_ref() - .expect("services initialized")) - .await - { - error!("Running server: {error}"); - return Err(error); - } - - let reloads = server.server.reloading.swap(false, Ordering::AcqRel); - - let stops = !reloads || stale(server).await? <= restart_thresh(); - let starts = reloads && stops; - if stops { - let stop = main_mod.get::("stop")?; - if let Err(error) = stop( - server - .services - .lock() - .await - .take() - .expect("services initialized"), - ) - .await - { - error!("Stopping server: {error}"); - return Err(error); - } - } - - Ok((starts, reloads)) -} - -pub(crate) async fn open(server: &Arc) -> Result { - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - "Loading modules", - ); - - for (i, name) in MODULE_NAMES.iter().enumerate() { - if mods.get(i).is_none() { - mods.push(mods::Module::from_name(name)?); - } - } - - Ok(mods.len()) -} - -pub(crate) async fn close(server: &Arc, force: bool) -> Result { - let stale = stale_count(server).await; - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - stale = %stale, - force, - "Unloading modules", - ); - - while mods.last().is_some() { - let module = &mods.last().expect("module"); - if force || module.deleted()? { - mods.pop(); - } else { - break; - } - } - - Ok(mods.len()) -} - -async fn stale_count(server: &Arc) -> usize { - let watermark = stale(server).await.unwrap_or(available()); - available().saturating_sub(watermark) -} - -async fn stale(server: &Arc) -> Result { - let mods_lock = server.mods.read().await; - let mods: &Vec = &mods_lock; - for (i, module) in mods.iter().enumerate() { - if module.deleted()? { - return Ok(i); - } - } - - Ok(mods.len()) -} - -fn restart_thresh() -> usize { - MODULE_NAMES - .iter() - .position(|&name| name.ends_with(RESTART_THRESH)) - .unwrap_or(MODULE_NAMES.len()) -} - -const fn available() -> usize { MODULE_NAMES.len() } diff --git a/src/main/sentry.rs b/src/main/sentry.rs index 0a013fa66..775d63406 100644 --- a/src/main/sentry.rs +++ b/src/main/sentry.rs @@ -1,19 +1,12 @@ #![cfg(feature = "sentry_telemetry")] -use std::{ - borrow::Cow, - str::FromStr, - sync::{Arc, OnceLock}, -}; +use std::{borrow::Cow, sync::OnceLock}; use conduwuit_build_metadata as build; use conduwuit_core::{config::Config, debug, trace}; use sentry::{ Breadcrumb, ClientOptions, Level, - types::{ - Dsn, - protocol::v7::{Context, Event}, - }, + types::protocol::v7::{Context, Event}, }; static SEND_PANIC: OnceLock = OnceLock::new(); @@ -37,22 +30,21 @@ fn options(config: &Config) -> ClientOptions { .expect("init_sentry should only be called if sentry is enabled and this is not None") .as_str(); - let server_name = config - .sentry_send_server_name - .then(|| config.server_name.to_string().into()); + let options = ClientOptions::new() + .dsn(dsn) + .traces_sample_rate(config.sentry_traces_sample_rate) + .debug(cfg!(debug_assertions)) + .maybe_release(release_name()) + .user_agent(conduwuit_core::user_agent()) + .attach_stacktrace(config.sentry_attach_stacktrace) + .before_send(before_send) + .before_breadcrumb(before_breadcrumb); - ClientOptions { - dsn: Some(Dsn::from_str(dsn).expect("sentry_endpoint must be a valid URL")), - server_name, - traces_sample_rate: config.sentry_traces_sample_rate, - debug: cfg!(debug_assertions), - release: release_name(), - user_agent: conduwuit_core::user_agent().into(), - attach_stacktrace: config.sentry_attach_stacktrace, - before_send: Some(Arc::new(before_send)), - before_breadcrumb: Some(Arc::new(before_breadcrumb)), - ..Default::default() - } + config + .sentry_send_server_name + .then(|| config.server_name.to_string()) + .into_iter() + .fold(options, ClientOptions::server_name) } fn before_send(event: Event<'static>) -> Option> { diff --git a/src/main/server.rs b/src/main/server.rs index 28b9039ef..e75c9777b 100644 --- a/src/main/server.rs +++ b/src/main/server.rs @@ -27,10 +27,6 @@ pub(crate) struct Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: Option<::sentry::ClientInitGuard>, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - // Module instances; TODO: move to mods::loaded mgmt vector - pub(crate) mods: tokio::sync::RwLock>, } impl Server { @@ -87,9 +83,6 @@ impl Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: sentry_guard, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - mods: tokio::sync::RwLock::new(Vec::new()), })) } diff --git a/src/main/signal.rs b/src/main/signal.rs index 42cade135..5cd9914fe 100644 --- a/src/main/signal.rs +++ b/src/main/signal.rs @@ -12,7 +12,6 @@ pub(super) async fn signal(server: Arc) { use unix::SignalKind; const CONSOLE: bool = cfg!(feature = "console"); - const RELOADING: bool = cfg!(all(conduwuit_mods, feature = "conduwuit_mods", not(CONSOLE))); let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler"); let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler"); @@ -30,9 +29,7 @@ pub(super) async fn signal(server: Arc) { } warn!("Received {sig}"); - let result = if RELOADING && sig == "SIGINT" { - server.server.reload() - } else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { + let result = if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { server.server.shutdown() } else { server.server.signal(sig) diff --git a/src/router/Cargo.toml b/src/router/Cargo.toml index e1e66373a..aa0bc9aca 100644 --- a/src/router/Cargo.toml +++ b/src/router/Cargo.toml @@ -25,9 +25,11 @@ brotli_compression = [ ] direct_tls = [ "axum-server/tls-rustls-no-provider", - "dep:rustls", "dep:axum-server-dual-protocol", ] +element_hacks = [ + "conduwuit-api/element_hacks", +] gzip_compression = [ "conduwuit-admin/gzip_compression", "conduwuit-api/gzip_compression", @@ -71,13 +73,9 @@ release_max_log_level = [ "conduwuit-service/release_max_log_level", "tracing/max_level_trace", "tracing/release_max_level_info", - "log/max_level_trace", - "log/release_max_level_info", ] sentry_telemetry = [ "conduwuit-core/sentry_telemetry", - "dep:sentry", - "dep:sentry-tracing", "dep:sentry-tower", ] systemd = [ @@ -110,17 +108,9 @@ http.workspace = true http-body-util.workspace = true hyper.workspace = true hyper-util.workspace = true -log.workspace = true opentelemetry-instrumentation-tower.workspace = true ruma.workspace = true -rustls.workspace = true -rustls.optional = true -sentry.optional = true -sentry.workspace = true -sentry-tower.optional = true -sentry-tower.workspace = true -sentry-tracing.optional = true -sentry-tracing.workspace = true +sentry-tower = { workspace = true, optional = true } serde_json.workspace = true tokio.workspace = true tower.workspace = true diff --git a/src/router/mod.rs b/src/router/mod.rs index c6f909d36..d907de7be 100644 --- a/src/router/mod.rs +++ b/src/router/mod.rs @@ -16,11 +16,7 @@ use conduwuit::{Error, Result, Server}; use conduwuit_service::Services; use futures::{Future, FutureExt, TryFutureExt}; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -#[unsafe(no_mangle)] -pub extern "Rust" fn start( +pub fn start( server: &Arc, ) -> Pin>> + Send>> { AssertUnwindSafe(run::start(server.clone())) @@ -30,10 +26,7 @@ pub extern "Rust" fn start( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn stop( - services: Arc, -) -> Pin> + Send>> { +pub fn stop(services: Arc) -> Pin> + Send>> { AssertUnwindSafe(run::stop(services)) .catch_unwind() .map_err(Error::from_panic) @@ -41,10 +34,7 @@ pub extern "Rust" fn stop( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn run( - services: &Arc, -) -> Pin> + Send>> { +pub fn run(services: &Arc) -> Pin> + Send>> { AssertUnwindSafe(run::run(services.clone())) .catch_unwind() .map_err(Error::from_panic) diff --git a/src/router/request.rs b/src/router/request.rs index d6a962727..2f0d7d7d2 100644 --- a/src/router/request.rs +++ b/src/router/request.rs @@ -64,7 +64,7 @@ pub(crate) async fn handle( .server .metrics .requests_handle_active - .fetch_add(1, Ordering::Relaxed), + .load(Ordering::Relaxed), handled = %services .server .metrics @@ -81,7 +81,11 @@ async fn execute( next: axum::middleware::Next, parent: &Span, ) -> Response { - #[cfg(debug_assertions)] + services + .server + .metrics + .requests_handle_active + .fetch_add(1, Ordering::Relaxed); conduwuit::defer! {{ _ = services.server .metrics diff --git a/src/router/router.rs b/src/router/router.rs index c482bfb79..9267a6ce0 100644 --- a/src/router/router.rs +++ b/src/router/router.rs @@ -8,7 +8,11 @@ use ruma::api::error::ErrorKind; pub(crate) fn build(services: &Arc) -> (Router, Guard) { let router = Router::::new(); - let (state, guard) = state::create(services.clone()); + // SAFETY: `guard` is returned alongside `router` and held in `serve()` + // until the HTTP server has finished serving all requests and dropped + // `router`, ensuring no `State` copy can be dereferenced after `Services` + // is dropped. + let (state, guard) = unsafe { state::create(services.clone()) }; let router = conduwuit_api::router::build(router, state) .merge(conduwuit_web::build(services)) .fallback(not_found) diff --git a/src/router/run.rs b/src/router/run.rs index bff30367a..f5a2ebb2f 100644 --- a/src/router/run.rs +++ b/src/router/run.rs @@ -25,7 +25,7 @@ pub(crate) async fn run(services: Arc) -> Result<()> { debug!("Start"); // Install the admin room callback here for now - admin::init(&services.admin).await; + admin::init(&services.admin); // Setup shutdown/signal handling let handle = ServerHandle::new(); @@ -60,7 +60,7 @@ pub(crate) async fn run(services: Arc) -> Result<()> { _ = sigs.await; // Remove the admin room callback - admin::fini(&services.admin).await; + admin::fini(&services.admin); debug_info!("Finish"); res diff --git a/src/router/serve/unix.rs b/src/router/serve/unix.rs index 9bb3dd6e0..ceba1c1b9 100644 --- a/src/router/serve/unix.rs +++ b/src/router/serve/unix.rs @@ -22,7 +22,7 @@ use hyper_util::{ use tokio::{ fs, net::{UnixListener, UnixStream, unix::SocketAddr}, - sync::broadcast::{self}, + sync::broadcast, task::JoinSet, time::{Duration, sleep}, }; diff --git a/src/ruminuwuity/Cargo.toml b/src/ruminuwuity/Cargo.toml index 0bdcb2f90..d523ce8a6 100644 --- a/src/ruminuwuity/Cargo.toml +++ b/src/ruminuwuity/Cargo.toml @@ -25,7 +25,7 @@ http.workspace = true ruma.workspace = true serde = { workspace = true } serde_json = { workspace = true } -wildmatch = "2.6.1" +wildmatch.workspace = true [dev-dependencies] diff --git a/src/service/Cargo.toml b/src/service/Cargo.toml index 60a362608..28c1f78a9 100644 --- a/src/service/Cargo.toml +++ b/src/service/Cargo.toml @@ -16,6 +16,12 @@ crate-type = [ ] [features] +bindgen-runtime = [ + "conduwuit-database/bindgen-runtime" +] +bindgen-static = [ + "conduwuit-database/bindgen-static" +] brotli_compression = [ "conduwuit-core/brotli_compression", "reqwest/brotli", @@ -29,6 +35,9 @@ gzip_compression = [ "conduwuit-core/gzip_compression", "reqwest/gzip", ] +http3 = [ + "reqwest/http3" +] io_uring = [ "conduwuit-database/io_uring", ] @@ -96,6 +105,7 @@ itertools.workspace = true log.workspace = true loole.workspace = true lru-cache.workspace = true +mime.workspace = true nonzero_ext.workspace = true p256.workspace = true regex.workspace = true @@ -122,6 +132,9 @@ lettre.workspace = true resolvematrix.workspace = true serde_urlencoded.workspace = true openidconnect.workspace = true +# We use this to set TLS backend features on the outdated reqwest bundled by openidconnect, +# which is necessary to call `danger_accept_invalid_certs`. +reqwest_0_12.workspace = true rand.workspace = true [target.'cfg(all(unix, target_os = "linux"))'.dependencies] @@ -130,3 +143,10 @@ sd-notify.optional = true [lints] workspace = true + +[package.metadata.cargo-shear] +ignored = ["reqwest_0_12"] + +[dev-dependencies] +opentelemetry.workspace = true +rustls = { workspace = true, features = ["ring"] } diff --git a/src/service/account_data/mod.rs b/src/service/account_data/mod.rs index 52e9cb9b2..14301ee91 100644 --- a/src/service/account_data/mod.rs +++ b/src/service/account_data/mod.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use conduwuit::{ Err, Result, err, - utils::{ReadyExt, result::LogErr, stream::TryIgnore}, + utils::{MutexMap, ReadyExt, result::LogErr, stream::TryIgnore}, }; use database::{Deserialized, Handle, Ignore, Json, Map}; use futures::{Stream, StreamExt, TryFutureExt}; @@ -27,6 +27,7 @@ pub enum AnyRawAccountDataEvent { pub struct Service { services: Services, db: Data, + update_mutex: MutexMap, } struct Data { @@ -50,6 +51,7 @@ impl crate::Service for Service { roomuserdataid_accountdata: args.db["roomuserdataid_accountdata"].clone(), roomusertype_roomuserdataid: args.db["roomusertype_roomuserdataid"].clone(), }, + update_mutex: MutexMap::new(), })) } @@ -71,6 +73,10 @@ impl Service { return Err!(Request(InvalidParam("Account data doesn't have all required fields."))); } + // Two updates reading the same previous entry would both remove it, + // and the entry of the one that lost the index would stay forever. + let _lock = self.update_mutex.lock(user_id).await; + let count = self.services.globals.next_count().unwrap(); let roomuserdataid = (room_id, user_id, count, &event_type); self.db diff --git a/src/service/admin/execute.rs b/src/service/admin/execute.rs index 3ab282740..0a6f64ff5 100644 --- a/src/service/admin/execute.rs +++ b/src/service/admin/execute.rs @@ -1,6 +1,7 @@ +#[cfg(feature = "console")] use std::io::IsTerminal; -use conduwuit::{Err, Result, debug, debug_info, error, info, warn}; +use conduwuit::{Err, Result, debug, debug_info, error, info}; use ruma::events::room::message::RoomMessageEventContent; use tokio::time::{Duration, sleep}; @@ -15,7 +16,7 @@ impl super::Service { #[cfg(feature = "console")] if self.services.server.config.admin_console_automatic { if !std::io::stdin().is_terminal() { - warn!("Console enabled without a tty available; Not enabling console"); + conduwuit::warn!("Console enabled without a tty available; Not enabling console"); return; } diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index 15dc33d50..923c2f15c 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -27,7 +27,6 @@ use ruma::{ }, }, }; -use tokio::sync::RwLock; use crate::{ Dep, account_data, config, globals, @@ -38,7 +37,7 @@ use crate::{ pub struct Service { services: Services, channel: (Sender, Receiver), - pub handle: RwLock>, + pub handle: SyncRwLock>, pub complete: SyncRwLock>, #[cfg(feature = "console")] pub console: Arc, @@ -131,7 +130,7 @@ impl crate::Service for Service { media: args.depend::("media"), }, channel: loole::bounded(COMMAND_QUEUE_LIMIT), - handle: RwLock::new(None), + handle: SyncRwLock::new(None), complete: SyncRwLock::new(None), #[cfg(feature = "console")] console: console::Console::new(&args), @@ -372,8 +371,11 @@ impl Service { } async fn process_command(&self, command: CommandInput) -> ProcessorResult { - let handle_guard = self.handle.read().await; - let handle = handle_guard.as_ref().expect("Admin module is not loaded"); + let handle = *self + .handle + .read() + .as_ref() + .expect("Admin module is not loaded"); let services = self .services diff --git a/src/service/antispam/mod.rs b/src/service/antispam/mod.rs index 3e235e264..93eda539b 100644 --- a/src/service/antispam/mod.rs +++ b/src/service/antispam/mod.rs @@ -8,7 +8,7 @@ use ruma::{ }; use ruminuwuity::{draupnir_antispam, meowlnir_antispam}; -use crate::{client, config, sending, service::Dep}; +use crate::{client, config, rooms::membership::JoinConditionResult, sending, service::Dep}; struct Services { server: Arc, @@ -103,7 +103,7 @@ impl Service { } else { Ok(()) }; - self.record("user_may_invite", &result); + self.record("user_may_invite", if result.is_ok() { "allowed" } else { "denied" }); return result; } Ok(()) @@ -149,7 +149,7 @@ impl Service { } else { Ok(()) }; - self.record("user_may_join_room", &result); + self.record("user_may_join_room", if result.is_ok() { "allowed" } else { "denied" }); return result; } Ok(()) @@ -161,10 +161,10 @@ impl Service { &self, room_id: OwnedRoomId, user_id: OwnedUserId, - ) -> Result<()> { + ) -> JoinConditionResult { if let Some(Antispam { meowlnir: Some(meowlnir), .. }) = &self.services.config.antispam { debug!(?room_id, ?user_id, "Asking meowlnir for accept_make_join"); - let result = self + match self .send_antispam_request( meowlnir.base_url.as_str(), &meowlnir.secret, @@ -175,18 +175,24 @@ impl Service { ), ) .await - .inspect(|_| debug!("meowlnir allowed the make_join")) - .inspect_err(|e| debug!("meowlnir denied the make_join: {e:?}")) - .map(|_| ()); - self.record("accept_make_join", &result); - result + { + | Ok(_) => { + debug!("meowlnir allowed the make_join"); + self.record("accept_make_join", "allowed"); + JoinConditionResult::Satisfied + }, + | Err(err) => { + debug!("meowlnir denied the make_join: {err:?}"); + self.record("accept_make_join", "denied"); + JoinConditionResult::Unsatisfied + }, + } } else { - Ok(()) + JoinConditionResult::UnableToAuthorizeJoin } } - fn record(&self, check: &'static str, result: &Result) { - let outcome = if result.is_ok() { "allowed" } else { "denied" }; + fn record(&self, check: &'static str, outcome: &'static str) { self.services .server .metrics diff --git a/src/service/appservice/mod.rs b/src/service/appservice/mod.rs index 9a4d6f772..8a69921a3 100644 --- a/src/service/appservice/mod.rs +++ b/src/service/appservice/mod.rs @@ -1,20 +1,19 @@ mod namespace_regex; mod registration_info; -use std::{collections::BTreeMap, iter::IntoIterator, sync::Arc}; +use std::{collections::BTreeMap, sync::Arc}; use async_trait::async_trait; -use conduwuit::{Err, Result, err, utils::stream::IterStream}; +use conduwuit::{Err, Result, SyncRwLock, SyncRwLockReadGuard, err, utils::stream::IterStream}; use database::Map; -use futures::{Future, FutureExt, Stream, TryStreamExt}; +use futures::{Stream, TryStreamExt}; use ruma::{RoomAliasId, RoomId, UserId, api::appservice::Registration}; -use tokio::sync::{RwLock, RwLockReadGuard}; pub use self::{namespace_regex::NamespaceRegex, registration_info::RegistrationInfo}; use crate::{Dep, globals, sending, users}; pub struct Service { - registration_info: RwLock, + registration_info: SyncRwLock, services: Services, db: Data, } @@ -35,7 +34,7 @@ type Registrations = BTreeMap; impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { Ok(Arc::new(Self { - registration_info: RwLock::new(BTreeMap::new()), + registration_info: SyncRwLock::new(BTreeMap::new()), services: Services { globals: args.depend::("globals"), sending: args.depend::("sending"), @@ -123,7 +122,6 @@ impl Service { self.registration_info .write() - .await .insert(id, registration.try_into()?); Ok(()) @@ -139,7 +137,7 @@ impl Service { // Check for token collision with other appservices (allow // re-registration of same appservice) - if let Ok(existing) = self.find_from_token(®istration.as_token).await { + if let Ok(existing) = self.find_from_token(®istration.as_token) { if existing.registration.id != registration.id { return Err(err!(Request(InvalidParam( "Cannot register appservice: Token is already used by appservice '{}'. \ @@ -182,7 +180,6 @@ impl Service { // removes the appservice registration info self.registration_info .write() - .await .remove(appservice_id) .ok_or_else(|| err!("Appservice not found"))?; @@ -197,19 +194,17 @@ impl Service { .await } - pub async fn get_registration(&self, id: &str) -> Option { + pub fn get_registration(&self, id: &str) -> Option { self.registration_info .read() - .await .get(id) .cloned() .map(|info| info.registration) } /// Returns Result to match users::find_from_token for select_ok usage - pub async fn find_from_token(&self, token: &str) -> Result { + pub fn find_from_token(&self, token: &str) -> Result { self.read() - .await .values() .find(|info| info.registration.as_token == token) .cloned() @@ -217,26 +212,21 @@ impl Service { } /// Checks if a given user id matches any exclusive appservice regex - pub async fn is_exclusive_user_id(&self, user_id: &UserId) -> bool { + pub fn is_exclusive_user_id(&self, user_id: &UserId) -> bool { self.read() - .await .values() .any(|info| info.is_exclusive_user_match(user_id)) } /// Checks if a given user id matches any appservice regex, exclusive or /// otherwise - pub async fn is_user_id(&self, user_id: &UserId) -> bool { - self.read() - .await - .values() - .any(|info| info.is_user_match(user_id)) + pub fn is_user_id(&self, user_id: &UserId) -> bool { + self.read().values().any(|info| info.is_user_match(user_id)) } /// Checks if a given room alias matches any exclusive appservice regex - pub async fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool { + pub fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool { self.read() - .await .values() .any(|info| info.aliases.is_exclusive_match(alias.as_str())) } @@ -245,19 +235,15 @@ impl Service { /// /// TODO: use this? #[allow(dead_code)] - pub async fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool { + pub fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool { self.read() - .await .values() .any(|info| info.rooms.is_exclusive_match(room_id.as_str())) } pub fn iter_ids(&self) -> impl Stream + Send { - self.read() - .map(|info| info.keys().cloned().collect::>()) - .map(IntoIterator::into_iter) - .map(IterStream::stream) - .flatten_stream() + let ids: Vec = self.read().keys().cloned().collect(); + ids.stream() } pub fn iter_db_ids(&self) -> impl Stream> + Send { @@ -281,7 +267,5 @@ impl Service { }) } - pub fn read(&self) -> impl Future> + Send { - self.registration_info.read() - } + pub fn read(&self) -> SyncRwLockReadGuard<'_, Registrations> { self.registration_info.read() } } diff --git a/src/service/client/dns_resolver.rs b/src/service/client/dns_resolver.rs new file mode 100644 index 000000000..97c534704 --- /dev/null +++ b/src/service/client/dns_resolver.rs @@ -0,0 +1,61 @@ +use std::{ + net::{IpAddr, SocketAddr}, + sync::Arc, +}; + +use hickory_resolver::{Resolver, net::runtime::TokioRuntimeProvider}; +use reqwest::dns::{Addrs, Resolving}; + +/// A simple struct to implement reqwest::dns::Resolve, as that is what's +/// required by the reqwest client builder. Most code is based on +/// reqwest::dns::HickoryDnsResolver, which we here have to almost re-create +/// because it's pub(crate) instead of pub: +pub struct DnsResolver { + resolver: Arc, +} + +type TokioResolver = Resolver; + +impl DnsResolver { + pub(crate) fn new(resolver: Arc) -> Self { Self { resolver } } +} + +struct SocketAddrs { + iter: std::vec::IntoIter, +} + +impl Iterator for SocketAddrs { + type Item = SocketAddr; + + fn next(&mut self) -> Option { + self.iter.next().map(|ip_addr| SocketAddr::new(ip_addr, 0)) + } +} + +impl reqwest::dns::Resolve for DnsResolver { + fn resolve(&self, name: reqwest::dns::Name) -> Resolving { + let resolver = self.resolver.clone(); + Box::pin(async move { + let lookup = resolver.lookup_ip(name.as_str()).await?; + let addrs: Addrs = Box::new(SocketAddrs { + iter: lookup.iter().collect::>().into_iter(), + }); + Ok(addrs) + }) + } +} + +// openidconnect is weird and vendors reqwest (?), therefore we have to +// completely re-implement Resolve with different types +impl openidconnect::reqwest::dns::Resolve for DnsResolver { + fn resolve(&self, name: openidconnect::reqwest::dns::Name) -> Resolving { + let resolver = self.resolver.clone(); + Box::pin(async move { + let lookup = resolver.lookup_ip(name.as_str()).await?; + let addrs: Addrs = Box::new(SocketAddrs { + iter: lookup.iter().collect::>().into_iter(), + }); + Ok(addrs) + }) + } +} diff --git a/src/service/client/mod.rs b/src/service/client/mod.rs index fc139a144..5959c0a8a 100644 --- a/src/service/client/mod.rs +++ b/src/service/client/mod.rs @@ -1,26 +1,39 @@ +mod dns_resolver; + use std::{sync::Arc, time::Duration}; use async_trait::async_trait; -use conduwuit::{Config, Result, Server, err, trace, utils::response::LimitReadExt, warn}; +use conduwuit::{ + Config, Result, Server, debug, err, info, trace, utils::response::LimitReadExt, warn, +}; +pub(crate) use dns_resolver::DnsResolver; use either::Either; use hickory_resolver::{ TokioResolver, - config::{ConnectionConfig, NameServerConfig}, + config::{ConnectionConfig, NameServerConfig, ResolverConfig}, net::runtime::TokioRuntimeProvider, proto::rr::IntoName, }; use ipaddress::IPAddress; -use reqwest::redirect; +use reqwest::{dns::Resolve, redirect}; use resolvematrix::server::{MatrixResolver, MatrixResolverBuilder}; use serde::Deserialize; use crate::service; pub struct Service { - pub matrix_resolver: Arc, + /// Regular DNS resolver pub dns_resolver: Arc, - pub dns: reqwest::Client, + /// Tokio system resolver wrapped + pub reqwest_resolver: Arc, + + /// Matrix server resolver according to server resolution spec + pub matrix_resolver: Arc, + + /// HTTP client used for fetching files during server resolution + pub matrix_http_client: reqwest::Client, + pub url_preview: reqwest::Client, pub external_resource: reqwest::Client, pub federation: reqwest::Client, @@ -38,9 +51,18 @@ impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { let config = &args.server.config; - let dns_resolver = get_dns_resolver(args.server)?; + // Regular DNS resolver + let tokio_dns_resolver = get_dns_resolver(args.server)?; - let dns_client = base(&args.server.config)? + // More different DNS resolver that also implements + // reqwest::dns::Resolve (which is required for reqwest to use it). + // Don't ask me, I just work here. - @silversys + let reqwest_dns_resolver = Arc::new(DnsResolver::new(tokio_dns_resolver.clone())); + + // Regular HTTP client that does regular HTTP requests with regular DNS + // resolution, but with timeouts for /.well-known/matrix/* files + // according to c10y config. + let matrix_http_client = base(&args.server.config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(args.server.config.well_known_conn_timeout)) .read_timeout(Duration::from_secs(args.server.config.well_known_timeout)) .timeout(Duration::from_secs(args.server.config.well_known_timeout)) @@ -48,12 +70,17 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(4)) .build()?; + // Resolves hostnames into ip+port or hostname+port server combinations + // according to the server resolution spec let matrix_resolver = Arc::new(MatrixResolverBuilder::new() - .dangerous_tls_accept_invalid_certs(args.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .http_client(dns_client.clone()) - .dns_resolver(dns_resolver.clone()) - .build()?); - let matrix_dns_resolver = matrix_resolver.create_dns_resolver(); + .dangerous_tls_accept_invalid_certs(args.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) + .http_client(matrix_http_client.clone()) + .dns_resolver(tokio_dns_resolver.clone()) + .build()?); + // Does the same as the above, but acts as a DNS resolver for reqwest + // (implementing caching and following the matrix server resolution + // spec) + let matrix_dns_resolver = Arc::new(matrix_resolver.create_dns_resolver()); let url_preview_bind_addr = config .url_preview_bound_interface @@ -72,26 +99,26 @@ impl crate::Service for Service { Ok(Arc::new(Self { matrix_resolver, - dns_resolver, + matrix_http_client, + reqwest_resolver: reqwest_dns_resolver.clone(), - dns: dns_client, + dns_resolver: tokio_dns_resolver, - url_preview: base(config) + url_preview: base(config, reqwest_dns_resolver.clone()) .and_then(|builder| { builder_interface(builder, url_preview_bind_iface.as_deref()) })? .local_address(url_preview_bind_addr) .timeout(Duration::from_secs(config.url_preview_timeout)) .redirect(redirect::Policy::limited(3)) - .user_agent(url_preview_user_agent) + .user_agent(url_preview_user_agent.replace("", conduwuit::version_ua())) .build()?, - external_resource: base(config)? + external_resource: base(config, reqwest_dns_resolver.clone())? .redirect(redirect::Policy::limited(3)) .build()?, - federation: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + federation: base(config, matrix_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.federation_timeout)) .timeout(Duration::from_secs( @@ -104,8 +131,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(3)) .build()?, - federation_slow: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + federation_slow: base(config, matrix_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.federation_timeout.saturating_mul(6))) .timeout(Duration::from_secs( @@ -118,8 +144,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(3)) .build()?, - sender: base(config)? - .dns_resolver(matrix_dns_resolver.clone()) + sender: base(config, matrix_dns_resolver)? .connect_timeout(Duration::from_secs(config.federation_conn_timeout)) .read_timeout(Duration::from_secs(config.sender_timeout)) .timeout(Duration::from_secs(config.sender_timeout)) @@ -128,8 +153,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - appservice: base(config)? - .dns_resolver(matrix_dns_resolver) + appservice: base(config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(5)) .read_timeout(Duration::from_secs(config.appservice_timeout)) .timeout(Duration::from_secs(config.appservice_timeout)) @@ -138,7 +162,7 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - pusher: base(config)? + pusher: base(config, reqwest_dns_resolver.clone())? .connect_timeout(Duration::from_secs(config.pusher_conn_timeout)) .timeout(Duration::from_secs(config.pusher_timeout)) .pool_max_idle_per_host(1) @@ -146,9 +170,9 @@ impl crate::Service for Service { .redirect(redirect::Policy::limited(2)) .build()?, - // MSC4174 recommends against following redirects, since the destination - // is only checked before the request is sent. - webpush: base(config)? + // MSC4174 recommends against following redirects, since the + // destination is only checked before the request is sent. + webpush: base(config, reqwest_dns_resolver)? .connect_timeout(Duration::from_secs(config.pusher_conn_timeout)) .timeout(Duration::from_secs(config.pusher_timeout)) .pool_max_idle_per_host(1) @@ -221,18 +245,21 @@ impl Service { } } -pub fn base(config: &Config) -> Result { +pub(crate) fn base( + config: &Config, + resolver: Arc, +) -> Result { let mut builder = reqwest::Client::builder() - .hickory_dns(true) - .connect_timeout(Duration::from_secs(config.request_conn_timeout)) - .read_timeout(Duration::from_secs(config.request_timeout)) - .timeout(Duration::from_secs(config.request_total_timeout)) - .pool_idle_timeout(Duration::from_secs(config.request_idle_timeout)) - .pool_max_idle_per_host(config.request_idle_per_host.into()) - .user_agent(conduwuit::user_agent()) - .redirect(redirect::Policy::limited(6)) + .dns_resolver(resolver) + .connect_timeout(Duration::from_secs(config.request_conn_timeout)) + .read_timeout(Duration::from_secs(config.request_timeout)) + .timeout(Duration::from_secs(config.request_total_timeout)) + .pool_idle_timeout(Duration::from_secs(config.request_idle_timeout)) + .pool_max_idle_per_host(config.request_idle_per_host.into()) + .user_agent(conduwuit::user_agent()) + .redirect(redirect::Policy::limited(6)) .danger_accept_invalid_certs(config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure) - .connection_verbose(cfg!(debug_assertions)); + .connection_verbose(cfg!(debug_assertions)); #[cfg(feature = "gzip_compression")] { @@ -310,19 +337,29 @@ fn builder_interface( fn get_dns_resolver(server: &Arc) -> Result> { let config = &server.config; - let (sys_conf, mut opts) = hickory_resolver::system_conf::read_system_conf() - .map_err(|e| err!(error!("Failed to configure DNS resolver from system: {e}")))?; - let mut conf = hickory_resolver::config::ResolverConfig::default(); + let (system_resolver_config, mut opts) = + match hickory_resolver::system_conf::read_system_conf() { + | Ok(system_conf) => system_conf, + | Err(e) if config.dns_servers.is_empty() => + return Err(err!(error!("Failed to configure DNS resolver from system: {e}"))), + | Err(e) => { + warn!("Failed to read system DNS configuration, using dns_servers: {e}"); + Default::default() + }, + }; - if let Some(domain) = sys_conf.domain() { + let mut conf = ResolverConfig::from_name_servers(vec![]); + + // Set domain and search domains from system config (/etc/resolv.conf) + if let Some(domain) = system_resolver_config.domain() { conf.set_domain(domain.clone()); } - - for sys_conf in sys_conf.search() { + for sys_conf in system_resolver_config.search() { conf.add_search(sys_conf.clone()); } + // Read nameservers from c10y config file let config_nameservers: Vec = server .config .dns_servers @@ -330,14 +367,19 @@ fn get_dns_resolver(server: &Arc) -> Result> { .filter_map(IntoName::to_ip) .map(NameServerConfig::udp_and_tcp) .collect(); + let system_nameservers = system_resolver_config.name_servers().to_vec(); + let nameservers = if !config_nameservers.is_empty() { + debug!("Using DNS nameservers from config file"); config_nameservers } else { - sys_conf.name_servers().to_vec() + debug!("Using DNS nameservers from /etc/resolv.conf"); + system_nameservers }; + info!(?nameservers, "Resolved nameservers for DNS client"); for sys_conf in nameservers { - let mut ns = sys_conf.clone(); + let mut ns = sys_conf; if config.query_over_tcp_only { ns.connections = vec![ConnectionConfig::tcp()]; diff --git a/src/service/federation/execute.rs b/src/service/federation/execute.rs index 78f3ee723..594b84a10 100644 --- a/src/service/federation/execute.rs +++ b/src/service/federation/execute.rs @@ -1,4 +1,9 @@ -use std::{borrow::Cow, fmt::Debug, mem, time::Instant}; +use std::{ + borrow::Cow, + fmt::Debug, + mem, + time::{Duration, Instant}, +}; use conduwuit::{ Err, Error, Result, debug, debug_error, debug_info, debug_warn, err, metrics::KeyValue, @@ -133,12 +138,19 @@ impl super::Service { self.ensure_remote_is_healthy(dest)?; + /// How long to wait with re-resolution if a server fails to resolve + const UNRESOLVABLE_RETRY_AFTER: Duration = Duration::from_hours(24 * 90); + let actual = self .services .client .matrix_resolver .resolve_server(dest.as_str()) - .await?; + .await + .inspect_err(|_| { + self.hit_unhealthy(dest.to_owned(), Some(UNRESOLVABLE_RETRY_AFTER)); + self.mark_destination_stale(dest); + })?; let request = Request::try_from(request.try_into_http_request::>( actual.base_url().as_str(), @@ -210,7 +222,7 @@ impl super::Service { if self.should_mark_stale(&wrapped) { debug_info!("{dest} is unhealthy & stale due to a connect error"); self.mark_destination_stale(dest); - self.hit_unhealthy(dest.to_owned()); + self.hit_unhealthy(dest.to_owned(), None); } let Error::Reqwest(unwrapped) = wrapped else { unreachable!("wrapped reqwest error must unwrap to a reqwest error"); @@ -300,6 +312,26 @@ async fn into_http_response( actual.base_url(), ); + if url.path() != "/.well-known/matrix/server" { + // For some reason, the spec starts off saying federation responses MUST + // include a `Content-Type` header of `application/json` on all + // responses. Then, the definition for the well-known server endpoint + // says that it's a SHOULD and that servers SHOULD just assume that the + // response is JSON regardless... And then there's media wayyyy down in + // the spec doc that just throws a `multipart/mixed` in there. + // + // Media has a special case regarding status codes. Only 200 OK + // responses should have the multipart assertion, as errors are JSON. + let ct = if url.path().starts_with("/_matrix/federation/v1/media/") + && response.status().is_success() + { + "multipart/mixed" + } else { + "application/json" + }; + enforce_content_type(&response, ct)?; + } + let mut http_response_builder = http::Response::builder() .status(status) .version(response.version()); @@ -353,6 +385,42 @@ fn handle_error( Err(e.into()) } +/// Enforces that the `Content-Type` response header is present, and that the +/// first part matches the expected header. This does not enforce that multipart +/// responses have a boundary as only the text left of a semicolon, if present, +/// is compared. +/// +/// Returns `M_UNKNOWN` with HTTP 415 (Unsupported Media Type) if the response +/// header is missing or mismatched. +fn enforce_content_type(response: &Response, expected: &str) -> Result<()> { + // N.B. Content type's value is case-insensitive per RFC 9110. The Matrix + // spec explicitly prescribes `application/json` and `multipart/mixed` etc, + // but it's assumed they're intended to be case-insensitive. + debug_assert_eq!( + expected, + expected.to_lowercase(), + "Content type checks should use the lowercase content type" + ); // ^ Saves us double-folding + match response + .headers() + .get(&http::header::CONTENT_TYPE) + .and_then(|h| h.to_str().ok()) + .map(|h| h.split_once(';').unwrap_or((h, "")).0.to_lowercase()) + { + | Some(ct) if ct == expected => Ok(()), + | Some(ct) => Err!(Request( + Unknown( + "Remote server returned the wrong Content-Type: expected {expected}, got {ct:?}" + ), + UNSUPPORTED_MEDIA_TYPE + )), + | None => Err!(Request( + Unknown("Remote server did not return a Content-Type header"), + UNSUPPORTED_MEDIA_TYPE + )), + } +} + /// A trait for the input types of acceptable path builders for outgoing /// federation requests. /// diff --git a/src/service/federation/mod.rs b/src/service/federation/mod.rs index 76d0e124a..0b09c56bf 100644 --- a/src/service/federation/mod.rs +++ b/src/service/federation/mod.rs @@ -92,7 +92,7 @@ impl Service { /// retry count is incremented and next retry window is updated. /// /// Does not update the marker if the backoff period is already in effect. - pub fn hit_unhealthy(&self, server_name: OwnedServerName) { + pub fn hit_unhealthy(&self, server_name: OwnedServerName, next_attempt: Option) { if server_name == self.services.server.name { return; } @@ -109,7 +109,8 @@ impl Service { } *retries = retries.saturating_add(1); - let next_interval = self.services.server.config.sender_retry_backoff(*retries); + let next_interval = next_attempt + .unwrap_or_else(|| self.services.server.config.sender_retry_backoff(*retries)); *next_retry = millis_from_now(next_interval); debug!( "{} is (now) unhealthy ({} retries, blocked until: {})", @@ -200,14 +201,14 @@ impl Service { } match error.status_code() { - // Some special servers account for this specifically - | StatusCode::MISDIRECTED_REQUEST - // Common error codes observed for misdirected requests - // | StatusCode::NOT_FOUND This one can be encountered naturally - | StatusCode::METHOD_NOT_ALLOWED - | StatusCode::IM_A_TEAPOT => true, - _ => false, - } + // Some special servers account for this specifically + | StatusCode::MISDIRECTED_REQUEST + // Common error codes observed for misdirected requests + // | StatusCode::NOT_FOUND This one can be encountered naturally + | StatusCode::METHOD_NOT_ALLOWED + | StatusCode::IM_A_TEAPOT => true, + _ => false, + } } /// Returns a clone of the internal remote health tracking map. diff --git a/src/service/globals/data.rs b/src/service/globals/data.rs index 07f1de5c6..ee2f7d232 100644 --- a/src/service/globals/data.rs +++ b/src/service/globals/data.rs @@ -21,7 +21,9 @@ impl Data { } } - pub fn next_count(&self) -> Result { + pub fn next_count(&self) -> Result { self.next_count_with(|_| ()) } + + pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result { let _cork = self.db.cork(); let mut lock = self.counter.write(); let counter: &mut u64 = &mut lock; @@ -30,7 +32,9 @@ impl Data { "counter mismatch" ); - *counter = counter.checked_add(1).unwrap_or(*counter); + let next = counter.checked_add(1).unwrap_or(*counter); + write(next); + *counter = next; self.global.insert(COUNTER, counter.to_be_bytes()); diff --git a/src/service/globals/mod.rs b/src/service/globals/mod.rs index 23c3f8db4..b88e99206 100644 --- a/src/service/globals/mod.rs +++ b/src/service/globals/mod.rs @@ -80,6 +80,11 @@ impl Service { #[inline] pub fn next_count(&self) -> Result { self.db.next_count() } + #[inline] + pub fn next_count_with(&self, write: impl FnOnce(u64)) -> Result { + self.db.next_count_with(write) + } + #[inline] pub fn current_count(&self) -> Result { Ok(self.db.current_count()) } diff --git a/src/service/media/data.rs b/src/service/media/data.rs index 7416464f8..bc20ee0b8 100644 --- a/src/service/media/data.rs +++ b/src/service/media/data.rs @@ -182,26 +182,11 @@ impl Data { let mut value = Vec::::new(); value.extend_from_slice(×tamp.as_secs().to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.title - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.title.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); - value.extend_from_slice( - data.description - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.description.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); - value.extend_from_slice( - data.image - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.image.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes()); value.push(0xFF); @@ -209,12 +194,7 @@ impl Data { value.push(0xFF); value.extend_from_slice(&data.image_height.unwrap_or(0).to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.video - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.video.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.video_size.unwrap_or(0).to_be_bytes()); value.push(0xFF); @@ -222,12 +202,7 @@ impl Data { value.push(0xFF); value.extend_from_slice(&data.video_height.unwrap_or(0).to_be_bytes()); value.push(0xFF); - value.extend_from_slice( - data.audio - .as_ref() - .map(String::as_bytes) - .unwrap_or_default(), - ); + value.extend_from_slice(data.audio.as_ref().map_or_default(String::as_bytes)); value.push(0xFF); value.extend_from_slice(&data.audio_size.unwrap_or(0).to_be_bytes()); @@ -248,6 +223,8 @@ impl Data { x => x, };*/ + // TODO(nex): Oh my god this is awful when can we kill it + let title = match values .next() .and_then(|b| String::from_utf8(b.to_vec()).ok()) @@ -346,6 +323,11 @@ impl Data { video_height, audio, audio_size, + ..Default::default() /* TODO(nex,silversys): This weird manual field + * de/serialisation just needs replacing with JSON storage to + * avoid this mess. This is consequently intentionally + * dropping information added later (like image alt text). + * I'll do it later. */ }) } } diff --git a/src/service/media/migrations.rs b/src/service/media/migrations.rs index 5fd628cd9..0cb91ea13 100644 --- a/src/service/media/migrations.rs +++ b/src/service/media/migrations.rs @@ -1,7 +1,7 @@ use std::{ collections::HashSet, ffi::{OsStr, OsString}, - fs::{self}, + fs, path::PathBuf, sync::Arc, time::Instant, diff --git a/src/service/media/mod.rs b/src/service/media/mod.rs index 7e229d9cf..d7021be01 100644 --- a/src/service/media/mod.rs +++ b/src/service/media/mod.rs @@ -112,14 +112,27 @@ impl Service { err!(Database(error!("Failed to write media file for MXC {mxc} at key {key:?}: {e}"))) })?; + self.record_write(mxc, file.len()); + + Ok(()) + } + + fn record_write(&self, mxc: &Mxc<'_>, len: usize) { self.services .server .metrics .instruments .media_write_size - .record(file.len().try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + .record(len.try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + } - Ok(()) + fn record_read(&self, mxc: &Mxc<'_>, len: usize) { + self.services + .server + .metrics + .instruments + .media_read_size + .record(len.try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); } fn origin(&self, mxc: &Mxc<'_>) -> KeyValue { @@ -196,12 +209,7 @@ impl Service { .read_to_end(&mut content) .await?; - self.services - .server - .metrics - .instruments - .media_read_size - .record(content.len().try_into().unwrap_or(u64::MAX), &[self.origin(mxc)]); + self.record_read(mxc, content.len()); Ok(Some(FileMeta { content: Some(content), diff --git a/src/service/media/preview.rs b/src/service/media/preview.rs index ac10fa40c..de649b709 100644 --- a/src/service/media/preview.rs +++ b/src/service/media/preview.rs @@ -8,32 +8,78 @@ use std::time::SystemTime; #[cfg(feature = "url_preview")] -use conduwuit::utils::response::LimitReadExt; -use conduwuit::{Err, Result, debug, err}; +use conduwuit::info; +use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt}; use ipaddress::IPAddress; -#[cfg(feature = "url_preview")] +use mime::Mime; use ruma::OwnedMxcUri; -use serde::Serialize; +use serde::{Serialize, Serializer}; use url::Url; use super::Service; -#[cfg(feature = "url_preview")] use crate::media::mxc::Mxc; -#[derive(Serialize, Default)] +// serde `serialize_with` passes `&Option` for `Option` fields. +#[allow(clippy::ref_option)] +fn serialize_mime(mime: &Option, serializer: S) -> Result { + match mime { + | Some(m) => serializer.serialize_str(m.as_ref()), + | None => serializer.serialize_none(), + } +} + +#[derive(Serialize, Default, Debug)] pub struct UrlPreviewData { + // From https://ogp.me/ + /// The title of your object as it should appear within the graph + /// "The Rock". #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))] pub title: Option, + + /// The type of your object, e.g., "video.movie". + #[serde(skip_serializing_if = "String::is_empty", rename(serialize = "og:type"))] + pub site_type: String, + /// The canonical URL of your object that will be used as its permanent ID + /// in the graph. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))] + pub url: Option, + /// A one to two sentence description of your object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))] pub description: Option, + /// The word that appears before this object's title in a sentence. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:determiner"))] + pub determiner: Option, + /// The locale these tags are marked up in + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:locale"))] + pub locale: Option, + /// If your object is part of a larger web site, the name which should be + /// displayed for the overall site. + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:site_name"))] + pub site_name: Option, + + /// An image URL which should represent your object within the graph. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))] pub image: Option, + /// A MIME type for this image. + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_mime", + rename(serialize = "og:image:type") + )] + pub image_type: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))] pub image_size: Option, + /// The number of pixels wide. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))] pub image_width: Option, + /// The number of pixels high. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))] pub image_height: Option, + /// A description of what is in the image (not a caption). + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:alt"))] + pub image_alt: Option, + + /// A URL to a video file that complements this object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video"))] pub video: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:video:size"))] @@ -42,6 +88,15 @@ pub struct UrlPreviewData { pub video_width: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))] pub video_height: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "serialize_mime", + rename(serialize = "og:video:type") + )] + pub video_type: Option, + #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))] + pub video_alt: Option, + /// A URL to an audio file to accompany this object. #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:audio"))] pub audio: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:audio:size"))] @@ -82,43 +137,39 @@ impl Service { } async fn request_url_preview(&self, url: &Url) -> Result { - if let Ok(ip) = IPAddress::parse(url.host_str().expect("URL previously validated")) { - if !self.services.client.valid_cidr_range(&ip) { - return Err!(Request(Forbidden("Requesting from this address is forbidden"))); - } - } + self.check_url_ip(url.as_str())?; let client = &self.services.client.url_preview; let response = client.head(url.as_str()).send().await?; debug!(%url, "URL preview response headers: {:?}", response.headers()); - if let Some(remote_addr) = response.remote_addr() { - debug!(%url, "URL preview response remote address: {:?}", remote_addr); - - if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) { - if !self.services.client.valid_cidr_range(&ip) { - return Err!(Request(Forbidden("Requesting from this address is forbidden"))); - } - } + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown( + "URL preview request returned HTTP {}", + response.status() + ))); } let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else { - return Err!(Request(Unknown("Unknown or invalid Content-Type header"))); + return Err!(Request(Unknown( + "Response contains unknown, invalid, or missing Content-Type header" + ))); }; - let content_type = content_type + let content_type: Mime = content_type .to_str() + .map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))? + .parse() .map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?; - let data = match content_type { - | html if html.starts_with("text/html") => self.download_html(url.as_str()).await?, - | img if img.starts_with("image/") => self.download_image(url.as_str(), None).await?, - | video if video.starts_with("video/") => - self.download_video(url.as_str(), None).await?, - | audio if audio.starts_with("audio/") => - self.download_audio(url.as_str(), None).await?, - | _ => return Err!(Request(Unknown("Unsupported Content-Type"))), + let data = match (content_type.type_(), content_type.subtype()) { + | (mime::TEXT, mime::HTML) => self.download_html(url.as_str()).await?, + | (mime::IMAGE, _) => self.download_image(url.as_str()).await?, + | (mime::VIDEO, _) => self.download_video(url.as_str()).await?, + | (mime::AUDIO, _) => self.download_audio(url.as_str()).await?, + | _ => return Err!(Request(Unknown("Unsupported Content-Type: {content_type}"))), }; self.set_url_preview(url.as_str(), &data).await?; @@ -127,19 +178,16 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_image( - &self, - url: &str, - preview_data: Option, - ) -> Result { + pub async fn download_image(&self, url: &str) -> Result { use conduwuit::utils::random_string; use image::ImageReader; - use crate::media::mxc::Mxc; + let mut preview_data = UrlPreviewData::default(); - let mut preview_data = preview_data.unwrap_or_default(); + self.check_url_ip(url)?; let response = self.services.client.url_preview.get(url).send().await?; + self.check_response_ip(&response)?; if !response.status().is_success() { return Err!(Request(Unknown("Image download returned HTTP {}", response.status()))); } @@ -161,13 +209,13 @@ impl Service { .ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))? .to_mime_type(); - if preview_data.image_height.is_none() || preview_data.image_width.is_none() { - let (width, height) = reader.into_dimensions().map_err(|error| { - err!(Request(Unknown("Failed to read preview image dimensions: {error}"))) - })?; - preview_data.image_width.get_or_insert(width); - preview_data.image_height.get_or_insert(height); - } + let (width, height) = reader.into_dimensions().map_err(|error| { + err!(Request(Unknown("Failed to read preview image dimensions: {error}"))) + })?; + preview_data.image_width = Some(width); + preview_data.image_height = Some(height); + preview_data.image_size = Some(image.len()); + preview_data.image_type = content_type.parse().ok(); let mxc = Mxc { server_name: self.services.globals.server_name(), @@ -183,12 +231,9 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_video( - &self, - url: &str, - preview_data: Option, - ) -> Result { - let mut preview_data = preview_data.unwrap_or_default(); + #[tracing::instrument(skip(self))] + pub async fn download_video(&self, url: &str) -> Result { + let mut preview_data = UrlPreviewData::default(); if self.services.globals.url_preview_allow_audio_video() { let (url, size) = self.download_media(url).await?; @@ -200,12 +245,9 @@ impl Service { } #[cfg(feature = "url_preview")] - pub async fn download_audio( - &self, - url: &str, - preview_data: Option, - ) -> Result { - let mut preview_data = preview_data.unwrap_or_default(); + #[tracing::instrument(skip(self))] + pub async fn download_audio(&self, url: &str) -> Result { + let mut preview_data = UrlPreviewData::default(); if self.services.globals.url_preview_allow_audio_video() { let (url, size) = self.download_media(url).await?; @@ -216,11 +258,18 @@ impl Service { Ok(preview_data) } + #[tracing::instrument(skip(self))] pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> { use conduwuit::utils::random_string; use http::header::CONTENT_TYPE; + self.check_url_ip(url)?; + let response = self.services.client.url_preview.get(url).send().await?; + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown("Media download returned HTTP {}", response.status()))); + } let content_type = response.headers().get(CONTENT_TYPE).cloned(); let media = response .limit_read( @@ -246,41 +295,32 @@ impl Service { } #[cfg(not(feature = "url_preview"))] - pub async fn download_image( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_image(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(not(feature = "url_preview"))] - pub async fn download_video( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_video(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(not(feature = "url_preview"))] - pub async fn download_audio( - &self, - _url: &str, - _preview_data: Option, - ) -> Result { - Err!(FeatureDisabled("url_preview")) + pub fn download_audio(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) } #[cfg(feature = "url_preview")] + #[tracing::instrument(skip(self))] async fn download_html(&self, url: &str) -> Result { use webpage::HTML; let client = &self.services.client.url_preview; - let body = client - .get(url) - .send() - .await? + let response = client.get(url).send().await?; + self.check_response_ip(&response)?; + if !response.status().is_success() { + return Err!(Request(Unknown("HTML download returned HTTP {}", response.status()))); + } + let body = response .limit_read_text( self.services .server @@ -290,39 +330,138 @@ impl Service { .expect("u64 should fit in usize"), ) .await?; - let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) else { + let Ok(html) = HTML::from_string(body, Some(url.to_owned())) + .inspect_err(|e| debug!(error=?e, "Failed to parse HTML data")) + else { return Err!(Request(Unknown("Failed to parse HTML"))); }; - let mut preview_data = UrlPreviewData::default(); + let mut preview_data = UrlPreviewData::from(&html.opengraph); + debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data"); - if let Some(obj) = html.opengraph.images.first() { - preview_data = self.download_image(&obj.url, Some(preview_data)).await?; + let base_url = Url::parse(url).ok(); + let resolve_asset_url = |asset_url: &str| -> String { + base_url + .as_ref() + .and_then(|base| base.join(asset_url).ok()) + .map_or_else(|| asset_url.to_owned(), Into::into) + }; + + if let Some(obj) = html + .opengraph + .images + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading preview image"); + if let Ok(image_data) = self.download_image(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview image"), + ) { + preview_data.image = image_data.image; + preview_data.image_size = image_data.image_size; + // Prioritise what the top-level site specified, falling back to + // detected params. + preview_data.image_width = preview_data.image_width.or(image_data.image_width); + preview_data.image_height = preview_data.image_height.or(image_data.image_height); + preview_data.image_type = preview_data.image_type.or(image_data.image_type); + } } - if let Some(obj) = html.opengraph.videos.first() { - preview_data = self.download_video(&obj.url, Some(preview_data)).await?; - preview_data.video_width = obj.properties.get("width").and_then(|v| v.parse().ok()); - preview_data.video_height = obj.properties.get("height").and_then(|v| v.parse().ok()); + if let Some(obj) = html + .opengraph + .videos + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading preview video"); + if let Ok(video_data) = self.download_video(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview video"), + ) { + preview_data.video = video_data.video; + preview_data.video_size = video_data.video_size; + } } - if let Some(obj) = html.opengraph.audios.first() { - preview_data = self.download_audio(&obj.url, Some(preview_data)).await?; + if let Some(obj) = html + .opengraph + .audios + .first() + .filter(|obj| !obj.url.is_empty()) + { + let asset_url = resolve_asset_url(&obj.url); + info!(%asset_url, "Downloading URL preview audio"); + if let Ok(audio_data) = self.download_audio(&asset_url).await.inspect_err( + |e| info!(error=?e, %asset_url, "Could not download URL preview audio"), + ) { + preview_data.audio = audio_data.audio; + preview_data.audio_size = audio_data.audio_size; + } } - let props = html.opengraph.properties; + // Provide defaults for some params + preview_data.title = preview_data.title.or(html.title); + preview_data.description = preview_data.description.or(html.description); + preview_data.url = preview_data.url.or_else(|| Some(url.to_owned())); - /* use OpenGraph title/description, but fall back to HTML if not - * available */ - preview_data.title = props.get("title").cloned().or(html.title); - preview_data.description = props.get("description").cloned().or(html.description); + // We remove og:image:*, og:video:*, and og:audio:* if their respective + // prior-level properties are not present. + // We do this here instead of in the From<> impl because we can't know + // if we'll be able to fetch the media to convert it to an mxc that + // point. + if preview_data.image.is_none() { + preview_data.image_type = None; + preview_data.image_alt = None; + preview_data.image_height = None; + preview_data.image_width = None; + preview_data.image_size = None; + } + if preview_data.video.is_none() { + preview_data.video_type = None; + preview_data.video_alt = None; + preview_data.video_height = None; + preview_data.video_width = None; + preview_data.video_size = None; + } + if preview_data.audio.is_none() { + preview_data.audio_size = None; + } Ok(preview_data) } #[cfg(not(feature = "url_preview"))] - async fn download_html(&self, _url: &str) -> Result { - Err!(FeatureDisabled("url_preview")) + #[allow(clippy::unused_self)] + fn download_html(&self, _url: &str) -> impl Future> { + std::future::ready(Err!(FeatureDisabled("url_preview"))) + } + + fn check_url_ip(&self, url: &str) -> Result<()> { + let parsed = Url::parse(url) + .map_err(|e| err!(Request(InvalidParam("Requested URL is not valid: {e}"))))?; + let Some(host) = parsed.host_str() else { + return Err!(Request(InvalidParam("Requested URL does not have a host"))); + }; + if let Ok(ip) = IPAddress::parse(host) { + if !self.services.client.valid_cidr_range(&ip) { + return Err!(Request(Forbidden("Requesting from this address is forbidden"))); + } + } + Ok(()) + } + + fn check_response_ip(&self, response: &reqwest::Response) -> Result<()> { + if let Some(remote_addr) = response.remote_addr() { + debug!(url = %response.url(), "URL preview response remote address: {:?}", remote_addr); + + if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) { + if !self.services.client.valid_cidr_range(&ip) { + return Err!(Request(Forbidden("Requesting from this address is forbidden"))); + } + } + } + Ok(()) } pub fn url_preview_allowed(&self, url: &Url) -> bool { @@ -447,3 +586,115 @@ impl Service { false } } + +#[cfg(feature = "url_preview")] +impl From<&webpage::Opengraph> for UrlPreviewData { + fn from(og: &webpage::Opengraph) -> Self { + Self { + title: og.properties.get("title").cloned(), + description: og.properties.get("description").cloned(), + site_type: og.og_type.clone(), + url: og.properties.get("url").cloned(), + determiner: og.properties.get("determiner").cloned(), + locale: og.properties.get("locale").cloned(), + site_name: og.properties.get("site_name").cloned(), + image_type: og + .images + .first() + .and_then(|img| img.properties.get("type").and_then(|t| t.parse().ok())), + image_width: og + .images + .first() + .and_then(|img| img.properties.get("width").and_then(|w| w.parse().ok())), + image_height: og + .images + .first() + .and_then(|img| img.properties.get("height").and_then(|h| h.parse().ok())), + image_alt: og + .images + .first() + .and_then(|img| img.properties.get("alt").cloned()), + video_type: og + .videos + .first() + .and_then(|vid| vid.properties.get("type")) + .and_then(|t| t.parse().ok()), + video_width: og + .videos + .first() + .and_then(|vid| vid.properties.get("width")) + .and_then(|w| w.parse().ok()), + video_height: og + .videos + .first() + .and_then(|vid| vid.properties.get("height")) + .and_then(|h| h.parse().ok()), + video_alt: og + .videos + .first() + .and_then(|vid| vid.properties.get("alt").cloned()), + ..Default::default() + } + } +} + +#[cfg(test)] +mod tests { + #[cfg(feature = "url_preview")] + #[test] + fn test_urlpreviewdata_parses_correctly() { + use webpage::HTML; + + use super::UrlPreviewData; + let html = r#" + + + + + + + + + + + + + + + + + + "#; + + let parsed_html = + HTML::from_string(html.to_owned(), Some("https://example.com".to_owned())) + .expect("Failed to parse HTML"); + + let data = UrlPreviewData::from(&parsed_html.opengraph); + + assert_eq!(data.title, Some("Test Title".to_owned())); + assert_eq!(data.description, Some("Test Description".to_owned())); + assert_eq!( + data.image, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); + assert_eq!( + data.video, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); + assert_eq!( + data.audio, None, + "UrlPreviewData should not inherit HTTP/S URL from URL preview" + ); + assert_eq!(data.url, Some("https://example.com/index.html".to_owned())); + assert_eq!(data.site_type, "org.continuwuity.other".to_owned()); + assert_eq!(data.site_name, Some("Example Site".to_owned())); + assert_eq!(data.image_alt, Some("An example image".to_owned())); + assert_eq!(data.image_type, Some("image/png".parse().unwrap())); + assert_eq!(data.image_height, Some(69)); + assert_eq!(data.image_width, Some(420)); + assert_eq!(data.image_size, None, "*_size must be None when pulling from opengraph"); + assert_eq!(data.video_size, None, "*_size must be None when pulling from opengraph"); + assert_eq!(data.audio_size, None, "*_size must be None when pulling from opengraph"); + } +} diff --git a/src/service/media/remote.rs b/src/service/media/remote.rs index 2be895a6e..15aa4f672 100644 --- a/src/service/media/remote.rs +++ b/src/service/media/remote.rs @@ -1,7 +1,7 @@ use std::{fmt::Debug, time::Duration}; use conduwuit::{ - Err, Error, Result, debug_warn, err, + Err, Result, debug_warn, err, utils::{content_disposition::make_content_disposition, response::LimitReadExt}, }; use http::header::{CONTENT_DISPOSITION, CONTENT_TYPE, HeaderValue}; @@ -9,9 +9,6 @@ use ruma::{ ServerName, UserId, api::{ OutgoingRequest, - auth_scheme::NoAccessToken, - client::media, - error::ErrorKind::{NotFound, Unrecognized}, federation::{ self, authenticated_media::{Content, FileOrLocation}, @@ -35,17 +32,8 @@ impl super::Service { ) -> Result { self.check_fetch_authorized(mxc)?; - let result = self - .fetch_thumbnail_authenticated(mxc, user, server, timeout_ms, dim) - .await; - - if let Err(Error::Request(NotFound, ..)) = &result { - return self - .fetch_thumbnail_unauthenticated(mxc, user, server, timeout_ms, dim) - .await; - } - - result + self.fetch_thumbnail_authenticated(mxc, user, server, timeout_ms, dim) + .await } pub async fn fetch_remote_content( @@ -57,8 +45,7 @@ impl super::Service { ) -> Result { self.check_fetch_authorized(mxc)?; - let result = self - .fetch_content_authenticated(mxc, user, server, timeout_ms) + self.fetch_content_authenticated(mxc, user, server, timeout_ms) .await .inspect_err(|error| { debug_warn!( @@ -68,15 +55,7 @@ impl super::Service { ?error, "Authenticated fetch of remote content failed" ); - }); - - if let Err(Error::Request(Unrecognized, ..)) = &result { - return self - .fetch_content_unauthenticated(mxc, user, server, timeout_ms) - .await; - } - - result + }) } async fn fetch_thumbnail_authenticated( @@ -127,66 +106,6 @@ impl super::Service { } } - #[allow(deprecated)] - async fn fetch_thumbnail_unauthenticated( - &self, - mxc: &Mxc<'_>, - user: Option<&UserId>, - server: Option<&ServerName>, - timeout_ms: Duration, - dim: &Dim, - ) -> Result { - use media::get_content_thumbnail::v3::{Request, Response}; - - let mut request = Request::new( - mxc.media_id.into(), - mxc.server_name.into(), - dim.width.into(), - dim.height.into(), - ); - request.allow_redirect = true; - request.allow_remote = true; - request.animated = Some(true); - request.method = Some(dim.method.clone()); - request.timeout_ms = timeout_ms; - - let Response { - file, content_type, content_disposition, .. - } = self - .federation_request_legacy_media(mxc, server, request) - .await?; - - let content = Content::new(file, content_type.unwrap(), content_disposition.unwrap()); - - self.handle_thumbnail_file(mxc, user, dim, content).await - } - - #[allow(deprecated)] - async fn fetch_content_unauthenticated( - &self, - mxc: &Mxc<'_>, - user: Option<&UserId>, - server: Option<&ServerName>, - timeout_ms: Duration, - ) -> Result { - use media::get_content::v3::{Request, Response}; - - let mut request = Request::new(mxc.media_id.into(), mxc.server_name.into()); - request.allow_remote = true; - request.allow_redirect = true; - request.timeout_ms = timeout_ms; - - let Response { - file, content_type, content_disposition, .. - } = self - .federation_request_legacy_media(mxc, server, request) - .await?; - - let content = Content::new(file, content_type.unwrap(), content_disposition.unwrap()); - - self.handle_content_file(mxc, user, content).await - } - async fn handle_thumbnail_file( &self, mxc: &Mxc<'_>, @@ -319,108 +238,6 @@ impl super::Service { .await } - async fn federation_request_legacy_media<'i, Request>( - &self, - mxc: &Mxc<'_>, - server: Option<&ServerName>, - request: Request, - ) -> Result - where - Request: OutgoingRequest< - Authentication = NoAccessToken, - PathBuilder: PathBuilder: FederationPathBuilderInput>, - > + Debug - + Send, - { - self.services - .sending - .send_legacy_media_request(server.unwrap_or(mxc.server_name), request) - .await - } - - #[allow(deprecated)] - pub async fn fetch_remote_thumbnail_legacy( - &self, - body: &media::get_content_thumbnail::v3::Request, - ) -> Result { - let mxc = Mxc { - server_name: &body.server_name, - media_id: &body.media_id, - }; - - let mut request = media::get_content_thumbnail::v3::Request::new( - body.media_id.clone(), - body.server_name.clone(), - body.width, - body.height, - ); - request.method.clone_from(&body.method); - request.allow_remote = body.allow_remote; - request.allow_redirect = body.allow_redirect; - request.animated = body.animated; - request.timeout_ms = body.timeout_ms; - - self.check_legacy_freeze()?; - self.check_fetch_authorized(&mxc)?; - let response = self - .services - .sending - .send_legacy_media_request(mxc.server_name, request) - .await?; - - let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?; - self.upload_thumbnail( - &mxc, - None, - None, - response.content_type.as_deref(), - &dim, - &response.file, - ) - .await?; - - Ok(response) - } - - #[allow(deprecated)] - pub async fn fetch_remote_content_legacy( - &self, - mxc: &Mxc<'_>, - allow_redirect: bool, - timeout_ms: Duration, - ) -> Result { - let mut request = - media::get_content::v3::Request::new(mxc.media_id.into(), mxc.server_name.into()); - request.allow_remote = true; - request.allow_redirect = allow_redirect; - request.timeout_ms = timeout_ms; - - self.check_legacy_freeze()?; - self.check_fetch_authorized(mxc)?; - let response = self - .services - .sending - .send_legacy_media_request(mxc.server_name, request) - .await?; - - let content_disposition = make_content_disposition( - response.content_disposition.as_ref(), - response.content_type.as_deref(), - None, - ); - - self.create( - mxc, - None, - Some(&content_disposition), - response.content_type.as_deref(), - &response.file, - ) - .await?; - - Ok(response) - } - fn check_fetch_authorized(&self, mxc: &Mxc<'_>) -> Result<()> { if self .services @@ -436,13 +253,4 @@ impl super::Service { Ok(()) } - - fn check_legacy_freeze(&self) -> Result<()> { - self.services - .server - .config - .freeze_legacy_media - .then_some(()) - .ok_or(err!(Request(NotFound("Remote media is frozen.")))) - } } diff --git a/src/service/media/thumbnail.rs b/src/service/media/thumbnail.rs index 139516653..8b67dbe2a 100644 --- a/src/service/media/thumbnail.rs +++ b/src/service/media/thumbnail.rs @@ -44,6 +44,7 @@ impl super::Service { //TODO: Dangling metadata in database if creation fails let mut f = self.create_media_file(&key).await?; f.write_all(file).await?; + self.record_write(mxc, file.len()); Ok(()) } @@ -66,13 +67,19 @@ impl super::Service { // 0, 0 because that's the original file let dim = dim.normalized(); - match self.db.search_file_metadata(mxc, &dim).await { + let thumbnail = match self.db.search_file_metadata(mxc, &dim).await { | Ok(metadata) => self.get_thumbnail_saved(metadata).await, | _ => match self.db.search_file_metadata(mxc, &Dim::default()).await { | Ok(metadata) => self.get_thumbnail_generate(mxc, &dim, metadata).await, | _ => Ok(None), }, + }; + + if let Ok(Some(FileMeta { content: Some(content), .. })) = &thumbnail { + self.record_read(mxc, content.len()); } + + thumbnail } /// Using saved thumbnail @@ -132,6 +139,7 @@ impl super::Service { let mut f = self.create_media_file(&thumbnail_key).await?; f.write_all(&thumbnail_bytes).await?; + self.record_write(mxc, thumbnail_bytes.len()); Ok(Some(into_filemeta(data, thumbnail_bytes))) } diff --git a/src/service/metrics.rs b/src/service/metrics.rs index a1291de06..80a985f4e 100644 --- a/src/service/metrics.rs +++ b/src/service/metrics.rs @@ -18,6 +18,28 @@ impl Services { }, ); + self.gauge( + "continuwuity.sender.requests", + "Estimated outgoing requests stored as queued or in flight", + "{request}", + |services, observer| { + for (state, count) in services.sending.db.request_counts() { + if let Some(count) = count { + observer.observe(count, &[KeyValue::new("state", state)]); + } + } + }, + ); + + self.gauge( + "continuwuity.sender.workers", + "Running sender workers", + "{worker}", + |services, observer| { + observe(observer, services.sending.workers_alive(), &[]); + }, + ); + self.gauge( "continuwuity.federation.incoming.transactions.active", "Incoming federation transactions currently being processed", diff --git a/src/service/migrations.rs b/src/service/migrations.rs index 894dd5aa3..ac4825d8d 100644 --- a/src/service/migrations.rs +++ b/src/service/migrations.rs @@ -8,21 +8,21 @@ use std::{ }; use conduwuit::{ - Err, Error, Event, Pdu, Result, debug, debug_info, debug_warn, err, error, info, + Err, Error, Event, Pdu, PduCount, Result, debug, debug_info, debug_warn, err, error, info, result::NotFound, trace, utils::{ IterStream, ReadyExt, - stream::{TryExpect, TryIgnore}, + stream::{TryExpect, TryIgnore, WidebandExt, automatic_width}, to_canonical_object, }, warn, }; -use database::Json; +use database::{Database, Deserialized, Ignore, Json}; use futures::{FutureExt, StreamExt, TryStreamExt}; use itertools::Itertools; use ruma::{ - OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId, + MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedUserId, UserId, api::OAuthClientScope, events::{ AnyStrippedStateEvent, GlobalAccountDataEventType, StateEventType, @@ -32,9 +32,13 @@ use ruma::{ push::Ruleset, serde::{Raw, from_raw_json_value}, }; +use serde::Deserialize; use serde_json::{Value, value::to_raw_value}; -use crate::{Services, media, rooms, rooms::short::ShortStateHash}; +use crate::{ + Services, media, rooms, + rooms::{short::ShortStateHash, timeline::RawPduId}, +}; type MigrationFn = for<'a> fn(&'a Services) -> Pin> + Send + 'a>>; @@ -109,35 +113,37 @@ migration!(stringify!($name) => $name) migration!(fix_readreceiptid_readreceipt_duplicates), // End pre-fork logic. - // v18: `fix_corrupt_msc4133_fields` will change the `us.cloke.msc4175.tz` field - // in a way that old versions don't understand. + // v18: `fix_corrupt_msc4133_fields` will change the + // `us.cloke.msc4175.tz` field in a way that old versions don't + // understand. VersionBump(18), migration!(fix_corrupt_msc4133_fields), - // v19: `populate_userroomid_leftstate_table` will put data in the values of - // `userroomid_leftstate` that old versions will fail to deserialize because - // they expect the values to be empty. + // v19: `populate_userroomid_leftstate_table` will put data in the + // values of `userroomid_leftstate` that old versions will fail to + // deserialize because they expect the values to be empty. VersionBump(19), migration!(populate_userroomid_leftstate_table), - // This is backwards compatible because it fixes some data that clients care about but we - // don't. + // This is backwards compatible because it fixes some data that clients + // care about but we don't. migration!(fix_local_invite_state), - // v20: Old versions expect remote users to be tracked in `userid_password`. This - // migration moves them to a different keyspace. + // v20: Old versions expect remote users to be tracked in + // `userid_password`. This migration moves them to a different keyspace. VersionBump(20), migration!(split_userid_password), - // This is backwards compatible because old versions will recreate the keyspace if it's - // missing. + // This is backwards compatible because old versions will recreate the + // keyspace if it's missing. migration!("drop_roomsynctoken_shortstatehash" => obliterate_roomsynctoken_shortstatehash_with_extreme_prejudice), - // v21: `unembed_unsigned_info` will remove `unsigned` data from PDUs that old versions - // expect to be embedded. + // v21: `unembed_unsigned_info` will remove `unsigned` data from PDUs + // that old versions expect to be embedded. VersionBump(21), - // This migration can take several hours on old databases, so we run it in the background - // to keep the service manager from killing us for taking too long to start. - // Future maintainers: !!! BE VERY CAREFUL !!! if you need to write more migrations like - // this! This one is fine because it deletes data that we don't check anymore, - // but migrations which replace existing data that we do check should NOT run in - // the background. If they do, the server will finish starting up and might - // access data that the migration hasn't gotten to yet. + // This migration can take several hours on old databases, so we run it + // in the background to keep the service manager from killing us for + // taking too long to start. Future maintainers: !!! BE VERY CAREFUL !!! + // if you need to write more migrations like this! This one is fine + // because it deletes data that we don't check anymore, but migrations + // which replace existing data that we do check should NOT run in + // the background. If they do, the server will finish starting up and + // might access data that the migration hasn't gotten to yet. Migration("unembed_unsigned_info", |services| { Box::pin(async { if services.db["global"] @@ -158,13 +164,52 @@ migration!(stringify!($name) => $name) Ok(()) }) }), - // This is backwards compatible because old versions will recreate the keyspace if it's - // missing. + // This is backwards compatible because old versions will recreate the + // keyspace if it's missing. migration!(drop_server_signingkeys), - // v22: Old versions will fail to deserialize the fixed OAuth scope names, - // preventing users from signing in. + // v22: Old versions will fail to deserialize the fixed OAuth scope + // names, preventing users from signing in. VersionBump(22), migration!(fix_oauth_scope_names), + // Removes any extremities in roomid_pduleaves that we do not know about + // (and consequently should not reference). + migration!(remove_unknown_extremities), + // Re-calculates extremities for any rooms that actually lack any + // extremities at all. + migration!(consistency_check_extremity_tracker), + // This is backwards compatible because old versions never read the + // account data entries it removes. + migration!(remove_replaced_account_data), + // This is backwards compatible because old versions ignore the + // `roomts_pduid` keyspace. + Migration(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, |services| { + Box::pin(async { + let global = &services.db["global"]; + if global + .exists(rooms::timeline::TIMESTAMP_INDEX_MIGRATION) + .await + .is_ok() + { + return Ok(()); + } + + let until = match global.get(ROOMTS_UNTIL).await.deserialized::() { + | Ok(until) => until, + | Err(_) => { + let until = services.globals.current_count()?; + global.insert(ROOMTS_UNTIL, until.to_be_bytes()); + until + }, + }; + + services + .server + .runtime() + .spawn(populate_roomts_pduid(services.db.clone(), until)); + + Ok(()) + }) + }), ] }; @@ -851,7 +896,7 @@ async fn split_userid_password(services: &Services) -> Result { userid_password.remove(&user_id); remote_users = remote_users.saturating_add(1); } else if hash.is_empty() { - if !(services.appservice.is_user_id(&user_id).await + if !(services.appservice.is_user_id(&user_id) || user_id == services.globals.server_user) { info!("Marking {user_id} as deactivated"); @@ -950,6 +995,38 @@ async fn drop_server_signingkeys(services: &Services) -> Result<()> { Ok(()) } +const ROOMTS_UNTIL: &str = "populate_roomts_pduid_until"; + +async fn populate_roomts_pduid(db: Arc, until: u64) { + #[derive(Deserialize)] + struct ExtractTs { + origin_server_ts: MilliSecondsSinceUnixEpoch, + } + + info!("Starting background migration to index PDUs by timestamp."); + let start = Instant::now(); + let roomts_pduid = db["roomts_pduid"].clone(); + + db["pduid_pdu"] + .raw_stream() + .ignore_err() + .ready_for_each(|(key, val)| { + let pdu_id = RawPduId::from(key); + if matches!(pdu_id.pdu_count(), PduCount::Normal(count) if count > until) { + return; + } + if let Ok(pdu) = serde_json::from_slice::(val) { + roomts_pduid + .insert(&rooms::timeline::roomts_key(&pdu_id, pdu.origin_server_ts), []); + } + }) + .await; + + db["global"].insert(rooms::timeline::TIMESTAMP_INDEX_MIGRATION, []); + db["global"].remove(ROOMTS_UNTIL); + info!(elapsed = ?start.elapsed(), "Finished indexing PDUs by timestamp."); +} + async fn fix_oauth_scope_names(services: &Services) -> Result { let db = &services.db; let userdeviceid_oauthsessioninfo = db["userdeviceid_oauthsessioninfo"].clone(); @@ -977,3 +1054,169 @@ async fn fix_oauth_scope_names(services: &Services) -> Result { Ok(()) } + +#[tracing::instrument(skip_all)] +async fn remove_unknown_extremities(services: &Services) -> Result { + services.db["roomid_pduleaves"] + .keys() + .ignore_err() + .for_each_concurrent( + automatic_width(), + |(room_id, event_id): (OwnedRoomId, OwnedEventId)| async move { + if !services.rooms.timeline.pdu_exists(&event_id).await { + info!("Removing unknown extremity in {room_id}: {event_id}"); + services + .rooms + .state + .remove_forward_extremity(&room_id, &event_id); + } else if !services + .rooms + .pdu_metadata + .is_event_accepted(&event_id) + .await + { + info!("Removing failed extremity in {room_id}: {event_id}"); + services + .rooms + .state + .remove_forward_extremity(&room_id, &event_id); + } + }, + ) + .await; + Ok(()) +} + +async fn remove_replaced_account_data(services: &Services) -> Result { + type Key = (Option, OwnedUserId, u64, String); + type Latest = (Ignore, Ignore, u64, Ignore); + + let entries = services.db["roomuserdataid_accountdata"].clone(); + let latest_of_type = services.db["roomusertype_roomuserdataid"].clone(); + + let keys: Vec = entries.keys().ignore_err().collect().await; + let mut removed: usize = 0; + for (room_id, user_id, count, event_type) in &keys { + let latest = latest_of_type + .qry(&(room_id, user_id, event_type)) + .await + .deserialized::(); + + if latest.is_ok_and(|(_, _, latest, _)| latest != *count) { + entries.del((room_id, user_id, count, event_type)); + removed = removed.saturating_add(1); + } + } + + info!( + total = keys.len(), + ?removed, + "Removed replaced entries in 'roomuserdataid_accountdata'." + ); + Ok(()) +} + +#[tracing::instrument(skip_all)] +async fn consistency_check_extremity_tracker(services: &Services) -> Result { + let mut rooms = services.rooms.metadata.iter_ids(); + + // For every room the server is a member of, + while let Some(room_id) = rooms.next().await { + // If this room has no extremities, re-calculate + let extremity_count = services + .rooms + .state + .get_forward_extremities(&room_id) + .count() + .await; + + if extremity_count == 0 { + warn!( + "Room {room_id} is missing extremity information, recalculating. This may take \ + a long time if this room is old." + ); + let epoch_ts = services + .rooms + .timeline + .first_pdu_in_room(&room_id) + .await + .map_or_default(|e| e.origin_server_ts().0); + services + .rooms + .timeline + .pdus(&room_id, Some(PduCount::Normal(0))) + .ignore_err() + .for_each(|(_, pdu)| { + let room_id = &room_id; + async move { + if pdu.origin_server_ts < epoch_ts { + return; + } + if !services + .rooms + .pdu_metadata + .is_event_accepted(pdu.event_id()) + .await + { + return; + } + services + .rooms + .timeline + .progress_extremities(&pdu) + .await + .inspect_err(|e| { + error!("Failed to progress extremities in {room_id}: {e:?}"); + }) + .ok(); + } + }) + .await; + } else if extremity_count > 20 { + warn!( + %extremity_count, + "Room {room_id} has an abnormal number of forward extremities, retaining latest 20" + ); + let mut thinned = services + .rooms + .state + .get_forward_extremities(&room_id) + .wide_filter_map(|event_id| { + let room_id = &room_id; + async move { + let Ok(pdu) = + services.rooms.timeline.get_non_outlier_pdu(&event_id).await + else { + services + .rooms + .state + .remove_forward_extremity(room_id, &event_id); + return None; + }; + Some(pdu) + } + }) + .collect::>() + .await; + thinned.sort_by_key(|pdu| { + ( + i64::from(pdu.depth).saturating_mul(-1), + i64::from(pdu.origin_server_ts).saturating_mul(-1), + ) + }); + thinned + .into_iter() + .stream() + .skip(20) + .ready_for_each(move |pdu| { + services + .rooms + .state + .remove_forward_extremity(&room_id, pdu.event_id()); + }) + .await; + } + } + + Ok(()) +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 1a5505583..5d7de067f 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -1,4 +1,5 @@ #![type_length_limit = "8192"] +#![recursion_limit = "256"] #![allow(refining_impl_trait)] extern crate conduwuit_core as conduwuit; @@ -12,6 +13,8 @@ mod migrations; mod service; pub mod services; pub mod state; +#[cfg(test)] +mod test_utils; pub mod account_data; pub mod admin; @@ -33,6 +36,7 @@ pub mod oidc; pub mod presence; pub mod pusher; pub mod registration_tokens; +pub mod rendezvous; pub mod rooms; pub mod sending; pub mod server_keys; @@ -42,17 +46,13 @@ pub mod transactions; pub mod uiaa; pub mod users; +use std::{collections::BTreeMap, sync::LazyLock}; + +use conduwuit::matrix::versions::versions; +use ruma::api::SupportedVersions; pub(crate) use service::{Args, Dep, Service}; pub use crate::services::Services; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -use std::sync::LazyLock; - -use conduwuit::matrix::versions::{unstable_features, versions}; -use ruma::api::SupportedVersions; - pub static SUPPORTED_VERSIONS: LazyLock = - LazyLock::new(|| SupportedVersions::from_parts(&versions(), &unstable_features())); + LazyLock::new(|| SupportedVersions::from_parts(&versions(), &BTreeMap::new())); diff --git a/src/service/oauth/client_metadata.rs b/src/service/oauth/client_metadata.rs index 75d6d15b3..4ee946e8e 100644 --- a/src/service/oauth/client_metadata.rs +++ b/src/service/oauth/client_metadata.rs @@ -81,6 +81,15 @@ impl ClientMetadata { if !uri.username().is_empty() || uri.password().is_some() { return Err("HTTPS redirect URIs must not contain credentials."); } + + if !uri + .domain() + .is_some_and(|domain| is_subdomain(domain, client_domain)) + { + return Err( + "All HTTPS redirect URIs must be subdomains of the client URI." + ); + } }, | "http" if self.application_type == ApplicationType::Native => { if uri diff --git a/src/service/oauth/grant.rs b/src/service/oauth/grant.rs index 1eccc8f98..b42506f1b 100644 --- a/src/service/oauth/grant.rs +++ b/src/service/oauth/grant.rs @@ -106,12 +106,14 @@ impl Display for RequestedScopes { pub struct RawScopes(String); impl RawScopes { + const MIN_DEVICE_ID_LENGTH: usize = 5; + #[allow(clippy::trivial_regex)] pub fn to_scopes(&self) -> Result { let client_api_token_regex = regex!(r"urn:matrix:(client|org.matrix.msc2967.client):api:\*"); let device_token_regex = - regex!(r"urn:matrix:(client|org.matrix.msc2967.client):device:([a-zA-Z0-9-._~]{5,})"); + regex!(r"urn:matrix:(client|org.matrix.msc2967.client):device:(.+)"); let server_administration_regex = regex!(r"urn:matrix:client:cc.c10y.msc4484.server_administration"); @@ -124,10 +126,40 @@ impl RawScopes { } else if server_administration_regex.is_match(token) { scopes.scopes.insert(OAuthClientScope::ServerAdministration) } else if let Some(captures) = device_token_regex.captures(token) { - scopes - .device_id - .replace(captures.get(2).unwrap().as_str().into()) - .is_none() + let device_id = captures.get(2).unwrap().as_str(); + + if device_id.len() < Self::MIN_DEVICE_ID_LENGTH { + return Err(format!( + "Device ID is too short, it must be at least {} characters", + Self::MIN_DEVICE_ID_LENGTH + )); + } + + // The Matrix specification has a "suggested" set of + // characters to be used in the device + // ID scope. In the past we checked against this set, but we + // no longer do that; instead we check + // against the _required_ set of + // characters defined by the OAuth specification. + // We do this because we have observed SDKs in the wild + // (*cough* matrix-rust-sdk) that will provide device IDs + // that are just unpadded base64, which they're allowed to + // do, since the spec just says that + // clients "SHOULD" only use the suggested character set and + // servers "MAY" choose to require that they do. + // Of course this actually means that clients will do + // whatever the hell they want and + // servers can never ever be stricter + // than they absolutely have to be. What + // a stupid provision. + if device_id + .chars() + .any(|char| !matches!(char, '\x21' | '\x23'..='\x5b' | '\x5d'..='\x7e')) + { + return Err("Device ID contains disallowed characters".to_owned()); + } + + scopes.device_id.replace(device_id.into()).is_none() } else { continue; } diff --git a/src/service/oauth/mod.rs b/src/service/oauth/mod.rs index c3db66a57..e0d118b2a 100644 --- a/src/service/oauth/mod.rs +++ b/src/service/oauth/mod.rs @@ -1,12 +1,14 @@ use std::{ collections::{BTreeSet, HashMap}, - sync::{Arc, Mutex}, + sync::Arc, time::{Duration, SystemTime}, }; use base64::Engine; use conduwuit::{ - Result, info, + Result, SyncMutex, + config::experiments::ToggledExperiment, + info, utils::{self, hash::sha256}, }; use database::{Deserialized, Json, Map}; @@ -36,9 +38,9 @@ pub mod grant; pub struct Service { services: Services, db: Data, - tickets: Mutex>>, - pending_auth_code_grants: tokio::sync::Mutex>, - pending_device_code_grants: tokio::sync::Mutex>, + tickets: SyncMutex>>, + pending_auth_code_grants: SyncMutex>, + pending_device_code_grants: SyncMutex>, } struct Data { @@ -169,13 +171,9 @@ impl crate::Service for Service { userdeviceid_oauthsessioninfo: args.db["userdeviceid_oauthsessioninfo"].clone(), refreshtoken_refreshtokeninfo: args.db["refreshtoken_refreshtokeninfo"].clone(), }, - tickets: Mutex::default(), - pending_auth_code_grants: tokio::sync::Mutex::new(LruCache::new( - Self::MAX_PENDING_GRANTS, - )), - pending_device_code_grants: tokio::sync::Mutex::new(LruCache::new( - Self::MAX_PENDING_GRANTS, - )), + tickets: SyncMutex::default(), + pending_auth_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), + pending_device_code_grants: SyncMutex::new(LruCache::new(Self::MAX_PENDING_GRANTS)), })) } @@ -328,7 +326,6 @@ impl Service { self.pending_auth_code_grants .lock() - .await .insert(code, pending_grant); Ok(redirect_uri) @@ -383,7 +380,6 @@ impl Service { self.pending_device_code_grants .lock() - .await .insert(device_code.clone(), pending_grant); Ok(DeviceCodeResponse { @@ -399,32 +395,36 @@ impl Service { &self, supplied_user_code: &str, ) -> Option { - let pending_grants = self.pending_device_code_grants.lock().await; + let (device_code, client_id, requested_scopes) = { + let pending_grants = self.pending_device_code_grants.lock(); - let (device_code, grant) = pending_grants - .iter() - .find(|(_, grant)| { - matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) - })?; + let (device_code, grant) = pending_grants + .iter() + .find(|(_, grant)| { + matches!(&grant.state, DeviceCodeGrantState::Unverified { user_code } if user_code == supplied_user_code) + })?; + + (device_code.clone(), grant.client_id.clone(), grant.requested_scopes.clone()) + }; let client_metadata = self - .get_client_metadata(&grant.client_id) + .get_client_metadata(&client_id) .await .expect("client should exist"); Some(DeviceCodeGrantInfo { - device_code: device_code.clone(), + device_code, client_metadata, - requested_scopes: grant.requested_scopes.clone(), + requested_scopes, }) } - pub async fn validate_device_code( + pub fn validate_device_code( &self, authorizing_user: OwnedUserId, device_code: &str, ) -> Result<(), String> { - let mut pending_grants = self.pending_device_code_grants.lock().await; + let mut pending_grants = self.pending_device_code_grants.lock(); let Some(pending_grant) = pending_grants.get_mut(device_code) else { return Err("Invalid device code".to_owned()); @@ -460,25 +460,29 @@ impl Service { match request { | TokenRequestType::AuthorizationCode { code, redirect_uri, code_verifier } => { - let mut pending_grants = self.pending_auth_code_grants.lock().await; + let pending_grant = { + let mut pending_grants = self.pending_auth_code_grants.lock(); - let Some(pending_grant) = pending_grants - .remove(&code) - .filter(|grant| grant.is_valid_for(&client_id)) - else { - return Err(OAuthError::invalid_grant("Invalid authorization code")); + let Some(pending_grant) = pending_grants + .remove(&code) + .filter(|grant| grant.is_valid_for(&client_id)) + else { + return Err(OAuthError::invalid_grant("Invalid authorization code")); + }; + + if redirect_uri != pending_grant.expected_redirect_uri { + return Err(OAuthError::invalid_grant("Invalid redirect URI")); + } + + let expected_code_challenge = base64::prelude::BASE64_URL_SAFE_NO_PAD + .encode(sha256::hash(&code_verifier)); + if expected_code_challenge != pending_grant.code_challenge { + return Err(OAuthError::invalid_grant("Invalid code challenge")); + } + + pending_grant }; - if redirect_uri != pending_grant.expected_redirect_uri { - return Err(OAuthError::invalid_grant("Invalid redirect URI")); - } - - let expected_code_challenge = - base64::prelude::BASE64_URL_SAFE_NO_PAD.encode(sha256::hash(&code_verifier)); - if expected_code_challenge != pending_grant.code_challenge { - return Err(OAuthError::invalid_grant("Invalid code challenge")); - } - self.create_session( pending_grant.authorizing_user, pending_grant.requested_scopes, @@ -488,36 +492,38 @@ impl Service { .await }, | TokenRequestType::DeviceCode { device_code } => { - let mut pending_grants = self.pending_device_code_grants.lock().await; + let (authorizing_user, requested_scopes, client_name) = { + let mut pending_grants = self.pending_device_code_grants.lock(); - let Some(pending_grant) = pending_grants - .remove(&device_code) - .filter(|grant| grant.is_valid_for(&client_id)) - else { - return Err(OAuthError::new_static( - ErrorCode::ExpiredToken, - "Invalid device code", - )); - }; + let Some(pending_grant) = pending_grants + .remove(&device_code) + .filter(|grant| grant.is_valid_for(&client_id)) + else { + return Err(OAuthError::new_static( + ErrorCode::ExpiredToken, + "Invalid device code", + )); + }; - match &pending_grant.state { - | DeviceCodeGrantState::Unverified { .. } => { - pending_grants.insert(device_code, pending_grant); + match &pending_grant.state { + | DeviceCodeGrantState::Unverified { .. } => { + pending_grants.insert(device_code, pending_grant); - Err(OAuthError::new_static( - ErrorCode::AuthorizationPending, - "Authorization is pending", - )) - }, - | DeviceCodeGrantState::Verified { authorizing_user } => - self.create_session( + return Err(OAuthError::new_static( + ErrorCode::AuthorizationPending, + "Authorization is pending", + )); + }, + | DeviceCodeGrantState::Verified { authorizing_user } => ( authorizing_user.to_owned(), pending_grant.requested_scopes, pending_grant.client_name, - client_id, - ) - .await, - } + ), + } + }; + + self.create_session(authorizing_user, requested_scopes, client_name, client_id) + .await }, | TokenRequestType::RefreshToken { refresh_token } => self.refresh_session(client_id, refresh_token).await, @@ -758,6 +764,7 @@ impl Service { scopes: &BTreeSet, ) -> Result<(), OAuthError> { if scopes.contains(&OAuthClientScope::ServerAdministration) + && self.services.config.experiments.msc4484.is_enabled() && !self.services.admin.user_is_admin(authorizing_user).await { return Err(OAuthError::new( @@ -773,7 +780,6 @@ impl Service { pub fn issue_ticket(&self, localpart: String, ticket: OAuthTicket) { self.tickets .lock() - .unwrap() .entry(localpart) .or_default() .insert(ticket, SystemTime::now()); @@ -785,7 +791,6 @@ impl Service { self.tickets .lock() - .unwrap() .get_mut(localpart) .and_then(|tickets| tickets.remove(&ticket)) .is_some_and(|issued| { diff --git a/src/service/oidc/mod.rs b/src/service/oidc/mod.rs index d0369cf5e..a1632baf9 100644 --- a/src/service/oidc/mod.rs +++ b/src/service/oidc/mod.rs @@ -1,18 +1,18 @@ -use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; +use std::{collections::HashMap, net::IpAddr, str::FromStr, sync::Arc, time::Duration}; use async_trait::async_trait; use conduwuit::{ - Result, + Result, SyncRwLock, config::{OidcConfig, OidcProfileKeyImportMode}, debug, err, error, info, warn, }; use database::{Deserialized, Map}; use lettre::Address; use openidconnect::{ - AdditionalClaims, AuthorizationCode, ClientSecret, CsrfToken, EmptyExtraTokenFields, - EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims, IdTokenFields, IssuerUrl, - Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, StandardErrorResponse, - StandardTokenResponse, TokenResponse, + AdditionalClaims, AuthorizationCode, ClaimsVerificationError, ClientSecret, CsrfToken, + EmptyExtraTokenFields, EndpointMaybeSet, EndpointNotSet, EndpointSet, IdTokenClaims, + IdTokenFields, IssuerUrl, Nonce, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, + SignatureVerificationError, StandardErrorResponse, StandardTokenResponse, TokenResponse, core::{ CoreAuthDisplay, CoreAuthPrompt, CoreAuthenticationFlow, CoreErrorResponseType, CoreGenderClaim, CoreJsonWebKey, CoreJweContentEncryptionAlgorithm, @@ -32,7 +32,7 @@ use tokio::{runtime, sync::SetOnce}; use url::Url; use crate::{ - Dep, config, globals, media, + Dep, client, config, globals, media, oauth::grant::AuthorizationCodeResponse, threepid, users::{self, AccountStatus, ProfileFieldChange}, @@ -60,7 +60,7 @@ struct Services { struct OidcClient { config: OidcConfig, client_secret: ClientSecret, - machine: SetOnce, + machine: SetOnce>>, client: reqwest::Client, } @@ -163,6 +163,7 @@ impl crate::Service for Service { machine: SetOnce::new(), // This isn't in the client service because it has to use the `reqwest` shipped by `openidconnect` client: reqwest::ClientBuilder::new() + .dns_resolver(args.depend::("client").reqwest_resolver.clone()) .connect_timeout(Duration::from_secs(args.server.config.request_conn_timeout)) .read_timeout(Duration::from_secs(args.server.config.request_timeout)) .timeout(Duration::from_secs(args.server.config.request_total_timeout)) @@ -179,31 +180,10 @@ impl crate::Service for Service { } async fn worker(self: Arc) -> Result { - if let Some(OidcClient { config, client_secret, machine, client }) = &self.client { - let redirect_url = self - .services - .config - .get_client_domain() - .join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX)) - .expect("redirect url should be valid"); - - let provider_metadata = CoreProviderMetadata::discover_async( - IssuerUrl::new(config.discovery_url.clone()) - .map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?, - client, - ) - .await - .map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?; - + if let Some(OidcClient { machine, .. }) = &self.client { + let discovered = self.discover().await?; machine - .set( - OidcClientMachine::from_provider_metadata( - provider_metadata, - config.client_id.clone(), - Some(client_secret.clone()), - ) - .set_redirect_uri(RedirectUrl::from_url(redirect_url)), - ) + .set(SyncRwLock::new(Arc::new(discovered))) .expect("machine should be empty"); } @@ -223,6 +203,33 @@ impl Service { pub fn enabled(&self) -> bool { self.client.is_some() } + async fn discover(&self) -> Result { + let OidcClient { config, client_secret, client, .. } = + self.client.as_ref().expect("oidc should be configured"); + + let redirect_url = self + .services + .config + .get_client_domain() + .join(&format!("{}/oidc/complete", conduwuit::ROUTE_PREFIX)) + .expect("redirect url should be valid"); + + let provider_metadata = CoreProviderMetadata::discover_async( + IssuerUrl::new(config.discovery_url.clone()) + .map_err(|err| err!("Failed to parse OIDC discovery URL: {err}"))?, + client, + ) + .await + .map_err(|err| err!("Failed to discover OIDC provider metadata: {err}"))?; + + Ok(OidcClientMachine::from_provider_metadata( + provider_metadata, + config.client_id.clone(), + Some(client_secret.clone()), + ) + .set_redirect_uri(RedirectUrl::from_url(redirect_url))) + } + pub fn provider_name(&self) -> Option { let OidcClient { config, .. } = self.client.as_ref().expect("oidc should be configured"); @@ -252,7 +259,7 @@ impl Service { pub async fn begin_session(&self, prompt: Option) -> (PendingSession, Url) { let OidcClient { machine, config, .. } = self.client.as_ref().expect("oidc should be configured"); - let machine = machine.wait().await; + let machine = machine.wait().await.read().clone(); let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); @@ -283,13 +290,13 @@ impl Service { return Err("Delegated authentication is not enabled on this server."); }; - let machine = machine.wait().await; + let current = machine.wait().await.read().clone(); if session.csrf_token.into_secret() != response.state { return Err("State mismatch."); } - let token_response = machine + let token_response = current .exchange_code(AuthorizationCode::new(response.code)) .expect("machine should be configured correctly") .set_pkce_verifier(session.pkce_verifier) @@ -306,19 +313,41 @@ impl Service { return Err(Self::SERVER_MISCONFIGURED); }; - let verifier = machine - .id_token_verifier() - .set_other_audience_verifier_fn(|audience| { - config.additional_trusted_audiences.contains(audience) - }); + let verify = |machine: &OidcClientMachine| { + let verifier = + machine + .id_token_verifier() + .set_other_audience_verifier_fn(|audience| { + config.additional_trusted_audiences.contains(audience) + }); - let claims = id_token - .claims(&verifier, &session.nonce) - .map_err(|err| { - error!("Failed to verify id token claims: {err}"); - Self::SERVER_MISCONFIGURED - })? - .to_owned(); + id_token + .claims(&verifier, &session.nonce) + .map(ToOwned::to_owned) + }; + + let mut result = verify(¤t); + + if matches!( + result, + Err(ClaimsVerificationError::SignatureVerification( + SignatureVerificationError::NoMatchingKey + )) + ) { + match self.discover().await { + | Ok(discovered) => { + info!("Refreshed OIDC provider metadata after an unknown signing key"); + result = verify(&discovered); + *machine.wait().await.write() = Arc::new(discovered); + }, + | Err(err) => warn!("Failed to refresh OIDC provider metadata: {err}"), + } + } + + let claims = result.map_err(|err| { + error!("Failed to verify id token claims: {err}"); + Self::SERVER_MISCONFIGURED + })?; info!(subject = claims.subject().as_str(), "Authenticated subject"); @@ -330,6 +359,7 @@ impl Service { &self, claims: &Claims, supplied_user_id: Option, + client_ip: &IpAddr, ) -> Result { let Some(OidcClient { config, .. }) = self.client.as_ref() else { return Err("Delegated authentication is not enabled on this server."); @@ -390,7 +420,7 @@ impl Service { // Create a new shadow user self.services .users - .create_local_account(&user_id, None, None, None, None) + .create_local_account(&user_id, None, None, Some(client_ip), None) .await .map_err(|err| { error!("Failed to create a shadow user for {user_id}: {err}"); diff --git a/src/service/pusher/mod.rs b/src/service/pusher/mod.rs index 1dd51495a..a7af1364c 100644 --- a/src/service/pusher/mod.rs +++ b/src/service/pusher/mod.rs @@ -3,7 +3,7 @@ mod webpush; use std::{fmt::Debug, mem, net::IpAddr, sync::Arc}; use bytes::BytesMut; -use conduwuit::utils::response::LimitReadExt; +use conduwuit::{config::experiments::ToggledExperiment, utils::response::LimitReadExt}; use conduwuit_core::{ Err, Event, Result, Server, debug_warn, err, trace, utils::{stream::TryIgnore, string_from_bytes}, @@ -133,7 +133,9 @@ impl Service { self.validate_push_url(&http.url, PUSH_GATEWAY_SCHEMES) .await?; }, - | PusherKind::WebPush(data) => { + | PusherKind::WebPush(data) + if self.services.config.experiments.msc4174.is_enabled() => + { self.validate_push_url(&data.url, WEBPUSH_SCHEMES).await?; webpush::decode_pushkey(pushkey)?; webpush::decode_auth(&data.auth)?; @@ -147,7 +149,7 @@ impl Service { } } }, - | PusherKind::Email(_) | PusherKind::Custom { .. } => (), + | _ => (), } let key = (sender, pushkey); @@ -532,6 +534,7 @@ impl Service { let notify = self .build_notification( + user, pusher, &http.data, http.format.as_ref(), @@ -546,9 +549,12 @@ impl Service { Ok(()) }, - | PusherKind::WebPush(data) => { + | PusherKind::WebPush(data) + if self.services.config.experiments.msc4174.is_enabled() => + { let notify = self .build_notification( + user, pusher, &data.data, data.format.as_ref(), @@ -560,12 +566,14 @@ impl Service { self.send_webpush_notice(user, pusher, data, notify).await }, - | PusherKind::Email(_) | PusherKind::Custom { .. } => Ok(()), + | _ => Ok(()), } } + #[allow(clippy::too_many_arguments)] async fn build_notification( &self, + user: &UserId, pusher: &Pusher, data: &JsonObject, format: Option<&PushFormat>, @@ -614,7 +622,7 @@ impl Service { notify.content = serde_json::value::to_raw_value(event.content()).ok(); if *event.kind() == TimelineEventType::RoomMember { - notify.user_is_target = event.state_key() == Some(event.sender().as_str()); + notify.user_is_target = event.state_key() == Some(user.as_str()); } notify.sender_display_name = diff --git a/src/service/pusher/webpush/mod.rs b/src/service/pusher/webpush/mod.rs index 2a428d539..e8f9572ae 100644 --- a/src/service/pusher/webpush/mod.rs +++ b/src/service/pusher/webpush/mod.rs @@ -3,6 +3,7 @@ mod vapid; use std::time::{Duration, SystemTime}; +use conduwuit::config::experiments::ToggledExperiment; use conduwuit_core::{ Err, Result, debug, debug_warn, err, utils::{self, string::constant_time_eq}, @@ -85,6 +86,9 @@ impl Service { /// Reports whether a Web Push pusher has completed its activation /// handshake. pub async fn is_webpush_activated(&self, sender: &UserId, pushkey: &str) -> bool { + if !self.services.config.experiments.msc4174.is_enabled() { + return false; + } self.webpush_state(sender, pushkey).await.activated } @@ -109,6 +113,9 @@ impl Service { pusher: &Pusher, previous: Option<&Pusher>, ) -> bool { + if !self.services.config.experiments.msc4174.is_enabled() { + return false; + } let Some(data) = pusher.kind.as_webpush() else { return false; }; @@ -126,6 +133,13 @@ impl Service { } pub(super) fn begin_webpush_activation(&self, sender: &UserId, pusher: &Pusher) { + debug_assert!( + self.services.config.experiments.msc4174.is_enabled(), + "begin_webpush_activation should not be called with MSC4174 disabled" + ); + if !self.services.config.experiments.msc4174.is_enabled() { + return; + } // Send a one-time encrypted token before allowing notification // delivery. let token = utils::rand::string(ACK_TOKEN_LENGTH); diff --git a/src/service/pusher/webpush/vapid.rs b/src/service/pusher/webpush/vapid.rs index ad9a83cb7..2d7344f5b 100644 --- a/src/service/pusher/webpush/vapid.rs +++ b/src/service/pusher/webpush/vapid.rs @@ -8,7 +8,7 @@ use conduwuit_database::Database; use p256::{ SecretKey, ecdsa::{Signature, SigningKey, signature::Signer}, - elliptic_curve::sec1::ToEncodedPoint, + elliptic_curve::sec1::ToSec1Point, }; use serde_json::json; @@ -48,7 +48,7 @@ impl Vapid { }; let public_key = - URL_SAFE_NO_PAD.encode(secret.public_key().to_encoded_point(false).as_bytes()); + URL_SAFE_NO_PAD.encode(secret.public_key().to_sec1_point(false).as_bytes()); Ok(Self { secret, diff --git a/src/service/rendezvous/mod.rs b/src/service/rendezvous/mod.rs new file mode 100644 index 000000000..09cceafbc --- /dev/null +++ b/src/service/rendezvous/mod.rs @@ -0,0 +1,168 @@ +use std::{ + sync::Arc, + time::{Duration, SystemTime}, +}; + +use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils}; +use lru_cache::LruCache; +use ruma::{ + OwnedTransactionId, + api::client::rendezvous::{ + create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session, + update_rendezvous_session, + }, +}; + +pub struct Service { + sessions: SyncMutex>, +} + +struct Session { + data: String, + created_at: SystemTime, + last_sequence_token: String, + transaction_sequences: LruCache, +} + +impl Session { + const SAVED_TRANSACTION_SEQUENCES: usize = 256; + + fn new(data: String, sequence_token: String) -> Self { + Self { + data, + created_at: SystemTime::now(), + last_sequence_token: sequence_token, + transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES), + } + } +} + +impl crate::Service for Service { + fn build(_: crate::Args<'_>) -> Result> { + Ok(Arc::new(Self { + sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)), + })) + } + + fn name(&self) -> &str { crate::service::make_name(std::module_path!()) } +} + +impl Service { + const MAX_DATA_SIZE_BYTES: usize = 4096; + const MAX_SESSIONS: usize = 256; + const SESSION_MAX_AGE: Duration = Duration::from_secs(300); + const TOKEN_LENGTH: usize = 32; + + fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) } + + /// Lock and fetch an unexpired rendezvous session. + fn lock_session(&self, id: &str) -> Result> { + // We don't clear out expired sessions manually, the LRU cache will + // evict them over time + SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| { + sessions + .get_mut(id) + .filter(|session| { + SystemTime::now() + .duration_since(session.created_at) + .is_ok_and(|duration| duration < Self::SESSION_MAX_AGE) + }) + .ok_or_else(|| err!(Request(NotFound("Unknown session")))) + }) + .map_err(at!(1)) + } + + /// Create a fresh rendezvous session. + pub fn create_session( + &self, + data: String, + ) -> Result { + if data.len() > Self::MAX_DATA_SIZE_BYTES { + return Err!(Request(TooLarge("Data too large"))); + } + + let id = Self::create_token(); + let sequence_token = Self::create_token(); + + self.sessions + .lock() + .insert(id.clone(), Session::new(data, sequence_token.clone())); + + Ok(create_rendezvous_session::msc4388::Response::new( + id, + sequence_token, + Self::SESSION_MAX_AGE, + )) + } + + /// Update a rendezvous session with new data. + pub fn update_session( + &self, + id: &str, + transaction: OwnedTransactionId, + sequence_token: String, + data: String, + ) -> Result { + let mut session = self.lock_session(id)?; + + // If the provided transaction ID was used already, we have to return + // the sequence token that we returned last time it was used. + // This makes session updates with the same transaction ID idempotent. + if let Some(sequence_token) = session.transaction_sequences.get_mut(&transaction) { + return Ok(update_rendezvous_session::msc4388::Response::new( + sequence_token.to_owned(), + )); + } + + if session.last_sequence_token != sequence_token { + return Err!(Request(ConcurrentWrite("Sequence token mismatch"))); + } + + drop(sequence_token); + + let new_sequence_token = Self::create_token(); + + if data.len() > Self::MAX_DATA_SIZE_BYTES { + return Err!(Request(TooLarge("Data too large"))); + } + + session.data = data; + session.last_sequence_token.clone_from(&new_sequence_token); + session + .transaction_sequences + .insert(transaction, new_sequence_token.clone()); + + Ok(update_rendezvous_session::msc4388::Response::new(new_sequence_token)) + } + + /// Look up a rendezvous session by ID. + pub fn get_session(&self, id: &str) -> Result { + let session = self.lock_session(id)?; + + let session_age = SystemTime::now() + .duration_since(session.created_at) + .unwrap_or(Duration::MAX); + + let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age); + + Ok(get_rendezvous_session::msc4388::Response::new( + session.last_sequence_token.clone(), + session.data.clone(), + session_time_remaining, + )) + } + + /// Delete a rendezvous session. + pub fn delete_session( + &self, + id: &str, + ) -> Result { + let mut sessions = self.sessions.lock(); + + if sessions.remove(id).is_some() { + Ok(delete_rendezvous_session::msc4388::Response::new()) + } else { + Err!(Request(NotFound("Unknown session"))) + } + } +} diff --git a/src/service/rooms/alias/mod.rs b/src/service/rooms/alias/mod.rs index 5056a02fc..bed0fd3c7 100644 --- a/src/service/rooms/alias/mod.rs +++ b/src/service/rooms/alias/mod.rs @@ -269,18 +269,26 @@ impl Service { ) -> Result> { use ruma::api::appservice::query::query_room_alias; - for appservice in self.services.appservice.read().await.values() { - if appservice.aliases.is_match(room_alias.as_str()) - && matches!( - self.services - .sending - .send_appservice_request( - appservice.registration.clone(), - query_room_alias::v1::Request::new(room_alias.to_owned()), - ) - .await, - Ok(Some(_opt_result)) - ) { + let matching_appservices: Vec<_> = self + .services + .appservice + .read() + .values() + .filter(|appservice| appservice.aliases.is_match(room_alias.as_str())) + .cloned() + .collect(); + + for appservice in matching_appservices { + if matches!( + self.services + .sending + .send_appservice_request( + appservice.registration.clone(), + query_room_alias::v1::Request::new(room_alias.to_owned()), + ) + .await, + Ok(Some(_opt_result)) + ) { return self .resolve_local_alias(room_alias) .await @@ -292,7 +300,7 @@ impl Service { Ok(None) } - pub async fn appservice_checks( + pub fn appservice_checks( &self, room_alias: &RoomAliasId, appservice_info: Option<&RegistrationInfo>, @@ -309,12 +317,7 @@ impl Service { if !info.aliases.is_match(room_alias.as_str()) { return Err!(Request(Exclusive("Room alias is not in namespace."))); } - } else if self - .services - .appservice - .is_exclusive_alias(room_alias) - .await - { + } else if self.services.appservice.is_exclusive_alias(room_alias) { return Err!(Request(Exclusive("Room alias reserved by appservice."))); } diff --git a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs index 3fbe57c30..24ef24f54 100644 --- a/src/service/rooms/event_handler/fetch_and_handle_outliers.rs +++ b/src/service/rooms/event_handler/fetch_and_handle_outliers.rs @@ -9,7 +9,7 @@ use assign::assign; use conduwuit::error; use conduwuit::{ Err, Event, PduEvent, Result, debug, debug_info, debug_warn, err, - result::FlatOk, + result::{FlatOk, LogErr}, state_res::lexicographical_topological_sort, trace, utils::{IterStream, math::Expected, stream::BroadbandExt}, @@ -203,8 +203,8 @@ impl super::Service { "GET_MISSING_EVENTS_MAX_BATCH_SIZE (usize) should fit in u16 (<=65536)", )) .max( - // This max call ensures we fetch *at least* all the prev events the - // head has. + // This max call ensures we fetch *at least* all the prev + // events the head has. u16::try_from(head.prev_events.len()) .expect("cannot have more than 20 prev events, which fits in u16"), ); @@ -310,9 +310,9 @@ impl super::Service { .stream() .fold(0_u8, |i, event_id| async move { if self.services.timeline.pdu_exists(event_id).await { - i.expected_add(1) - } else { i + } else { + i.expected_add(1) } }) .await; @@ -387,6 +387,7 @@ impl super::Service { remote: OwnedServerName, event_id: OwnedEventId, room_version_rules: &RoomVersionRules, + create_event_id: &EventId, ) -> Result<(OwnedEventId, CanonicalJsonObject)> { let res = self .services @@ -399,21 +400,28 @@ impl super::Service { .await?; if calculated_event_id != event_id { - Err!(Request(BadJson(warn!( + return Err!(Request(BadJson(warn!( expected=%event_id, received=%calculated_event_id, "Server didn't return event id we requested", - )))) - } else { - Ok((event_id, value)) + )))); } + + Self::pdu_format_check_1(&value, room_version_rules, create_event_id)?; + self.signature_hash_check_2_3(value, room_version_rules) + .await + .map(|value| (calculated_event_id, value)) } + /// Fetches an event from multiple candidates in parallel (by calling + /// fetch_event_via on each candidate), returning the first successful + /// result. async fn fetch_event_vias( &self, candidates: impl Iterator, event_id: &EventId, room_version_rules: &RoomVersionRules, + create_event_id: &EventId, ) -> Result<(OwnedEventId, CanonicalJsonObject)> { if let Ok(pdu_json) = self.services.timeline.get_pdu_json(event_id).await { return Ok((event_id.to_owned(), pdu_json)); @@ -424,6 +432,7 @@ impl super::Service { remote.to_owned(), event_id.to_owned(), room_version_rules, + create_event_id, )) }) .collect::>(); @@ -511,7 +520,12 @@ impl super::Service { })?; debug!(elapsed=?start.elapsed(), "Fetching {target_id} over federation"); let value = match self - .fetch_event_vias(candidates.iter(), &target_id, room_version_rules) + .fetch_event_vias( + candidates.iter(), + &target_id, + room_version_rules, + create_event.event_id(), + ) .await { | Ok((_, value)) => { @@ -657,8 +671,13 @@ impl super::Service { debug_warn!(error=?e, "Not attempting to pull missing prev event"); continue; } - let pdu = match self - .fetch_event_vias(candidates.iter(), &next_id, room_version_rules) + let pdu_json = match self + .fetch_event_vias( + candidates.iter(), + &next_id, + room_version_rules, + create_event.event_id(), + ) .await { | Ok((_, data)) => { @@ -676,7 +695,7 @@ impl super::Service { }, }; - let prev_events = match expect_event_id_array(&pdu, "prev_events").map_err(|e| { + let prev_events = match expect_event_id_array(&pdu_json, "prev_events").map_err(|e| { err!(Request(BadJson(warn!( event_id=%next_id, "Failed to parse event fetched from remote: {e}" @@ -698,11 +717,14 @@ impl super::Service { }) .collect::>() .await; + let Ok(pdu) = PduEvent::from_id_val(&next_id, pdu_json.clone()) + .map_err(|e| err!("Failed to parse already validated PDU {next_id}: {e:?}")) + .log_err() + else { + continue; + }; todo.extend(missing_prev); - discovered_events.insert( - next_id.clone(), - PduEvent::from_id_val(&next_id, pdu).expect("fetched PDU was already validated"), - ); + discovered_events.insert(next_id, pdu); } discovered_events diff --git a/src/service/rooms/event_handler/pdu_checks.rs b/src/service/rooms/event_handler/pdu_checks.rs index 458ff4f3b..af0338a97 100644 --- a/src/service/rooms/event_handler/pdu_checks.rs +++ b/src/service/rooms/event_handler/pdu_checks.rs @@ -62,12 +62,6 @@ impl super::Service { return Err!(Request(TooLarge("PDU is too large"))); } - if event_format.require_room_create_room_id { - if pdu_json.get("room_id").is_none() { - return Err!(Request(BadJson("Missing required PDU field: `room_id`"))); - } - } - let auth_events = expect_event_id_array(pdu_json, "auth_events")?; if auth_events.len() > 10 { return Err!(Request(BadJson("PDU has too many auth events"))); @@ -90,6 +84,9 @@ impl super::Service { let is_create_event = event_type == "m.room.create" && state_key == Some(""); if !is_create_event { + if pdu_json.get("room_id").is_none() { + return Err!(Request(BadJson("Missing required PDU field: `room_id`"))); + } let create_event_in_auth_events = auth_events.iter().any(|id| id == create_event_id); if !event_format.allow_room_create_in_auth_events && create_event_in_auth_events { return Err!(Request(BadJson("PDU references a create event"))); @@ -98,6 +95,8 @@ impl super::Service { { return Err!(Request(BadJson("PDU does not reference the room create event"))); } + } else if !event_format.require_room_create_room_id && pdu_json.get("room_id").is_some() { + return Err!(Request(BadJson("Unexpected PDU field: `room_id`"))); } let prev_events = expect_event_id_array(pdu_json, "prev_events")?; @@ -160,15 +159,9 @@ impl super::Service { ready(auth_events_by_key.get(&key).map(ToOwned::to_owned)) }; - state_res::event_auth::auth_check( - room_version_rules, - pdu, - None, // TODO: third party invite - state_fetch, - create_event, - ) - .await - .map_err(|e| err!("Event self-authentication failed: {e:?}")) + state_res::event_auth::auth_check(room_version_rules, pdu, state_fetch, create_event) + .await + .map_err(|e| err!("Event self-authentication failed: {e:?}")) } /// Checks that the event passes PDU check 5, which ensures that the event @@ -242,7 +235,6 @@ impl super::Service { let auth_check = state_res::event_auth::auth_check( room_version_rules, incoming_pdu, - None, // TODO: third party invite |ty, sk| state_fetch(ty.clone(), sk.into()), create_event.as_pdu(), ) @@ -292,7 +284,6 @@ impl super::Service { state_res::event_auth::auth_check( room_version_rules, incoming_pdu, - None, // third-party invite state_fetch, create_event.as_pdu(), ) diff --git a/src/service/rooms/event_handler/state_at_incoming.rs b/src/service/rooms/event_handler/state_at_incoming.rs index e232df7bc..7025077c7 100644 --- a/src/service/rooms/event_handler/state_at_incoming.rs +++ b/src/service/rooms/event_handler/state_at_incoming.rs @@ -15,6 +15,9 @@ use ruma::{OwnedEventId, RoomId, room_version_rules::RoomVersionRules}; use crate::rooms::short::ShortStateHash; +#[cfg(test)] +mod tests; + impl super::Service { /// Resolves the state before the incoming event. /// @@ -124,7 +127,7 @@ impl super::Service { .pdu_shortstatehash(prev_eventid) .map_ok(move |sstatehash| (sstatehash, prev_event)) }) - .try_collect::>() + .try_collect::>() .inspect_err(|e| debug_error!("failed to calculate N-degree short state hashes: {e}")) .await else { diff --git a/src/service/rooms/event_handler/state_at_incoming/tests.rs b/src/service/rooms/event_handler/state_at_incoming/tests.rs new file mode 100644 index 000000000..fc90905e3 --- /dev/null +++ b/src/service/rooms/event_handler/state_at_incoming/tests.rs @@ -0,0 +1,244 @@ +use conduwuit::PduEvent; +use futures::StreamExt; +use ruma::{RoomId, RoomVersionId, events::StateEventType}; +use serde_json::json; + +use crate::test_utils::test_services; + +#[tokio::test] +async fn admitted_joins_do_not_disappear_after_a_merge() { + use conduwuit::matrix::PartialPdu; + use ruma::{ + UserId, + events::room::{ + join_rules::{JoinRule, RoomJoinRulesEventContent}, + member::{MembershipState, RoomMemberEventContent}, + }, + }; + + let (services, path, _database) = test_services().await; + let alice = UserId::parse("@alice:test.example").unwrap(); + let bob = UserId::parse("@bob:bob.example").unwrap(); + let charlie = UserId::parse("@charlie:charlie.example").unwrap(); + let dave = UserId::parse("@dave:dave.example").unwrap(); + let mut remote_keys = Vec::new(); + for user in [&bob, &charlie, &dave] { + let key = ruma::signatures::Ed25519KeyPair::from_der( + &ruma::signatures::Ed25519KeyPair::generate(), + "test".into(), + ) + .unwrap(); + cache_key(&services, user.server_name(), &key); + remote_keys.push(key); + } + let bootstrap = services + .rooms + .state + .mutex + .lock("!bootstrap:test.example") + .await; + let create_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.create".into(), + content: serde_json::value::to_raw_value(&json!({ "room_version": "12" })) + .unwrap(), + state_key: Some("".into()), + ..Default::default() + }, + &alice, + None, + &bootstrap, + ) + .await + .unwrap(); + drop(bootstrap); + let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap(); + let lock = services.rooms.state.mutex.lock(&room).await; + services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu::state( + alice.to_string(), + &RoomMemberEventContent::new(MembershipState::Join), + ), + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + let rules_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu::state("", &RoomJoinRulesEventContent::new(JoinRule::Public)), + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + drop(lock); + let rules = services.rooms.timeline.get_pdu(&rules_id).await.unwrap(); + let (dave_join, json) = signed_remote_event( + json!({ + "room_id": room, "sender": dave, "type": "m.room.member", "state_key": dave, + "content": { "membership": "join" }, "auth_events": [rules_id], "prev_events": [rules_id], + "depth": rules.depth + ruma::uint!(1), "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + dave.server_name(), + &remote_keys[2], + ); + assert!( + services + .rooms + .event_handler + .handle_incoming_pdu(dave.server_name(), &room, &dave_join.event_id, json, false) + .await + .unwrap() + .is_some() + ); + let mut joins = Vec::new(); + for (user, key) in [&bob, &charlie].into_iter().zip(&remote_keys) { + let signed = signed_remote_event( + json!({ + "room_id": room, "sender": user, "type": "m.room.member", "state_key": user, + "content": { "membership": "join" }, "auth_events": [rules_id], "prev_events": [dave_join.event_id], + "depth": dave_join.depth + ruma::uint!(1), "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + user.server_name(), + key, + ); + joins.push(signed); + } + for ((pdu, json), user) in joins.iter().zip([&bob, &charlie]) { + let accepted = services + .rooms + .event_handler + .handle_incoming_pdu(user.server_name(), &room, &pdu.event_id, json.clone(), false) + .await + .unwrap(); + assert!(accepted.is_some()); + } + let bob_hash = services + .rooms + .state_accessor + .pdu_shortstatehash(&joins[0].0.event_id) + .await + .unwrap(); + let charlie_hash = services + .rooms + .state_accessor + .pdu_shortstatehash(&joins[1].0.event_id) + .await + .unwrap(); + assert_eq!(bob_hash, charlie_hash); + let (merge, json) = signed_remote_event( + json!({ + "room_id": room, "sender": dave, "type": "m.room.message", + "content": { "msgtype": "m.text", "body": "merge" }, + "auth_events": [dave_join.event_id], + "prev_events": [joins[0].0.event_id, joins[1].0.event_id], + "depth": joins[0].0.depth + ruma::uint!(1), + "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + dave.server_name(), + &remote_keys[2], + ); + assert!( + services + .rooms + .event_handler + .handle_incoming_pdu(dave.server_name(), &room, &merge.event_id, json, false) + .await + .unwrap() + .is_some() + ); + let mut results = Vec::new(); + for ((user, key), (join, _)) in [&bob, &charlie].into_iter().zip(&remote_keys).zip(&joins) { + let membership = services + .rooms + .state_accessor + .room_state_get_content::( + &room, + &StateEventType::RoomMember, + user.as_str(), + ) + .await + .unwrap(); + assert_eq!(membership.membership, MembershipState::Join); + let prev_events = services + .rooms + .state + .get_forward_extremities(&room) + .collect::>() + .await; + let depth = services + .rooms + .timeline + .get_pdu(&prev_events[0]) + .await + .unwrap() + .depth + + ruma::uint!(1); + let (message, json) = signed_remote_event( + json!({ + "room_id": room, "sender": user, "type": "m.room.message", + "content": { "msgtype": "m.text", "body": format!("message from {user}") }, + "auth_events": [join.event_id], "prev_events": prev_events, + "depth": depth, "origin_server_ts": conduwuit::utils::millis_since_unix_epoch(), + }), + user.server_name(), + key, + ); + let result = services + .rooms + .event_handler + .handle_incoming_pdu(user.server_name(), &room, &message.event_id, json, false) + .await; + results.push(result.is_ok_and(|pdu| pdu.is_some())); + } + services.stop().await; + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(results, [true, true], "both joined users must be able to send messages"); +} + +fn cache_key( + services: &crate::Services, + server: &ruma::ServerName, + key: &ruma::signatures::Ed25519KeyPair, +) { + let mut response = ruma::api::federation::discovery::ServerSigningKeys::new( + server.to_owned(), + crate::server_keys::in_one_week(), + ); + let id: ruma::OwnedServerSigningKeyId = + format!("ed25519:{}", key.version()).try_into().unwrap(); + response.verify_keys.insert( + id.clone(), + ruma::api::federation::discovery::VerifyKey::new(ruma::serde::Base64::new( + key.public_key().to_vec(), + )), + ); + services.db["servernamekeyid_response"] + .put((server.as_str(), id.as_str()), database::Json(&response)); +} + +fn signed_remote_event( + value: serde_json::Value, + server: &ruma::ServerName, + key: &ruma::signatures::Ed25519KeyPair, +) -> (PduEvent, ruma::CanonicalJsonObject) { + let rules = RoomVersionId::V12.rules().unwrap(); + let mut value = serde_json::from_value(value).unwrap(); + ruma::signatures::hash_and_sign_event(server.as_str(), key, &mut value, &rules.redaction) + .unwrap(); + let id = conduwuit::matrix::event::gen_event_id(&value, &rules).unwrap(); + let pdu = PduEvent::from_id_val(&id, value.clone()).unwrap(); + (pdu, value) +} diff --git a/src/service/rooms/membership/mod.rs b/src/service/rooms/membership/mod.rs index 2f9a926c5..0659db2be 100644 --- a/src/service/rooms/membership/mod.rs +++ b/src/service/rooms/membership/mod.rs @@ -2,7 +2,6 @@ use std::{collections::HashMap, iter::once, sync::Arc}; use conduwuit::{ Err, Event, Pdu, Result, Server, debug, debug_info, debug_warn, defer, err, error, info, - is_true, matrix::{ StateKey, event::{gen_event_id, gen_event_id_canonical_json}, @@ -16,7 +15,7 @@ use database::Database; use futures::{FutureExt, StreamExt, TryFutureExt, join}; use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, - RoomVersionId, UserId, + RoomVersionId, ServerName, UserId, api::{ error::{ErrorKind, IncompatibleRoomVersionErrorData}, federation, @@ -24,12 +23,9 @@ use ruma::{ canonical_json::to_canonical_value, events::{ StateEventType, StaticEventContent, - room::{ - join_rules::RoomJoinRulesEventContent, - member::{MembershipState, RoomMemberEventContent}, - }, + room::member::{MembershipState, RoomMemberEventContent}, }, - room::{AllowRule, JoinRule}, + room::{AllowRule, JoinRule, Restricted, RoomMembership}, }; use crate::{ @@ -44,6 +40,32 @@ use crate::{ sending, server_keys, sync, users, }; +#[derive(PartialEq, Eq)] +pub enum JoinConditionResult { + /// The local server verified that the user satisfies at least one join + /// condition. + Satisfied, + /// The local server verified that the user does not satisfy any join + /// conditions. + Unsatisfied, + /// The local server could not check all join conditions. + UnableToAuthorizeJoin, +} + +#[derive(Copy, Clone, Debug)] +pub enum JoinConditionEntity<'id> { + User(&'id UserId), + Server(&'id ServerName), +} + +impl<'id> From<&'id UserId> for JoinConditionEntity<'id> { + fn from(value: &'id UserId) -> Self { Self::User(value) } +} + +impl<'id> From<&'id ServerName> for JoinConditionEntity<'id> { + fn from(value: &'id ServerName) -> Self { Self::Server(value) } +} + pub struct Service { services: Services, } @@ -110,16 +132,36 @@ impl Service { ) -> Result { assert!(self.services.globals.user_is_local(sender_user), "user should be local"); + let servers: Vec<_> = servers + .iter() + .filter(|server| !self.services.globals.server_is_ours(server)) + .collect(); + let state_lock = self.services.state.mutex.lock(room_id).await; - if self + let server_in_room = self .services .state_cache - .is_joined(sender_user, room_id) - .await - { - debug_warn!("{sender_user} is already joined in {room_id}"); + .server_in_room(self.services.globals.server_name(), room_id) + .await; + + // Only check our known membership if we're already in the room. + // See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/855 + let current_membership = if server_in_room { + self.services + .state_accessor + .get_member(room_id, sender_user) + .await + .ok() + .map_or(MembershipState::Leave, |content| content.membership) + } else { + MembershipState::Leave + }; + + if current_membership == MembershipState::Join { return Ok(room_id.to_owned()); + } else if current_membership == MembershipState::Ban { + return Err!(Request(Forbidden("You are banned from this room."))); } if let Err(e) = self @@ -137,31 +179,16 @@ impl Service { { warn!("Antispam prevented user {} from joining room {}: {}", sender_user, room_id, e); return Err!(Request(Forbidden("You are not allowed to join this room."))); - } - - let server_in_room = self - .services - .state_cache - .server_in_room(self.services.globals.server_name(), room_id) - .await; - - // Only check our known membership if we're already in the room. - // See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/855 - let membership = if server_in_room { - self.services - .state_accessor - .get_member(room_id, sender_user) + } else if self.services.antispam.check_all_joins() { + if self + .services + .antispam + .meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned()) .await - } else { - debug!("Ignoring local state for join {room_id}, we aren't in the room yet."); - Ok(RoomMemberEventContent::new(MembershipState::Leave)) - }; - - if let Ok(m) = membership { - if m.membership == MembershipState::Ban { - debug_warn!("{sender_user} is banned from {room_id} but attempted to join"); - // TODO: return reason - return Err!(Request(Forbidden("You are banned from the room."))); + != JoinConditionResult::Satisfied + { + warn!("Antispam prevented user {} from joining room {}", sender_user, room_id); + return Err!(Request(Forbidden("Antispam rejected join request."))); } } @@ -172,31 +199,42 @@ impl Service { ))); } - if self.services.antispam.check_all_joins() { - if let Err(e) = self - .services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), sender_user.to_owned()) + if server_in_room { + // Try to join the room locally. + match self + .join_local_room( + sender_user, + room_id, + current_membership, + reason.clone(), + &state_lock, + ) + .boxed() .await { - warn!( - "Antispam prevented user {} from joining room {}: {}", - sender_user, room_id, e - ); - return Err!(Request(Forbidden("Antispam rejected join request."))); + | Ok(()) => { + // We were able to authorize a local join. + info!("Joined room locally"); + return Ok(room_id.to_owned()); + }, + | Err(err) => { + // We couldn't authorize a local join, probably because it's + // restricted and we couldn't satisfy + // the join rules ourselves. + if servers.is_empty() { + return Err(err); + } + info!(?err, "Failed to join room locally, trying over federation instead"); + }, } } - if server_in_room { - self.join_local_room(sender_user, room_id, reason, servers, state_lock) - .boxed() - .await?; - } else { - // Ask a remote server if we are not participating in this room - self.join_remote_room(sender_user, room_id, reason, servers, state_lock) - .boxed() - .await?; - } + drop(state_lock); + // If we aren't participating in the room, or failed to join locally, + // try to join over federation. + self.join_remote_room(sender_user, room_id, reason, &servers) + .boxed() + .await?; Ok(room_id.to_owned()) } @@ -206,39 +244,39 @@ impl Service { &self, sender_user: &UserId, room_id: &RoomId, + current_membership: MembershipState, reason: Option, - servers: &[OwnedServerName], - state_lock: RoomMutexGuard, + state_lock: &RoomMutexGuard, ) -> Result { info!("Joining room locally"); - let (room_version, join_rules, is_invited) = join!( + let (room_version, join_rules) = join!( self.services.state.get_room_version(room_id), self.services.state_accessor.get_join_rules(room_id), - self.services.state_cache.is_invited(sender_user, room_id) ); let room_version = room_version?; let room_version_rules = room_version.rules().unwrap(); let mut auth_user: Option = None; - if !is_invited - && matches!(join_rules, JoinRule::Restricted(_) | JoinRule::KnockRestricted(_)) + + if !matches!(current_membership, MembershipState::Invite | MembershipState::Knock) + && let JoinRule::Restricted(conditions) | JoinRule::KnockRestricted(conditions) = + &join_rules { if room_version_rules.authorization.restricted_join_rule { // This is a restricted room, check if we can complete the join // requirements locally. - let needs_auth_user = self - .user_can_perform_restricted_join(sender_user, room_id) - .await; - if needs_auth_user.is_ok_and(is_true!()) { - // If there was an error or the value is false, we'll try - // joining over federation. Since it's Ok(true), we can - // authorise this locally. If we can't select a local - // user, this will remain None, the join will fail, and - // we'll fall back to federation. + if self + .evaluate_join_conditions(room_id, sender_user.into(), conditions) + .await + == JoinConditionResult::Satisfied + { + // Try to find an authorizing user. If we can't find one, + // the local join will fail to authorize and we'll fall back + // to federation. auth_user = self - .select_authorising_user(room_id, sender_user, &state_lock) + .select_authorizing_user(room_id, sender_user, state_lock) .await .ok(); } @@ -251,54 +289,26 @@ impl Service { content.reason.clone_from(&reason); content.join_authorized_via_users_server = auth_user; - // Try normal join first - let Err(error) = self - .services + self.services .timeline .build_and_append_pdu( PartialPdu::state(sender_user.to_string(), &content), sender_user, Some(room_id), - &state_lock, + state_lock, ) - .await - else { - info!("Joined room locally"); - return Ok(()); - }; + .await?; - if servers.is_empty() - || servers.len() == 1 && self.services.globals.server_is_ours(&servers[0]) - { - if !self.services.metadata.exists(room_id).await { - return Err!(Request( - Unknown( - "Room was not found locally and no servers were found to help us \ - discover it" - ), - NOT_FOUND - )); - } - - return Err(error); - } - - info!( - ?error, - remote_servers = %servers.len(), - "Could not join room locally, attempting remote join", - ); - Box::pin(self.join_remote_room(sender_user, room_id, reason, servers, state_lock)).await + Ok(()) } #[tracing::instrument(skip_all, fields(%sender_user, %room_id), name = "join_remote_room", level = "info")] - pub async fn join_remote_room( + async fn join_remote_room( &self, sender_user: &UserId, room_id: &RoomId, reason: Option, - servers: &[OwnedServerName], - state_lock: RoomMutexGuard, + servers: &[&OwnedServerName], ) -> Result { // public so the admin command force-join-room-remotely works info!("Joining {room_id} over federation."); @@ -524,7 +534,7 @@ impl Service { return state; }, }; - if !pdu_fits(&value.clone()) { + if !pdu_fits(&value) { warn!( "dropping incoming PDU {event_id} in room {room_id} from room join \ because it exceeds 65535 bytes or is otherwise too large." @@ -533,9 +543,6 @@ impl Service { } self.services.outlier.add_pdu_outlier(&event_id, &value); self.services.pdu_metadata.clear_pdu_markers(&event_id); - self.services - .pdu_metadata - .mark_as_referenced(room_id, once(event_id.as_ref())); if let Some(state_key) = &pdu.state_key { let shortstatekey = self .services @@ -568,9 +575,6 @@ impl Service { trace!(%event_id, "Adding PDU as an outlier from send_join auth_chain"); self.services.outlier.add_pdu_outlier(&event_id, &value); self.services.pdu_metadata.clear_pdu_markers(&event_id); - self.services - .pdu_metadata - .mark_as_referenced(room_id, once(event_id.as_ref())); let state_key = value .get("state_key") .and_then(|s| s.as_str()) @@ -616,7 +620,6 @@ impl Service { let auth_check = state_res::event_auth::auth_check( &room_version.rules().unwrap(), &parsed_join_pdu, - None, // TODO: third party invite |k, s| state_fetch(k.clone(), s.into()), &create_event, ) @@ -655,6 +658,7 @@ impl Service { .await?; debug!("Forcing state for new room"); + let state_lock = self.services.state.mutex.lock(room_id).await; self.services .state .force_state(room_id, statehash_before_join, added, removed, &state_lock) @@ -666,6 +670,10 @@ impl Service { // We append to state before appending the pdu, so we don't have a // moment in time with the pdu without it's state. This is okay // because append_pdu can't fail. + self.services + .timeline + .progress_extremities(&parsed_join_pdu) + .await?; let statehash_after_join = self .services .state @@ -675,14 +683,8 @@ impl Service { info!("Appending new room join event"); self.services .timeline - .append_pdu( - &parsed_join_pdu, - join_event, - once(parsed_join_pdu.event_id.as_ref()), - &state_lock, - room_id, - ) - .await?; + .append_pdu(&parsed_join_pdu, join_event, room_id) + .await; self.services .metadata .maybe_set_mindepth(room_id, parsed_join_pdu.depth.into()) @@ -704,7 +706,11 @@ impl Service { info!("Replacing local forward extremities"); self.services .state - .set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), &state_lock) + .replace_forward_extremities( + room_id, + once(parsed_join_pdu.event_id()), + &state_lock, + ) .await; } drop(cork); @@ -722,7 +728,7 @@ impl Service { &self, sender_user: &UserId, room_id: &RoomId, - servers: &[OwnedServerName], + servers: &[&OwnedServerName], ) -> Result<(federation::membership::prepare_join_event::v1::Response, OwnedServerName)> { let mut make_join_counter: usize = 1; @@ -762,7 +768,7 @@ impl Service { warn!("make_join response from {remote_server} failed validation: {e}"); continue; } - return Ok((response, remote_server.clone())); + return Ok((response, (*remote_server).clone())); }, | Err(e) => match e.kind() { | ErrorKind::UnableToAuthorizeJoin => { @@ -810,7 +816,7 @@ impl Service { /// Attempts to find a user who is able to issue an invite in the target /// room. - pub async fn select_authorising_user<'a>( + pub async fn select_authorizing_user<'a>( &self, room_id: &'a RoomId, user_id: &'a UserId, @@ -838,108 +844,115 @@ impl Service { /// Checks whether the given user can join the given room via a restricted /// join. - pub(crate) async fn user_can_perform_restricted_join( + pub async fn evaluate_join_conditions( &self, - user_id: &UserId, room_id: &RoomId, - ) -> Result { - let Ok(join_rules_event_content) = self - .services - .state_accessor - .room_state_get_content::( - room_id, - &StateEventType::RoomJoinRules, - "", - ) - .await - else { - // No join rules means there's nothing to authorise (defaults to - // invite) - return Ok(false); - }; - - let (JoinRule::Restricted(r) | JoinRule::KnockRestricted(r)) = - join_rules_event_content.join_rule - else { - // This is not a restricted room - return Ok(false); - }; - - if r.allow.is_empty() { + entity: JoinConditionEntity<'_>, + conditions: &Restricted, + ) -> JoinConditionResult { + if conditions.allow.is_empty() { // This will never be authorisable, return forbidden. - return Err!(Request(Forbidden("You are not invited to this room."))); + return JoinConditionResult::Unsatisfied; } - let mut could_satisfy = true; - for allow_rule in &r.allow { - match allow_rule { - | AllowRule::RoomMembership(membership) => { - if !self - .services - .state_cache - .server_in_room(self.services.globals.server_name(), &membership.room_id) - .await - { - // Since we can't check this room, mark could_satisfy as - // false so that we can return - // M_UNABLE_TO_AUTHORIZE_JOIN later. - could_satisfy = false; - continue; - } + let mut unable_to_authorize = false; - if self - .services - .state_cache - .is_joined(user_id, &membership.room_id) - .await - { - debug!( - "User {} is allowed to join room {} via membership in room {}", - user_id, room_id, membership.room_id - ); - return Ok(true); - } + for rule in &conditions.allow { + match self.evaluate_allow_rule(room_id, entity, rule).await { + | JoinConditionResult::Satisfied => { + // This allow rule is satisfied, the user can join. + return JoinConditionResult::Satisfied; }, - | other if other.rule_type() == "fi.mau.spam_checker" => - return match self - .services - .antispam - .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) - .await - { - | Ok(()) => Ok(true), - | Err(_) => Err!(Request(Forbidden("Antispam rejected join request."))), - }, - | _ => { - // We don't recognise this join rule, so we cannot satisfy - // the request. - could_satisfy = false; - debug_info!( - "Unsupported allow rule in restricted join for room {}: {:?}", - room_id, - allow_rule - ); + | JoinConditionResult::Unsatisfied => { + // This allow rule is not satisfied, but the user might be + // able to join if they satisfy another + // rule. Keep checking. + continue; + }, + | JoinConditionResult::UnableToAuthorizeJoin => { + // We couldn't check this allow rule, but the user might be + // able to join if they satisfy another + // rule. Keep checking. + unable_to_authorize = true; + continue; }, } } - if could_satisfy { - // We were able to check all the restrictions and can be certain - // that the prospective member is not permitted to join. - Err!(Request(Forbidden( - "You do not belong to any of the rooms or spaces required to join this room." - ))) + if unable_to_authorize { + // We couldn't conclusively determine if the user satisfies some + // rules. + JoinConditionResult::UnableToAuthorizeJoin } else { - // We were unable to check all the restrictions. This usually means - // we aren't in one of the rooms this one is restricted to, ergo - // can't check its state for the user's membership, and - // consequently the user *might* be able to join if - // they ask another server. - Err!(Request(UnableToAuthorizeJoin( - "You do not belong to any of the recognised rooms or spaces required to join \ - this room, but this server is unable to verify every requirement. You may be \ - able to join via another server." - ))) + // We determined that the user does not satisfy any rules. + JoinConditionResult::Unsatisfied + } + } + + async fn evaluate_allow_rule( + &self, + room_id: &RoomId, + entity: JoinConditionEntity<'_>, + rule: &AllowRule, + ) -> JoinConditionResult { + match rule { + | AllowRule::RoomMembership(RoomMembership { room_id: condition_room, .. }) => { + if self + .services + .state_cache + .server_in_room(self.services.globals.server_name(), condition_room) + .await + { + let is_joined_to_condition_room = match entity { + | JoinConditionEntity::User(user_id) => + self.services + .state_cache + .is_joined(user_id, condition_room) + .await, + | JoinConditionEntity::Server(server) => + self.services + .state_cache + .server_in_room(server, condition_room) + .await, + }; + + if is_joined_to_condition_room { + debug!( + ?entity, + ?room_id, + ?condition_room, + "Entity may join via membership" + ); + JoinConditionResult::Satisfied + } else { + JoinConditionResult::Unsatisfied + } + } else { + JoinConditionResult::UnableToAuthorizeJoin + } + }, + | other if other.rule_type() == "fi.mau.spam_checker" => { + if let JoinConditionEntity::User(user_id) = entity { + self.services + .antispam + .meowlnir_accept_make_join(room_id.to_owned(), user_id.to_owned()) + .await + } else { + // We can't currently check server names against the spam + // checker, so we just assume that they + // can't access the room for now. + JoinConditionResult::Unsatisfied + } + }, + | unknown => { + debug!( + ?entity, + ?room_id, + rule_type = unknown.rule_type(), + "Could not check unknown allow rule" + ); + JoinConditionResult::UnableToAuthorizeJoin + }, } } } diff --git a/src/service/rooms/pdu_metadata/bundled_aggregations.rs b/src/service/rooms/pdu_metadata/bundled_aggregations.rs index b6b1cb930..bc7204e8c 100644 --- a/src/service/rooms/pdu_metadata/bundled_aggregations.rs +++ b/src/service/rooms/pdu_metadata/bundled_aggregations.rs @@ -1,14 +1,16 @@ -use conduwuit::{Event, PduEvent, Result, err}; +use conduwuit::{ + Event, PduEvent, Result, err, + matrix::{PduCount, event::relation_type}, + utils::ReadyExt, +}; use ruma::{ UserId, api::Direction, - events::relation::{BundledMessageLikeRelations, BundledReference, ReferenceChunk}, + events::relation::{ + BundledMessageLikeRelations, BundledReference, ReferenceChunk, RelationType, + }, }; -use crate::rooms::timeline::PdusIterItem; - -const MAX_BUNDLED_RELATIONS: usize = 50; - impl super::Service { /// Gets bundled aggregations for an event according to the Matrix /// specification. @@ -26,52 +28,24 @@ impl super::Service { return Ok(None); } - let relations = self - .get_relations( - user_id, - &pdu.room_id_or_hash(), - pdu.event_id(), - conduwuit::PduCount::max(), - MAX_BUNDLED_RELATIONS, - 0, - Direction::Backward, - ) + let Some((room_id, target)) = self + .relation_target(&pdu.room_id_or_hash(), pdu.event_id()) + .await + else { + return Ok(None); + }; + + let mut replace_events = Vec::new(); + let mut reference_events = Vec::new(); + self.db + .get_relations(room_id, target, PduCount::max(), Direction::Backward) + .ready_for_each(|(_, relation)| match relation_type(&relation) { + | Some(RelationType::Replacement) => replace_events.push(relation), + | Some(RelationType::Reference) => reference_events.push(relation), + | _ => {}, + }) .await; - // The relations database code still handles the basic unsigned data - // We don't want to recursively fetch relations - - if relations.is_empty() { - return Ok(None); - } - - // Partition relations by type - let (replace_events, reference_events): (Vec<_>, Vec<_>) = relations - .iter() - .filter_map(|relation| { - let pdu = &relation.1; - let content = pdu.get_content_as_value(); - - content - .get("m.relates_to") - .and_then(|relates_to| relates_to.get("rel_type")) - .and_then(|rel_type| rel_type.as_str()) - .and_then(|rel_type_str| match rel_type_str { - | "m.replace" => Some(RelationType::Replace(relation)), - | "m.reference" => Some(RelationType::Reference(relation)), - | _ => None, /* Ignore other relation types (threads are in DB but not - * handled here) */ - }) - }) - .fold((Vec::new(), Vec::new()), |(mut replaces, mut references), rel_type| { - match rel_type { - | RelationType::Replace(r) => replaces.push(r), - | RelationType::Reference(r) => references.push(r), - } - (replaces, references) - }); - - // If no relations to bundle, return None if replace_events.is_empty() && reference_events.is_empty() { return Ok(None); } @@ -85,7 +59,9 @@ impl super::Service { .find_most_recent_valid_replacement(user_id, pdu, &replace_events) .await? { - bundled.replace = Some(Self::serialize_replacement(replacement)?); + bundled.replace = Some(Self::serialize_replacement( + &self.with_unsigned(user_id, replacement.clone()).await, + )?); } } @@ -93,7 +69,7 @@ impl super::Service { if !reference_events.is_empty() { let reference_chunk: Vec<_> = reference_events .into_iter() - .map(|relation| BundledReference::new(relation.1.event_id().to_owned())) + .map(|relation| BundledReference::new(relation.event_id().to_owned())) .collect(); if !reference_chunk.is_empty() { @@ -123,14 +99,12 @@ impl super::Service { &self, user_id: &UserId, original_event: &PduEvent, - replacement_events: &[&'a PdusIterItem], + replacement_events: &'a [PduEvent], ) -> Result> { // Filter valid replacements and find the maximum in a single pass let mut result: Option<&PduEvent> = None; - for relation in replacement_events { - let pdu = &relation.1; - + for pdu in replacement_events { // Validate replacement if !Self::is_valid_replacement_event(original_event, pdu).await? { continue; @@ -245,12 +219,7 @@ impl super::Service { /// Check if an event is itself a replacement #[inline] fn is_replacement_event(event: &PduEvent) -> bool { - event - .get_content_as_value() - .get("m.relates_to") - .and_then(|relates_to| relates_to.get("rel_type")) - .and_then(|rel_type| rel_type.as_str()) - .is_some_and(|rel_type| rel_type == "m.replace") + relation_type(event) == Some(RelationType::Replacement) } /// Check if event has m.new_content or is encrypted (where m.new_content @@ -262,12 +231,6 @@ impl super::Service { } } -/// Helper enum for partitioning relations -enum RelationType<'a> { - Replace(&'a PdusIterItem), - Reference(&'a PdusIterItem), -} - #[cfg(test)] mod tests { use conduwuit_core::pdu::{EventHash, PduEvent}; diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index db3973f06..2b40f6e52 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -2,8 +2,7 @@ use std::{mem::size_of, sync::Arc}; use conduwuit::{ arrayvec::ArrayVec, - matrix::PduCount, - result::LogErr, + matrix::{PduCount, PduEvent}, utils::{ ReadyExt, stream::{TryIgnore, WidebandExt}, @@ -12,22 +11,22 @@ use conduwuit::{ }; use database::Map; use futures::{Stream, StreamExt}; -use ruma::{EventId, RoomId, UserId, api::Direction}; +use ruma::{EventId, RoomId, api::Direction}; use crate::{ Dep, rooms::{ self, - short::{ShortEventId, ShortRoomId}, - timeline::{PduId, PdusIterItem, RawPduId}, + short::ShortRoomId, + timeline::{PduId, RawPduId}, }, }; pub(super) struct Data { tofrom_relation: Arc, - referencedevents: Arc, softfailedeventids: Arc, rejectedeventids: Arc, + referencedevents: Arc, services: Services, } @@ -40,9 +39,9 @@ impl Data { let db = &args.db; Self { tofrom_relation: db["tofrom_relation"].clone(), - referencedevents: db["referencedevents"].clone(), softfailedeventids: db["softfailedeventids"].clone(), rejectedeventids: db["rejectedeventids"].clone(), + referencedevents: db["referencedevents"].clone(), services: Services { timeline: args.depend::("rooms::timeline"), }, @@ -56,70 +55,54 @@ impl Data { self.tofrom_relation.aput_raw::(key, []); } - pub(super) fn get_relations<'a>( - &'a self, - user_id: &'a UserId, + pub(super) fn get_relations( + &self, shortroomid: ShortRoomId, - target: ShortEventId, + target: u64, from: PduCount, dir: Direction, - ) -> impl Stream + Send + 'a { - // Query from exact position then filter excludes it (saturating_inc - // could skip events at min/max boundaries) - let from_unsigned = from.into_unsigned(); - let mut current = ArrayVec::::new(); - current.extend(target.to_be_bytes()); - current.extend(from_unsigned.to_be_bytes()); - let current = current.as_slice(); + ) -> impl Stream + Send + '_ { + self.relation_counts(target, from, dir) + .wide_filter_map(move |count| self.get_relation_pdu(shortroomid, count)) + } + + /// The counts of the direct relations of `target`, in the order of `dir`, + /// starting after `from`. + pub(super) fn relation_counts( + &self, + target: u64, + from: PduCount, + dir: Direction, + ) -> impl Stream + Send + '_ { + let start_count = match from { + | PduCount::Normal(count) => count, + | PduCount::Backfilled(_) => 0, + }; + let mut start = ArrayVec::::new(); + start.extend(target.to_be_bytes()); + start.extend(start_count.to_be_bytes()); + let start = start.as_slice(); match dir { - | Direction::Forward => self.tofrom_relation.raw_keys_from(current).boxed(), - | Direction::Backward => self.tofrom_relation.rev_raw_keys_from(current).boxed(), + | Direction::Forward => self.tofrom_relation.raw_keys_from(start).boxed(), + | Direction::Backward => self.tofrom_relation.rev_raw_keys_from(start).boxed(), } .ignore_err() .ready_take_while(move |key| key.starts_with(&target.to_be_bytes())) .map(|to_from| u64_from_u8(&to_from[8..16])) - .map(PduCount::from_unsigned) - .ready_filter(move |count| { - if from == PduCount::min() || from == PduCount::max() { - true - } else { - let count_unsigned = count.into_unsigned(); - match dir { - | Direction::Forward => count_unsigned > from_unsigned, - | Direction::Backward => count_unsigned < from_unsigned, - } - } - }) - .wide_filter_map(move |shorteventid| async move { - let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); - - let mut pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; - - let ctx = self - .services - .timeline - .get_unsigned_context(&pdu, Some(user_id)) - .await; - pdu.set_unsigned(Some(ctx)).log_err().ok(); - - Some((shorteventid, pdu)) - }) + // The scan includes `from` itself, which should be skipped + .ready_filter(move |&count| PduCount::Normal(count).is_after(from, dir)) } - #[inline] - pub(super) fn mark_as_referenced<'a, I>(&self, room_id: &RoomId, event_ids: I) - where - I: Iterator, - { - for prev in event_ids { - let key = (room_id, prev); - self.referencedevents.put_raw(key, []); - } - } + pub(super) async fn get_relation_pdu( + &self, + shortroomid: ShortRoomId, + count: u64, + ) -> Option<(u64, PduEvent)> { + let shorteventid = PduCount::Normal(count); + let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); + let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await.ok()?; - pub(super) async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { - let key = (room_id, event_id); - self.referencedevents.qry(&key).await.is_ok() + Some((count, pdu)) } pub(super) fn mark_event_soft_failed(&self, event_id: &EventId) { @@ -151,4 +134,16 @@ impl Data { self.unmark_event_rejected(event_id); self.unmark_event_soft_failed(event_id); } + + #[inline] + pub(super) fn mark_as_referenced(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.referencedevents.put_raw(key, []); + } + + #[inline] + pub(super) async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { + let key = (room_id, event_id); + self.referencedevents.qry(&key).await.is_ok() + } } diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index 7c22f408b..0ff50402c 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -1,15 +1,20 @@ mod bundled_aggregations; mod data; -use std::sync::Arc; +use std::{collections::HashSet, sync::Arc}; -use conduwuit::{Result, matrix::PduCount}; -use futures::{StreamExt, future::try_join}; +use conduwuit::{ + Result, + matrix::{PduCount, PduEvent}, + result::LogErr, + utils::{IterStream, ReadyExt, stream::WidebandExt}, +}; +use futures::{Stream, StreamExt, future::try_join}; use ruma::{EventId, RoomId, UserId, api::Direction}; use self::data::Data; use crate::{ Dep, - rooms::{self, timeline::PdusIterItem}, + rooms::{self, short::ShortRoomId, timeline::PdusIterItem}, }; pub struct Service { @@ -51,7 +56,7 @@ impl Service { } #[allow(clippy::too_many_arguments)] - pub async fn get_relations<'a>( + pub async fn get_relations<'a, F>( &'a self, user_id: &'a UserId, room_id: &'a RoomId, @@ -60,73 +65,130 @@ impl Service { limit: usize, max_depth: u8, dir: Direction, - ) -> Vec { - let room_id = self.services.short.get_shortroomid(room_id); - - let target = self.services.timeline.get_pdu_count(target); - - let Ok((room_id, target)) = try_join(room_id, target).await else { + matches: F, + ) -> Vec + where + F: Fn(&PduEvent) -> bool + Send + Sync, + { + let Some((room_id, target)) = self.relation_target(room_id, target).await else { return Vec::new(); }; - let target = match target { - | PduCount::Normal(c) => c, - // TODO: Support backfilled relations - | _ => 0, // This will result in an empty iterator + // Direct relations are already in order + if max_depth == 0 { + let counts = self.db.relation_counts(target, from, dir); + return self + .load_relations(user_id, room_id, counts, limit, &matches) + .await; + } + + let scan_from = match dir { + | Direction::Forward => PduCount::min(), + | Direction::Backward => from, }; - let mut pdus: Vec<_> = self + // An event can relate to two others in the tree, like a thread reply + // that also replies to another reply in the thread, so it's only kept + // and looked through the first time it's found + let mut seen = HashSet::new(); + let mut counts = Vec::new(); + let mut level: Vec<_> = self .db - .get_relations(user_id, room_id, target, from, dir) + .relation_counts(target, scan_from, dir) .collect() .await; + seen.extend(level.iter().copied()); + for _ in 0..max_depth { + if level.is_empty() { + break; + } - let mut stack: Vec<_> = pdus - .iter() - .filter(|_| max_depth > 0) - .map(|pdu| (pdu.clone(), 1)) - .collect(); - - 'limit: while let Some(stack_pdu) = stack.pop() { - let target = match stack_pdu.0.0 { - | PduCount::Normal(c) => c, - // TODO: Support backfilled relations - | PduCount::Backfilled(_) => 0, // This will result in an empty iterator - }; - - let relations: Vec<_> = self - .db - .get_relations(user_id, room_id, target, from, dir) + let next: Vec> = level + .iter() + .copied() + .stream() + .wide_then(|target| { + self.db + .relation_counts(target, scan_from, dir) + .collect::>() + }) .collect() .await; - for relation in relations { - if stack_pdu.1 < max_depth { - stack.push((relation.clone(), stack_pdu.1.saturating_add(1))); - } - - pdus.push(relation); - if pdus.len() >= limit { - break 'limit; - } - } + counts.append(&mut level); + level = next + .into_iter() + .flatten() + .filter(|&count| seen.insert(count)) + .collect(); } + counts.append(&mut level); - pdus + counts.retain(|&count| PduCount::Normal(count).is_after(from, dir)); + counts.sort_unstable_by(|a, b| match dir { + | Direction::Forward => a.cmp(b), + | Direction::Backward => b.cmp(a), + }); + + self.load_relations(user_id, room_id, counts.into_iter().stream(), limit, &matches) + .await } - #[tracing::instrument(skip_all, level = "debug")] - pub fn mark_as_referenced<'a, I>(&self, room_id: &RoomId, event_ids: I) + /// Loads the pdus of relations in the order of `counts` + async fn load_relations( + &self, + user_id: &UserId, + room_id: ShortRoomId, + counts: S, + limit: usize, + matches: &F, + ) -> Vec where - I: Iterator, + S: Stream + Send, + F: Fn(&PduEvent) -> bool + Send + Sync, { - self.db.mark_as_referenced(room_id, event_ids); + counts + .wide_filter_map(|count| self.db.get_relation_pdu(room_id, count)) + .ready_filter(|(_, pdu)| matches(pdu)) + .take(limit) + .wide_then(|relation| self.finish_relation(user_id, relation)) + .collect() + .await } - #[inline] - #[tracing::instrument(skip(self), level = "debug")] - pub async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { - self.db.is_event_referenced(room_id, event_id).await + /// The short room ID and count of `target` + async fn relation_target( + &self, + room_id: &RoomId, + target: &EventId, + ) -> Option<(ShortRoomId, u64)> { + let room_id = self.services.short.get_shortroomid(room_id); + let target = self.services.timeline.get_pdu_count(target); + + match try_join(room_id, target).await { + | Ok((room_id, PduCount::Normal(target))) => Some((room_id, target)), + // TODO: Support backfilled relations + | _ => None, + } + } + + async fn finish_relation( + &self, + user_id: &UserId, + (count, pdu): (u64, PduEvent), + ) -> PdusIterItem { + (PduCount::Normal(count), self.with_unsigned(user_id, pdu).await) + } + + async fn with_unsigned(&self, user_id: &UserId, mut pdu: PduEvent) -> PduEvent { + let ctx = self + .services + .timeline + .get_unsigned_context(&pdu, Some(user_id)) + .await; + pdu.set_unsigned(Some(ctx)).log_err().ok(); + + pdu } #[inline] @@ -145,6 +207,14 @@ impl Service { self.db.is_event_rejected(event_id).await } + pub async fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> bool { + self.db.is_event_referenced(room_id, event_id).await + } + + pub fn mark_as_referenced(&self, room_id: &RoomId, event_id: &EventId) { + self.db.mark_as_referenced(room_id, event_id); + } + pub fn mark_event_rejected(&self, event_id: &EventId) { self.db.mark_event_rejected(event_id); } diff --git a/src/service/rooms/read_receipt/data.rs b/src/service/rooms/read_receipt/data.rs index bcffd708c..496e76ece 100644 --- a/src/service/rooms/read_receipt/data.rs +++ b/src/service/rooms/read_receipt/data.rs @@ -8,7 +8,10 @@ use database::{Deserialized, Json, Map}; use futures::{Stream, StreamExt}; use ruma::{ CanonicalJsonObject, OwnedRoomId, OwnedUserId, RoomId, UserId, - events::{AnySyncEphemeralRoomEvent, receipt::ReceiptEvent}, + events::{ + AnySyncEphemeralRoomEvent, + receipt::{ReceiptEvent, ReceiptType}, + }, serde::Raw, }; @@ -45,20 +48,57 @@ impl Data { user_id: &UserId, room_id: &RoomId, event: &ReceiptEvent, - ) { - // Remove old entry + ) -> bool { + let Some((new_event, new_receipt)) = + event.content.user_receipt(user_id, ReceiptType::Read) + else { + return false; + }; + + // Find old entries for this user in this room let last_possible_key = (room_id, u64::MAX); + let mut old_entries = Vec::new(); self.readreceiptid_readreceipt - .rev_keys_from_raw(&last_possible_key) + .rev_stream_from_raw(&last_possible_key) .ignore_err() - .ready_take_while(|key| key.starts_with(room_id.as_bytes())) - .ready_filter_map(|key| key.ends_with(user_id.as_bytes()).then_some(key)) - .ready_for_each(|key| self.readreceiptid_readreceipt.del(key)) + .ready_take_while(|(key, _)| key.starts_with(room_id.as_bytes())) + .ready_filter_map(|(key, val)| { + key.ends_with(user_id.as_bytes()) + .then(|| (key.to_vec(), serde_json::from_slice::(val).ok())) + }) + .ready_for_each(|entry| old_entries.push(entry)) .await; + let mut to_del = Vec::new(); + + for (key, existing) in old_entries { + let Some(existing) = existing else { + to_del.push(key); + continue; + }; + let Some((old_event, old_receipt)) = + existing.content.user_receipt(user_id, ReceiptType::Read) + else { + to_del.push(key); + continue; + }; + + if old_receipt.thread == new_receipt.thread { + if old_event == new_event { + return false; + } + to_del.push(key); + } + } + + for key in to_del { + self.readreceiptid_readreceipt.del(&key); + } + let count = self.services.globals.next_count().unwrap(); let latest_id = (room_id, count, user_id); self.readreceiptid_readreceipt.put(latest_id, Json(event)); + true } pub(super) fn readreceipts_since<'a>( @@ -86,12 +126,28 @@ impl Data { .ignore_err() } - pub(super) fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, pdu_count: u64) { + pub(super) async fn private_read_set( + &self, + room_id: &RoomId, + user_id: &UserId, + pdu_count: u64, + ) -> bool { let key = (room_id, user_id); - let next_count = self.services.globals.next_count().unwrap(); + if let Ok(current) = self + .roomuserid_privateread + .qry(&key) + .await + .deserialized::() + { + if current == pdu_count { + return false; + } + } + let next_count = self.services.globals.next_count().unwrap(); self.roomuserid_privateread.put(key, pdu_count); self.roomuserid_lastprivatereadupdate.put(key, next_count); + true } pub(super) async fn private_read_get_count( diff --git a/src/service/rooms/read_receipt/mod.rs b/src/service/rooms/read_receipt/mod.rs index 2815828fd..346120d8b 100644 --- a/src/service/rooms/read_receipt/mod.rs +++ b/src/service/rooms/read_receipt/mod.rs @@ -65,7 +65,10 @@ impl Service { room_id: &RoomId, event: ReceiptEvent, ) { - self.db.readreceipt_update(user_id, room_id, &event).await; + if !self.db.readreceipt_update(user_id, room_id, &event).await { + return; + } + self.services.sync.wake_all_joined(room_id).await; // update appservices let edu = EphemeralData::Receipt(event); @@ -93,7 +96,7 @@ impl Service { }); let (pdu_count, shortroomid) = try_join!(pdu_count, shortroomid)?; - let shorteventid = PduCount::Normal(pdu_count); + let shorteventid = PduCount::from_unsigned(pdu_count); let pdu_id: RawPduId = PduId { shortroomid, shorteventid }.into(); let pdu = self.services.timeline.get_pdu_from_id(&pdu_id).await?; @@ -101,8 +104,7 @@ impl Service { let user_id: OwnedUserId = user_id.to_owned(); let mut receipt = ruma::events::receipt::Receipt::default(); - // TODO: start storing the timestamp so we can return one - receipt.ts = None; + receipt.ts = Some(pdu.origin_server_ts()); receipt.thread = ruma::events::receipt::ReceiptThread::Unthreaded; let content: BTreeMap = BTreeMap::from_iter([( @@ -143,7 +145,9 @@ impl Service { event_id: &EventId, count: u64, ) { - self.db.private_read_set(room_id, user_id, count); + if !self.db.private_read_set(room_id, user_id, count).await { + return; + } // update appservices matching the user's namespace (MSC2409) let receipt_content = [( @@ -267,4 +271,54 @@ mod tests { assert!(users.contains_key(user_id!("@alice:example.org"))); assert!(users.contains_key(user_id!("@bob:example.org"))); } + + #[test] + fn pack_receipts_merges_threaded_and_private_receipts() { + let event_a: OwnedEventId = "$event_a:example.org".try_into().expect("valid event ID"); + let event_b: OwnedEventId = "$event_b:example.org".try_into().expect("valid event ID"); + + let mut public_threaded_receipt = Receipt::default(); + public_threaded_receipt.thread = ruma::events::receipt::ReceiptThread::Main; + + let r1_content = ReceiptEventContent::from_iter([( + event_a.clone(), + BTreeMap::from([( + ReceiptType::Read, + BTreeMap::from([( + user_id!("@alice:example.org").to_owned(), + public_threaded_receipt, + )]), + )]), + )]); + let r1: Raw = Raw::from_json( + serde_json::value::to_raw_value(&SyncEphemeralRoomEvent::new(r1_content)).unwrap(), + ); + + let mut private_receipt = Receipt::default(); + private_receipt.thread = ruma::events::receipt::ReceiptThread::Unthreaded; + let r2_content = ReceiptEventContent::from_iter([( + event_b.clone(), + BTreeMap::from([( + ReceiptType::ReadPrivate, + BTreeMap::from([(user_id!("@alice:example.org").to_owned(), private_receipt)]), + )]), + )]); + let r2: Raw = Raw::from_json( + serde_json::value::to_raw_value(&SyncEphemeralRoomEvent::new(r2_content)).unwrap(), + ); + + let packed = pack_receipts([r1, r2].into_iter()); + let packed: SyncEphemeralRoomEvent = + serde_json::from_str(packed.json().get()).expect("packed receipt is valid"); + + assert_eq!( + packed.content[&event_a][&ReceiptType::Read][user_id!("@alice:example.org")].thread, + ruma::events::receipt::ReceiptThread::Main + ); + assert_eq!( + packed.content[&event_b][&ReceiptType::ReadPrivate][user_id!("@alice:example.org")] + .thread, + ruma::events::receipt::ReceiptThread::Unthreaded + ); + } } diff --git a/src/service/rooms/short/mod.rs b/src/service/rooms/short/mod.rs index 53d70fe85..34953228c 100644 --- a/src/service/rooms/short/mod.rs +++ b/src/service/rooms/short/mod.rs @@ -1,4 +1,4 @@ -use std::{borrow::Borrow, fmt::Debug, mem::size_of_val, sync::Arc}; +use std::{borrow::Borrow, collections::HashMap, fmt::Debug, mem::size_of_val, sync::Arc}; pub use conduwuit::matrix::pdu::{ShortEventId, ShortId, ShortRoomId, ShortStateKey}; use conduwuit::{ @@ -8,10 +8,7 @@ use conduwuit::{ utils::{self, IterStream, ReadyExt}, }; use database::{Deserialized, Get, Map, Qry}; -use futures::{ - Stream, StreamExt, - stream::{self}, -}; +use futures::{Stream, StreamExt, stream}; use ruma::{EventId, OwnedEventId, RoomId, events::StateEventType}; use serde::Deserialize; @@ -75,14 +72,22 @@ impl Service { where I: Iterator + Clone + Debug + Send + 'a, { + let mut created: HashMap = HashMap::new(); event_ids .clone() .stream() .get(&self.db.eventid_shorteventid) .zip(event_ids.into_iter().stream()) - .map(|(result, event_id)| match result { + .map(move |(result, event_id)| match result { | Ok(ref short) => utils::u64_from_u8(short), - | Err(_) => self.create_shorteventid(event_id), + | Err(_) => + if let Some(&short) = created.get(event_id) { + short + } else { + let short = self.create_shorteventid(event_id); + created.insert(event_id.to_owned(), short); + short + }, }) } @@ -220,32 +225,24 @@ impl Service { .map(Deserialized::deserialized) } - /// Gets or creates a short state hash ID. The boolean indicates whether a - /// new short ID was created. - pub async fn get_or_create_shortstatehash( - &self, - state_hash: &[u8], - ) -> (ShortStateHash, bool) { - const BUFSIZE: usize = size_of::(); - - if let Ok(shortstatehash) = self - .db + /// Gets an existing short state hash ID without creating one. + pub async fn get_shortstatehash(&self, state_hash: &[u8]) -> Result { + self.db .statehash_shortstatehash .get(state_hash) .await .deserialized() - { - return (shortstatehash, true); - } + } - let shortstatehash = self.services.globals.next_count().unwrap(); + /// Publishes the mapping from state hash to short state hash after the + /// corresponding state diff has been written. + pub fn set_shortstatehash(&self, state_hash: &[u8], shortstatehash: ShortStateHash) { + const BUFSIZE: usize = size_of::(); debug_assert!(size_of_val(&shortstatehash) == BUFSIZE, "buffer requirement changed"); self.db .statehash_shortstatehash .raw_aput::(state_hash, shortstatehash); - - (shortstatehash, false) } /// Gets a short room ID. diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index 200e03f7f..a7c3eacea 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -170,47 +170,50 @@ impl Service { let state_hash = calculate_hash(state_ids_compressed.iter().map(|s| &s[..])); - let (shortstatehash, already_existed) = self - .services - .short - .get_or_create_shortstatehash(&state_hash) - .await; - - if !already_existed { - let states_parents = match previous_shortstatehash { - | Ok(p) => - self.services - .state_compressor - .load_shortstatehash_info(p) - .await?, - | _ => Vec::new(), - }; - - let (statediffnew, statediffremoved) = - if let Some(parent_stateinfo) = states_parents.last() { - let statediffnew: CompressedState = state_ids_compressed - .difference(&parent_stateinfo.full_state) - .copied() - .collect(); - - let statediffremoved: CompressedState = parent_stateinfo - .full_state - .difference(&state_ids_compressed) - .copied() - .collect(); - - (Arc::new(statediffnew), Arc::new(statediffremoved)) - } else { - (state_ids_compressed, Arc::new(CompressedState::new())) + let shortstatehash = + if let Ok(existing) = self.services.short.get_shortstatehash(&state_hash).await { + existing + } else { + let states_parents = match previous_shortstatehash { + | Ok(p) => + self.services + .state_compressor + .load_shortstatehash_info(p) + .await?, + | _ => Vec::new(), }; - self.services.state_compressor.save_state_from_diff( - shortstatehash, - statediffnew, - statediffremoved, - 1_000_000, // high number because no state will be based on this one - states_parents, - )?; - } + + let (statediffnew, statediffremoved) = + if let Some(parent_stateinfo) = states_parents.last() { + let statediffnew: CompressedState = state_ids_compressed + .difference(&parent_stateinfo.full_state) + .copied() + .collect(); + + let statediffremoved: CompressedState = parent_stateinfo + .full_state + .difference(&state_ids_compressed) + .copied() + .collect(); + + (Arc::new(statediffnew), Arc::new(statediffremoved)) + } else { + (state_ids_compressed, Arc::new(CompressedState::new())) + }; + + let new_shortstatehash = self.services.globals.next_count()?; + self.services.state_compressor.save_state_from_diff( + new_shortstatehash, + statediffnew, + statediffremoved, + 1_000_000, // high number because no state will be based on this one + states_parents, + )?; + self.services + .short + .set_shortstatehash(&state_hash, new_shortstatehash); + new_shortstatehash + }; self.db .shorteventid_shortstatehash @@ -264,14 +267,11 @@ impl Service { .compress_state_event(shortstatekey, &new_pdu.event_id) .await; - let replaces = states_parents - .last() - .map(|info| { - info.full_state - .iter() - .find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes())) - }) - .unwrap_or_default(); + let replaces = states_parents.last().map_or_default(|info| { + info.full_state + .iter() + .find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes())) + }); if Some(&new) == replaces { return Ok(previous_shortstatehash.expect("must exist")); @@ -420,7 +420,11 @@ impl Service { .ignore_err() } - pub async fn set_forward_extremities<'a, I>( + /// Replaces the forward extremity set whole-sale. + /// + /// This should only be done during room joins, where our only source of + /// extremities is the join itself. + pub async fn replace_forward_extremities<'a, I>( &'a self, room_id: &'a RoomId, event_ids: I, @@ -428,6 +432,15 @@ impl Service { ) where I: Iterator + Send + 'a, { + self.clear_forward_extremities(room_id).await; + + for event_id in event_ids { + let key = (room_id, event_id); + self.db.roomid_pduleaves.put_raw(key, []); + } + } + + pub async fn clear_forward_extremities(&self, room_id: &RoomId) { let prefix = (room_id, Interfix); self.db .roomid_pduleaves @@ -435,11 +448,18 @@ impl Service { .ignore_err() .ready_for_each(|key| self.db.roomid_pduleaves.remove(key)) .await; + } - for event_id in event_ids { - let key = (room_id, event_id); - self.db.roomid_pduleaves.put_raw(key, event_id); - } + /// Appends a forward extremity to the extremity tracker. + pub fn add_forward_extremity(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.db.roomid_pduleaves.put_raw(key, []); + } + + /// Removes a forward extremity from the extremity tracker. + pub fn remove_forward_extremity(&self, room_id: &RoomId, event_id: &EventId) { + let key = (room_id, event_id); + self.db.roomid_pduleaves.del(key); } /// This fetches auth events from the current state. diff --git a/src/service/rooms/state_accessor/user_can.rs b/src/service/rooms/state_accessor/user_can.rs index 4754935ee..2a6d52515 100644 --- a/src/service/rooms/state_accessor/user_can.rs +++ b/src/service/rooms/state_accessor/user_can.rs @@ -33,6 +33,16 @@ impl super::Service { return Err!(Request(Forbidden("Redacting m.room.create is not safe, forbidding."))); } + // Defense in depth, shouldn't be reachable + if redacting_event + .as_ref() + .is_ok_and(|pdu| pdu.room_id() != Some(room_id)) + { + return Err!(Request(Forbidden( + "Cannot redact an event that belongs to a different room." + ))); + } + if redacting_event .as_ref() .is_ok_and(|pdu| *pdu.kind() == TimelineEventType::RoomServerAcl) @@ -77,12 +87,20 @@ impl super::Service { room_id: &RoomId, event_id: &EventId, ) -> bool { - let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else { - return true; - }; - let currently_member = self.services.state_cache.is_joined(user_id, room_id).await; + let Ok(shortstatehash) = self.pdu_shortstatehash(event_id).await else { + // We haven't calculated the state at this event, so we can't + // properly history visibility check it. This happens for outliers + // and backfilled events. Since continuwuity is primarily targeting + // single-user/trusted deployments, an acceptable compromise for now + // is to ensure that the user is currently joined to the room. + // Federation fails closed here, but if that was replicated for the + // check used for client-server, nobody would be allowed to see + // events before their server started participating in the room. + return currently_member; + }; + let history_visibility = self .state_get_content(shortstatehash, &StateEventType::RoomHistoryVisibility, "") .await diff --git a/src/service/rooms/state_compressor/mod.rs b/src/service/rooms/state_compressor/mod.rs index ddd25eac1..a65057eea 100644 --- a/src/service/rooms/state_compressor/mod.rs +++ b/src/service/rooms/state_compressor/mod.rs @@ -18,7 +18,7 @@ use lru_cache::LruCache; use ruma::{EventId, RoomId}; use crate::{ - Dep, rooms, + Dep, globals, rooms, rooms::short::{ShortEventId, ShortId, ShortStateHash, ShortStateKey}, }; @@ -29,6 +29,7 @@ pub struct Service { } struct Services { + globals: Dep, short: Dep, state: Dep, } @@ -78,6 +79,7 @@ impl crate::Service for Service { shortstatehash_statediff: args.db["shortstatehash_statediff"].clone(), }, services: Services { + globals: args.depend::("globals"), short: args.depend::("rooms::short"), state: args.depend::("rooms::state"), }, @@ -368,17 +370,17 @@ impl Service { let state_hash = utils::calculate_hash(new_state_ids_compressed.iter().map(|bytes| &bytes[..])); - let (new_shortstatehash, already_existed) = self + let existing = self .services .short - .get_or_create_shortstatehash(&state_hash) - .await; + .get_shortstatehash(&state_hash) + .await + .ok(); - if Some(new_shortstatehash) == previous_shortstatehash { - return Ok(HashSetCompressStateEvent { - shortstatehash: new_shortstatehash, - ..Default::default() - }); + if let Some(shortstatehash) = existing + && Some(shortstatehash) == previous_shortstatehash + { + return Ok(HashSetCompressStateEvent { shortstatehash, ..Default::default() }); } let states_parents = if let Some(p) = previous_shortstatehash { @@ -405,7 +407,10 @@ impl Service { (new_state_ids_compressed, Arc::new(CompressedState::new())) }; - if !already_existed { + let new_shortstatehash = if let Some(existing) = existing { + existing + } else { + let new_shortstatehash = self.services.globals.next_count()?; self.save_state_from_diff( new_shortstatehash, statediffnew.clone(), @@ -413,7 +418,11 @@ impl Service { 2, // every state change is 2 event changes on average states_parents, )?; - } + self.services + .short + .set_shortstatehash(&state_hash, new_shortstatehash); + new_shortstatehash + }; Ok(HashSetCompressStateEvent { shortstatehash: new_shortstatehash, @@ -437,7 +446,10 @@ impl Service { err!(Database("Failed to find StateDiff from short {shortstatehash:?}: {e}")) })?; - let parent = utils::u64_from_bytes(&value[0..size_of::()]) + let parent_bytes = value + .get(0..size_of::()) + .ok_or_else(|| err!(Database("Truncated StateDiff for short {shortstatehash:?}")))?; + let parent = utils::u64_from_bytes(parent_bytes) .ok() .take_if(|parent| *parent != 0); @@ -472,10 +484,14 @@ impl Service { /// Stores a new state diff with a shortstatehash. fn save_statediff(&self, shortstatehash: ShortStateHash, diff: &StateDiff) { + const STRIDE: usize = size_of::(); + let mut value = Vec::::with_capacity( - 2_usize - .saturating_add(diff.added.len()) - .saturating_add(diff.removed.len()), + 1_usize + .saturating_add(usize::from(!diff.removed.is_empty())) + .saturating_add(diff.added.len().saturating_mul(2)) + .saturating_add(diff.removed.len().saturating_mul(2)) + .saturating_mul(STRIDE), ); let parent = diff.parent.unwrap_or(0_u64); diff --git a/src/service/rooms/summary/mod.rs b/src/service/rooms/summary/mod.rs index f2d56eb52..d8d8d96fb 100644 --- a/src/service/rooms/summary/mod.rs +++ b/src/service/rooms/summary/mod.rs @@ -1,4 +1,8 @@ -use std::{collections::HashSet, sync::Arc}; +use std::{ + collections::{BTreeSet, HashSet}, + pin::pin, + sync::Arc, +}; use conduwuit::{ Err, Event, Result, debug, info, @@ -10,18 +14,27 @@ use ruma::{ OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, ServerName, UInt, UserId, api::{ client::space::SpaceHierarchyRoomsChunk, - federation::space::{SpaceHierarchyParentSummary, get_hierarchy}, + error::ErrorKind, + federation::{ + event::get_stripped_state, + space::{SpaceHierarchyParentSummary, get_hierarchy}, + }, }, assign, events::{ - StateEventType, + AnyStrippedStateEvent, StateEventType, + room::member::MembershipState, space::child::{HierarchySpaceChildEvent, SpaceChildEventContent}, }, - room::{JoinRuleSummary, RestrictedSummary, RoomSummary, RoomType}, + room::{JoinRule, RoomSummary, RoomType}, serde::Raw, }; -use crate::{Dep, rooms, sending}; +use crate::{ + Dep, globals, + rooms::{self, membership::JoinConditionResult}, + sending, +}; pub struct Service { services: Services, @@ -29,7 +42,8 @@ pub struct Service { struct Services { event_handler: Dep, - metadata: Dep, + globals: Dep, + membership: Dep, sending: Dep, state: Dep, state_accessor: Dep, @@ -57,13 +71,21 @@ struct SpaceChild { via: Vec, } +#[derive(Default)] +#[non_exhaustive] +pub struct RoomStrippedState { + pub state: Vec>, + pub num_joined_members: Option, +} + impl crate::Service for Service { fn build(args: crate::Args<'_>) -> Result> { Ok(Arc::new(Self { services: Services { event_handler: args .depend::("rooms::event_handler"), - metadata: args.depend::("rooms::metadata"), + globals: args.depend::("globals"), + membership: args.depend::("rooms::membership"), sending: args.depend::("sending"), state: args.depend::("rooms::state"), state_accessor: args @@ -90,9 +112,14 @@ impl Service { if let Some(summary) = self.build_local_room_summary(room_id).await { // We have this room locally. + // Check if the room is visible to the querying user. + if !self.user_may_see_summary(querying_user, room_id).await { + return Ok(Accessibility::Inaccessible); + } + summary } else if let Some((SpaceHierarchyParentSummary { summary, .. }, _)) = - self.fetch_remote_summary(room_id, via, false).await? + self.fetch_remote_room_summary(room_id, via, false).await { // A via has this room. @@ -104,11 +131,6 @@ impl Service { } }; - // Check if the room is visible to the querying user. - if !self.user_may_see_summary(querying_user, &summary).await { - return Ok(Accessibility::Inaccessible); - } - Ok(Accessibility::Accessible(summary)) } @@ -124,10 +146,18 @@ impl Service { via: Option<&[OwnedServerName]>, suggested_only: bool, ) -> Result> { - let (mut summary, inaccessible_children) = { + let (summary, inaccessible_children) = { if let Some(summary) = self.build_local_room_summary(room_id).await { // We have this room locally. - let children_state = self.get_space_child_events(room_id, suggested_only).await; + if !self.user_may_see_summary(querying_user, room_id).await { + return Ok(Accessibility::Inaccessible); + } + + let children_state = if matches!(summary.room_type, Some(RoomType::Space)) { + self.get_space_child_events(room_id, suggested_only).await + } else { + vec![] + }; // All of the room's children are accessible to this server // (because we have the full room and its state), although @@ -138,8 +168,8 @@ impl Service { SpaceHierarchyParentSummary { summary, children_state, .. }, inaccessible_children, )) = self - .fetch_remote_summary(room_id, via, suggested_only) - .await? + .fetch_remote_room_summary(room_id, via, suggested_only) + .await { // A via has this room. @@ -151,18 +181,6 @@ impl Service { } }; - // Check if the room is visible to the querying user. - if !self - .user_may_see_summary(querying_user, &summary.summary) - .await - { - return Ok(Accessibility::Inaccessible); - } - - if !matches!(summary.summary.room_type.as_ref(), Some(RoomType::Space)) { - summary.children_state.clear(); - } - let mut children: Vec<_> = summary .children_state .iter() @@ -282,11 +300,12 @@ impl Service { summaries.push(summary.summary); inaccessible_children.extend(summary.inaccessible_children); - // Bail out if queue length exceeds 50 to keep cycles in the space - // graph from blowing up the traversal. If you actually have over - // fifty nested spaces, and you're looking at this function to - // figure out what the issue is, I suggest you reconsider some of - // the choices you made which led you to this point. + // Bail out if more than fifty rooms are queued to prevent a DOS + // when traversing incredibly large hierarchies. If you + // actually have over fifty nested rooms, and you're + // looking at this function to figure out what the issue + // is, I suggest you reconsider some of the choices you + // made which led you to this point. if queue.len() > 50 { return Err!(Request(TooLarge("Space hierarchy is unreasonably large"))); } @@ -312,7 +331,7 @@ impl Service { }; // Check if the server can see the root room's summary - if !self.server_may_see_summary(querying_server, &summary).await { + if !self.server_may_see_summary(querying_server, room_id).await { return Accessibility::Inaccessible; } @@ -331,7 +350,10 @@ impl Service { .broad_then(async |child| { let summary = { if let Some(summary) = self.build_local_room_summary(&child.state_key).await { - if self.server_may_see_summary(querying_server, &summary).await { + if self + .server_may_see_summary(querying_server, &child.state_key) + .await + { Accessibility::Accessible(summary) } else { Accessibility::Inaccessible @@ -439,20 +461,14 @@ impl Service { } /// Query remote servers for the summary of a room. - async fn fetch_remote_summary( + async fn fetch_remote_room_summary( &self, room_id: &RoomId, via: &[OwnedServerName], suggested_only: bool, - ) -> Result)>> { - if self.services.metadata.is_disabled(room_id).await { - return Err!(Request(Forbidden("This room is blocked by this server."))); - } - + ) -> Option<(SpaceHierarchyParentSummary, Vec)> { if via.is_empty() { - return Err!(Request(MissingParam( - "No servers were provided with which to query this room's summary." - ))); + return None; } info!(%room_id, ?via, "Asking for room summary over federation"); @@ -477,7 +493,7 @@ impl Service { } info!(%room_id, %server, "Got room summary"); - return Ok(Some((room, inaccessible_children))); + return Some((room, inaccessible_children)); }, | Err(err) => { info!(%room_id, %server, %err, "Server could not provide a summary for this room"); @@ -486,7 +502,7 @@ impl Service { } info!(%room_id, "No servers queried could provide a summary for this room"); - Ok(None) + None } /// Get the stripped m.space.child events of a room. @@ -536,54 +552,223 @@ impl Service { .await } + /// Prepares the stripped state of a local or remote room for a user. + pub async fn get_stripped_state_for_user( + &self, + querying_user: Option<&UserId>, + room_id: &RoomId, + via: &[OwnedServerName], + state: &BTreeSet, + num_joined_members: bool, + ) -> Accessibility<(OwnedServerName, RoomStrippedState)> { + if let Some(state) = self + .build_local_stripped_state(room_id, state, num_joined_members) + .await + { + if self.user_may_see_summary(querying_user, room_id).await { + Accessibility::Accessible((self.services.globals.server_name().to_owned(), state)) + } else { + Accessibility::Inaccessible + } + } else { + self.fetch_remote_stripped_state(room_id, via, state, num_joined_members) + .await + } + } + + /// Prepares the stripped state of a local room for a server. + pub async fn get_local_stripped_state_for_server( + &self, + querying_server: &ServerName, + room_id: &RoomId, + state: &BTreeSet, + num_joined_members: bool, + ) -> Accessibility { + if let Some(state) = self + .build_local_stripped_state(room_id, state, num_joined_members) + .await + { + if self.server_may_see_summary(querying_server, room_id).await { + Accessibility::Accessible(state) + } else { + Accessibility::Inaccessible + } + } else { + Accessibility::NotFound + } + } + + /// Build a local room's stripped state. Returns None if we don't have the + /// room. + async fn build_local_stripped_state( + &self, + room_id: &RoomId, + state: &BTreeSet, + num_joined_members: bool, + ) -> Option { + if !self + .services + .state_cache + .server_in_room(self.services.globals.server_name(), room_id) + .await + { + return None; + } + + let current_shortstatehash = self + .services + .state + .get_room_shortstatehash(room_id) + .await + .expect("room should have state"); + + let state = state + .iter() + .stream() + .broad_flat_map(|event_type| { + self.services + .state_accessor + .state_keys_with_ids::(current_shortstatehash, event_type) + }) + .broad_filter_map(async |(_, event_id)| { + self.services.timeline.get_pdu(&event_id).ok().await + }) + .ready_filter_map(|pdu| Some(pdu.into_format())) + .collect() + .await; + + let num_joined_members = if num_joined_members { + Some( + self.services + .state_cache + .room_joined_count(room_id) + .await + .expect("room should have a joined count") + .try_into() + .expect("joined count should fit into uint"), + ) + } else { + None + }; + + Some(RoomStrippedState { state, num_joined_members }) + } + + /// Ask remote servers for a room's stripped state. + async fn fetch_remote_stripped_state( + &self, + room_id: &RoomId, + via: &[OwnedServerName], + state: &BTreeSet, + num_joined_members: bool, + ) -> Accessibility<(OwnedServerName, RoomStrippedState)> { + if via.is_empty() { + return Accessibility::NotFound; + } + + let request = assign!(get_stripped_state::msc4560::Request::new(room_id.to_owned()), { + state: state.to_owned(), + num_joined_members + }); + + let mut responses = pin!(via.iter().stream().broad_then(async |server| { + match self + .services + .sending + .send_federation_request(server, request.clone()) + .await + { + | Ok(response) => Accessibility::Accessible((server.to_owned(), response)), + | Err(err) => match err.kind() { + | ErrorKind::Forbidden => Accessibility::Inaccessible, + | _ => Accessibility::NotFound, + }, + } + })); + + let mut got_inaccessible = false; + + while let Some(response) = responses.next().await { + match response { + | Accessibility::Accessible((server, response)) => { + // The via has the room. + return Accessibility::Accessible((server, RoomStrippedState { + state: response.state, + num_joined_members: response.num_joined_members, + })); + }, + | Accessibility::Inaccessible => { + // The via has the room and was able to determine that we + // can't access it. We don't stop + // checking in case it's malicious or wrong, + // but we do switch to returning M_FORBIDDEN instead of + // M_NOT_FOUND if no other via lets us + // see the room. + got_inaccessible = true; + continue; + }, + | Accessibility::NotFound => { + // The via doesn't have the room. + continue; + }, + } + } + + if got_inaccessible { + Accessibility::Inaccessible + } else { + Accessibility::NotFound + } + } + /// Determine if a user (possibly anonymous) may view a room summary. async fn user_may_see_summary( &self, querying_user: Option<&UserId>, - summary: &RoomSummary, + room_id: &RoomId, ) -> bool { // Anyone can view the summary of world-readable rooms. - if summary.world_readable { - return true; - } - - // If the user is joined or invited they may always view the summary. - if let Some(querying_user) = querying_user - && (self - .services - .state_cache - .is_joined(querying_user, &summary.room_id) - .await - || self - .services - .state_cache - .is_invited(querying_user, &summary.room_id) - .await) + if self + .services + .state_accessor + .is_world_readable(room_id) + .await { return true; } - // Otherwise, visibility depends on the join rule. - match (&summary.join_rule, querying_user) { - // Anyone can view summaries for `public`, `knock`, and `knock_restricted` rooms. - | ( - JoinRuleSummary::Public - | JoinRuleSummary::Knock - | JoinRuleSummary::KnockRestricted(_), - _, - ) => true, + // If the user is joined or invited they may always view the summary. + if let Some(querying_user) = querying_user { + let membership = self + .services + .state_accessor + .get_member(room_id, querying_user) + .await + .ok() + .map_or(MembershipState::Leave, |content| content.membership); - // The user may be able to view the summary for a `restricted` room, even if they - // aren't invited, provided they're in one of the allowed rooms. - | ( - JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids, .. }), - Some(querying_user), - ) => + if matches!(membership, MembershipState::Join | MembershipState::Invite) { + return true; + } + } + + // Otherwise, visibility depends on the join rule. + let join_rule = self.services.state_accessor.get_join_rules(room_id).await; + + match (join_rule, querying_user) { + // Anyone can view summaries for `public`, `knock`, and + // `knock_restricted` rooms. + | (JoinRule::Public | JoinRule::Knock | JoinRule::KnockRestricted(_), _) => true, + + // The user may be able to view the summary for a `restricted` room, + // even if they aren't invited, provided they fulfill the join + // rules. + | (JoinRule::Restricted(conditions), Some(querying_user)) => self.services - .state_cache - .rooms_joined(querying_user) - .ready_any(|room_id| allowed_room_ids.contains(&room_id)) - .await, + .membership + .evaluate_join_conditions(room_id, querying_user.into(), &conditions) + .await + == JoinConditionResult::Satisfied, // In all other cases, the user may not view the summary. | _ => false, @@ -594,13 +779,13 @@ impl Service { async fn server_may_see_summary( &self, querying_server: &ServerName, - summary: &RoomSummary, + room_id: &RoomId, ) -> bool { // Servers may not see summaries of rooms they're ACLed from. if self .services .event_handler - .acl_check(querying_server, &summary.room_id) + .acl_check(querying_server, room_id) .await .is_err() { @@ -608,37 +793,33 @@ impl Service { } // Servers may always see summaries if any of their users are - // participating in the room. It's the requesting server's job to - // restrict visibility on a per-user basis. + // participating in the room. The server really should have generated a + // summary itself, instead of asking us for it, but we might as + // well save ourselves a bit of time checking the other rules. if self .services .state_cache - .server_in_room(querying_server, &summary.room_id) + .server_in_room(querying_server, room_id) .await { return true; } - // For restricted rooms, federation responses must include the summary - // when a user on the querying server can satisfy one of the join - // conditions. - if let JoinRuleSummary::Restricted(RestrictedSummary { allowed_room_ids, .. }) = - &summary.join_rule - { - for room_id in allowed_room_ids { - if self - .services - .state_cache - .server_in_room(querying_server, room_id) - .await - { - return true; - } - } + let join_rule = self.services.state_accessor.get_join_rules(room_id).await; + + // Servers may see summaries in restricted rooms if they satisfy the + // join conditions. + if let JoinRule::Restricted(conditions) = join_rule { + return self + .services + .membership + .evaluate_join_conditions(room_id, querying_server.into(), &conditions) + .await + == JoinConditionResult::Satisfied; } // If the server isn't in the room, the same visibility rules apply as // for anonymous summary requests. - self.user_may_see_summary(None, summary).await + self.user_may_see_summary(None, room_id).await } } diff --git a/src/service/rooms/threads/mod.rs b/src/service/rooms/threads/mod.rs index a29ca5511..4274933aa 100644 --- a/src/service/rooms/threads/mod.rs +++ b/src/service/rooms/threads/mod.rs @@ -3,7 +3,10 @@ use std::{collections::BTreeMap, sync::Arc}; use conduwuit::result::LogErr; use conduwuit_core::{ Event, Result, err, - matrix::pdu::{PduCount, PduEvent, PduId, RawPduId}, + matrix::{ + event::RelationTypeEqual, + pdu::{PduCount, PduEvent, PduId, RawPduId}, + }, utils::{ ReadyExt, stream::{TryIgnore, WidebandExt}, @@ -12,9 +15,14 @@ use conduwuit_core::{ use conduwuit_database::{Deserialized, Map}; use futures::{Stream, StreamExt}; use ruma::{ - CanonicalJsonValue, EventId, OwnedUserId, RoomId, UserId, - api::client::threads::get_threads::v1::IncludeThreads, events::relation::BundledThread, - serde::Raw, uint, + CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedUserId, RoomId, UInt, UserId, + api::{Direction, client::threads::get_threads::v1::IncludeThreads}, + events::{ + AnySyncMessageLikeEvent, AnySyncTimelineEvent, + relation::{BundledThread, RelationType}, + }, + serde::Raw, + uint, }; use serde_json::json; @@ -27,6 +35,7 @@ pub struct Service { struct Services { short: Dep, + pdu_metadata: Dep, timeline: Dep, } @@ -42,6 +51,7 @@ impl crate::Service for Service { }, services: Services { short: args.depend::("rooms::short"), + pdu_metadata: args.depend::("rooms::pdu_metadata"), timeline: args.depend::("rooms::timeline"), }, })) @@ -51,6 +61,86 @@ impl crate::Service for Service { } impl Service { + /// Serializes an event for the `latest_event` of a thread's aggregation, + /// stripping `unsigned` as we don't want to send e.g. txnid to clients. + fn latest_event(event: &E) -> Raw + where + E: Event, + { + let mut latest_pdu = event.clone().into_pdu(); + latest_pdu.unsigned = None; + latest_pdu + .into_format::>() + .cast_unchecked() + } + + fn set_thread(unsigned: &mut CanonicalJsonObject, thread: BundledThread) { + let content = serde_json::to_value(thread).expect("to_value always works"); + unsigned.insert( + "m.relations".to_owned(), + json!({ "m.thread": content }) + .try_into() + .expect("thread is valid json"), + ); + } + + /// Remove `event` from the aggregation of the thread matching + /// `root_event_id` + pub async fn remove_from_thread(&self, root_event_id: &EventId, event: &E) -> Result + where + E: Event + Send + Sync, + { + let Ok(root_id) = self.services.timeline.get_pdu_id(root_event_id).await else { + return Ok(()); + }; + + let mut root_pdu_json = self + .services + .timeline + .get_pdu_json_from_id(&root_id) + .await + .map_err(|e| err!(Database("Thread root pdu not found: {e:?}")))?; + + let Some(CanonicalJsonValue::Object(unsigned)) = root_pdu_json.get_mut("unsigned") else { + return Ok(()); + }; + + let thread = self + .services + .pdu_metadata + .get_relations( + event.sender(), + &event.room_id_or_hash(), + root_event_id, + PduCount::max(), + usize::MAX, + 0, + Direction::Backward, + |pdu| RelationType::Thread.relation_type_equal(pdu), + ) + .await; + + match thread.first() { + | Some((_, latest)) => Self::set_thread( + unsigned, + BundledThread::new( + Self::latest_event(latest), + thread.len().try_into().unwrap_or(UInt::MAX), + true, + ), + ), + | None => { + // No events are left in the thread, or the root is backfilled + unsigned.remove("m.relations"); + }, + } + + self.services + .timeline + .replace_pdu(&root_id, &root_pdu_json) + .await + } + pub async fn add_to_thread(&self, root_event_id: &EventId, event: &E) -> Result where E: Event + Send + Sync, @@ -78,11 +168,20 @@ impl Service { .await .map_err(|e| err!(Request(InvalidParam("Thread root pdu not found: {e:?}"))))?; - if let CanonicalJsonValue::Object(unsigned) = root_pdu_json - .entry("unsigned".to_owned()) - .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default())) + // get_relations doesn't support backfilled targets, so redactions + // couldn't update the aggregation of a backfilled root + // + // TODO: Support backfilled threads. This needs + // `src/service/rooms/pdu_metadata/mod.rs`'s + // (TODO: Relations with backfilled pdus) to be implemented, + // and then this check can be removed. + if matches!(root_id.pdu_count(), PduCount::Normal(_)) + && let CanonicalJsonValue::Object(unsigned) = root_pdu_json + .entry("unsigned".to_owned()) + .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default())) { - if let Some(mut relations) = unsigned + let latest_event = Self::latest_event(event); + let thread = match unsigned .get("m.relations") .and_then(|r| r.as_object()) .and_then(|r| r.get("m.thread")) @@ -90,34 +189,16 @@ impl Service { serde_json::from_value::(relations.clone().into()).ok() }) { // Thread already existed - relations.count = relations.count.saturating_add(uint!(1)); - relations.latest_event = Raw::from_json(event.content().to_owned()); - - let content = serde_json::to_value(relations).expect("to_value always works"); - - unsigned.insert( - "m.relations".to_owned(), - json!({ "m.thread": content }) - .try_into() - .expect("thread is valid json"), - ); - } else { + | Some(mut thread) => { + thread.count = thread.count.saturating_add(uint!(1)); + thread.latest_event = latest_event; + thread + }, // New thread - let relations = BundledThread::new( - Raw::from_json(event.content().to_owned()), - uint!(1), - true, - ); + | None => BundledThread::new(latest_event, uint!(1), true), + }; - let content = serde_json::to_value(relations).expect("to_value always works"); - - unsigned.insert( - "m.relations".to_owned(), - json!({ "m.thread": content }) - .try_into() - .expect("thread is valid json"), - ); - } + Self::set_thread(unsigned, thread); self.services .timeline diff --git a/src/service/rooms/timeline/append.rs b/src/service/rooms/timeline/append.rs index 5f09c4638..887dca516 100644 --- a/src/service/rooms/timeline/append.rs +++ b/src/service/rooms/timeline/append.rs @@ -1,17 +1,13 @@ use std::{ - borrow::Borrow, collections::{BTreeMap, HashMap, HashSet, VecDeque}, iter::once, - ops::Not, sync::Arc, - time::Instant, }; use conduwuit::{ - Err, Result, debug, debug_warn, + Result, debug, debug_warn, matrix::{Event, PduEvent}, pdu::{Count, ShortRoomId}, - trace, utils::{ IterStream, TryFutureExtExt, mutex_map::Guard, @@ -20,15 +16,15 @@ use conduwuit::{ warn, }; use conduwuit_core::{ - err, error, + error, matrix::pdu::{PduCount, PduId, RawPduId, sticky}, result::LogErr, utils::{self, stream::TryIgnore}, }; use futures::{FutureExt, StreamExt, TryFutureExt, pin_mut}; use ruma::{ - CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, OwnedServerName, - RoomId, RoomVersionId, ServerName, UserId, + CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, + RoomVersionId, ServerName, UserId, events::{ AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType, push_rules::PushRulesEvent, @@ -94,29 +90,13 @@ impl super::Service { // We do this BEFORE setting the extremities so that there's never a // point in time where we have fresh extremities referencing stale // state. - let extremities = self - .progress_state_and_extremities( - pdu, - room_version_rules, - state_before.clone(), - self.services - .state - .get_forward_extremities(&room_id) - .collect() - .await, - state_lock, - ) - .await?; + if pdu.state_key().is_some() { + debug!("Event is a state-event. Deriving new room state"); + self.derive_new_state(pdu, &room_id, room_version_rules, state_before, state_lock) + .await?; + } - let pdu_id = self - .append_pdu( - pdu, - pdu_json, - extremities.iter().map(Borrow::borrow), - state_lock, - &room_id, - ) - .await?; + let pdu_id = self.append_pdu(pdu, pdu_json, &room_id).await; // Process admin commands for federation events if *pdu.kind() == TimelineEventType::RoomMessage { @@ -156,105 +136,96 @@ impl super::Service { } /// Derives new room state from the incoming event and filters forward - /// extremities accordingly. Does not set forward extremities. + /// extremities accordingly. /// /// Only call this function if the incoming PDU is not soft-failed or /// rejected. - async fn progress_state_and_extremities( - &self, - incoming_pdu: &PduEvent, - room_version_rules: &RoomVersionRules, - state_before: HashMap, - current_extremities: Vec, - state_lock: &Guard, - ) -> Result> { - if incoming_pdu.state_key().is_some() { - debug!("Event is a state-event. Deriving new room state"); - self.derive_new_state(incoming_pdu, room_version_rules, state_before, state_lock) - .await?; - } - - let start = Instant::now(); - trace!("Calculating extremities"); - // Start with the current extremity set, to avoid dropping unreferenced - // events. - let mut new_extremities: HashSet = - current_extremities.into_iter().collect(); - // Add the incoming event - new_extremities.insert(incoming_pdu.event_id().to_owned()); - // Remove any extremities that have since been referenced but not - // removed(?) - new_extremities = new_extremities - .into_iter() - .stream() - .broad_filter_map(|extremity| async { - self.services - .pdu_metadata - .is_event_referenced(&incoming_pdu.room_id_or_hash(), &extremity) - .await - .not() - .then_some(extremity) - }) - .collect() - .await; - - // Also iteratively walk prev events to ensure we drop any ancestors - // which are referenced regardless of soft-fail or rejection status. - // Soft-failed events and rejected events are not added as forward - // extremities, and as such do not remove their own prevs from the - // extremity set. This can lead to a situation where extremities build - // up because there's lots of soft-fails in the room, ultimately - // resulting in excessive cross-state boundary dummy events being - // created to squash the references. By walking the prevs until we stop - // reaching soft-fails, we can ensure that we properly prune all events - // which have actually been referenced, regardless of their soft-fail - // or rejection status. - let mut ancestors_todo: VecDeque = - VecDeque::from_iter(incoming_pdu.prev_events.clone()); - let room_id = incoming_pdu.room_id_or_hash(); - while let Some(prev_event_id) = ancestors_todo.pop_front() { - new_extremities.remove(&prev_event_id); + pub async fn progress_extremities(&self, incoming_pdu: &PduEvent) -> Result<()> { + // Add this PDU to the list of extremities (unreferenced events). + // Note that we add it *again* as a no-op in append_pdu. This is done + // now so that there's never a point in time where we have zero forward + // extremities. + let effective_room_id = incoming_pdu.room_id_or_hash(); + if !self + .services + .pdu_metadata + .is_event_referenced(&effective_room_id, incoming_pdu.event_id()) + .await + { self.services - .pdu_metadata - .mark_as_referenced(&room_id, once(prev_event_id.as_ref())); + .state + .add_forward_extremity(&incoming_pdu.room_id_or_hash(), incoming_pdu.event_id()); + } + let Some(room_id) = incoming_pdu.room_id() else { + // If there's no room ID, this is a v12+ create event, which never + // has any predecessors, and consequently will be the + // only forward extremity. + return Ok(()); + }; + + // Walk backwards from this event to find any rejected or soft-failed + // events. Discovering these events may discover implicitly + // referenced extremities that we can now remove. Doing the walk + // from the prev events also means they will all automatically be + // removed from the extremity set. + let mut ancestors_todo = VecDeque::from_iter(incoming_pdu.prev_events.clone()); + while let Some(prev_event_id) = ancestors_todo.pop_front() { + assert_ne!( + incoming_pdu.event_id, prev_event_id, + "Current event appeared in extremity purge path (cycle)" + ); + // This event is known to be referenced, so we can remove it. + self.services + .state + .remove_forward_extremity(room_id, &prev_event_id); let Ok(prev_event) = self.get_pdu(&prev_event_id).await else { + // If we don't have this PDU, we can't walk its prev events. continue; }; - // Only retain prevs that we have, which are themselves not - // referenced AND soft-failed/rejected/outlier. + // Now we collect all the prev events of this predecessor and filter + // for ones that we 1. know, 2. are not backfilled, and 3. have + // rejected/soft-failed. + // Additionally, drop any events that were referenced late. let outlier_prevs = prev_event .prev_events() .map(ToOwned::to_owned) .stream() .broad_filter_map(|prev_id| async { - let (exists, referenced, is_outlier, is_soft_failed, is_rejected) = tokio::join!( + let (exists, count, is_accepted, is_referenced) = tokio::join!( self.pdu_exists(&prev_id), + self.get_pdu_count(&prev_id) + .unwrap_or(PduCount::Backfilled(i64::MIN)), + self.services.pdu_metadata.is_event_accepted(&prev_id), self.services .pdu_metadata - .is_event_referenced(&room_id, &prev_id), - self.db.outlier_pdu_exists(&prev_id).is_ok(), - self.services.pdu_metadata.is_event_soft_failed(&prev_id), - self.services.pdu_metadata.is_event_rejected(&prev_id) + .is_event_referenced(room_id, &prev_id) ); - (exists && !referenced && (is_outlier || is_soft_failed || is_rejected)) - .then_some(prev_id) + let is_backfilled = matches!(count, PduCount::Backfilled(_)); + if is_referenced { + self.services + .state + .remove_forward_extremity(room_id, &prev_id); + } else { + // If we got here, that means there's now at least an + // indirect reference to the event. + self.services + .pdu_metadata + .mark_as_referenced(room_id, &prev_id); + } + if is_referenced || !exists || !is_accepted || is_backfilled { + return None; + } + Some(prev_id) }) .collect::>() .await; + // We then add them to the queue to repeat the process. + // Eventually, we might end up walking back far enough to discover + // an accepted event that was added as a forward extremity, which + // means (since we can reach it) we can now remove it. ancestors_todo.extend(outlier_prevs); } - - debug!( - "Retained {} extremities against {} prev_events in {:?}", - new_extremities.len(), - incoming_pdu.prev_events().count(), - start.elapsed(), - ); - if new_extremities.is_empty() { - Err!("Resolved extremity set was empty after processing incoming event") - } else { - Ok(new_extremities.into_iter().collect()) - } + Ok(()) } /// Derives a new room state by adding the incoming PDU to the state before @@ -267,11 +238,11 @@ impl super::Service { async fn derive_new_state( &self, incoming_pdu: &PduEvent, + room_id: &RoomId, room_version_rules: &RoomVersionRules, state_before: HashMap, state_lock: &Guard, ) -> Result { - let room_id = incoming_pdu.room_id_or_hash(); // We also add state after incoming event to the fork states let mut state_at_incoming_event = state_before; let shortstatekey = self @@ -290,19 +261,19 @@ impl super::Service { let new_room_state = self .services .event_handler - .resolve_state(&room_id, room_version_rules, state_at_incoming_event) + .resolve_state(room_id, room_version_rules, state_at_incoming_event) .await?; debug!("Forcing new room state"); let HashSetCompressStateEvent { shortstatehash, added, removed } = self .services .state_compressor - .save_state(&room_id, new_room_state) + .save_state(room_id, new_room_state) .await?; self.services .state - .force_state(&room_id, shortstatehash, added, removed, state_lock) + .force_state(room_id, shortstatehash, added, removed, state_lock) .await } @@ -341,23 +312,18 @@ impl super::Service { ); } - /// Creates a new persisted data unit and adds it to a room. + /// Creates a new persistent data unit and adds it to a room. /// /// By this point the incoming event should be fully authenticated, no auth /// happens in `append_pdu`. /// /// Returns pdu id - pub async fn append_pdu<'a, Leaves>( - &'a self, - pdu: &'a PduEvent, + pub async fn append_pdu( + &self, + pdu: &PduEvent, mut pdu_json: CanonicalJsonObject, - leaves: Leaves, - state_lock: &'a RoomMutexGuard, - room_id: &'a RoomId, - ) -> Result - where - Leaves: Iterator + Send + 'a, - { + room_id: &RoomId, + ) -> RawPduId { // Coalesce database writes for the remainder of this scope. let _cork = self.db.db.cork_and_flush(); @@ -366,30 +332,14 @@ impl super::Service { .short .get_shortroomid(room_id) .await - .map_err(|_| err!(Database("Room does not exist")))?; + .expect("room ID must have a short room ID"); // Make unsigned fields correct. This is not properly documented in the // spec, but state events need to have previous content in the // unsigned field, so clients can easily interpret things like // membership changes - - // TODO: This needs to be refactored to add this information on the fly. - // Because the prev content becomes part of the unsigned object in the - // PDU, we unintentionally leak redacted or hidden content to local - // users. See: https://forgejo.ellis.link/continuwuation/continuwuity/issues/1103 self.populate_unsigned(pdu, &mut pdu_json).await; - // We must keep track of all events that have been referenced. - self.services - .pdu_metadata - .mark_as_referenced(room_id, pdu.prev_events().map(AsRef::as_ref)); - - trace!("setting forward extremities"); - self.services - .state - .set_forward_extremities(room_id, leaves, state_lock) - .await; - let insert_lock = self.mutex_insert.lock(room_id).await; let count1 = self.services.globals.next_count().unwrap(); @@ -399,8 +349,11 @@ impl super::Service { // Insert pdu self.db - .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2) + .append_pdu(&pdu_id, pdu, room_id, &pdu_json, count2, pdu.origin_server_ts()) .await; + self.progress_extremities(pdu) + .await + .expect("progressing extremities should never fail"); drop(insert_lock); @@ -432,7 +385,7 @@ impl super::Service { self.send_to_interested_appservices(pdu, &pdu_id, room_id) .await; - Ok(pdu_id) + pdu_id } /// Notifies local users of the incoming event with a power levels context. @@ -638,9 +591,7 @@ impl super::Service { room_id: &RoomId, ) -> Option { let server = target_user_id.server_name(); - if !self.services.config.allow_sticky_events - || self.services.globals.server_is_ours(server) - { + if self.services.globals.server_is_ours(server) { return None; } @@ -809,7 +760,6 @@ impl super::Service { .services .appservice .read() - .await .values() .map(ToOwned::to_owned) // TODO: is this to_owned expensive? .collect::>(); diff --git a/src/service/rooms/timeline/backfill.rs b/src/service/rooms/timeline/backfill.rs index ece996f6e..ff78e9ff9 100644 --- a/src/service/rooms/timeline/backfill.rs +++ b/src/service/rooms/timeline/backfill.rs @@ -225,16 +225,10 @@ impl super::Service { .into(); // Insert pdu - self.db.prepend_backfill_pdu(&pdu_id, &event_id, &value); + self.db + .prepend_backfill_pdu(&pdu_id, &event_id, &value, pdu.origin_server_ts()); drop(insert_lock); - - // Backfilled events skip append_pdu, so this is the only place their - // prev_events can be marked as referenced. See issue #2115. - self.services - .pdu_metadata - .mark_as_referenced(&room_id, pdu.prev_events().map(AsRef::as_ref)); - if pdu.kind == TimelineEventType::RoomMessage { let content: ExtractBody = pdu.get_content()?; if let Some(body) = content.body { diff --git a/src/service/rooms/timeline/build.rs b/src/service/rooms/timeline/build.rs index 6e0a7282c..ef46d245d 100644 --- a/src/service/rooms/timeline/build.rs +++ b/src/service/rooms/timeline/build.rs @@ -1,4 +1,4 @@ -use std::{collections::HashSet, iter::once}; +use std::collections::HashSet; use conduwuit::trace; use conduwuit_core::{ @@ -8,7 +8,7 @@ use conduwuit_core::{ }; use futures::{FutureExt, StreamExt}; use ruma::{ - EventId, OwnedEventId, OwnedServerName, RoomId, UserId, + OwnedEventId, OwnedServerName, RoomId, UserId, events::{ TimelineEventType, room::{ @@ -111,34 +111,11 @@ impl super::Service { // because append_pdu can't fail. trace!("Appending {} state for room {room_id}", pdu.event_id()); let statehashid = self.services.state.append_to_state(&pdu, &room_id).await?; + self.progress_extremities(&pdu).await?; trace!("State hash ID for {room_id}: {statehashid:?}"); - // prev_events is capped at the room version's limit, so this PDU does - // not necessarily reference every extremity. Any it did not reference - // is still a head of the DAG and has to be kept. - let prev_events: HashSet<&EventId> = pdu.prev_events().collect(); - let unreferenced: Vec = self - .services - .state - .get_forward_extremities(&room_id) - .ready_filter(|extremity| !prev_events.contains(&**extremity)) - .collect() - .await; - trace!("Generating raw ID for PDU {}", pdu.event_id()); - let pdu_id = self - .append_pdu( - &pdu, - pdu_json, - unreferenced - .iter() - .map(AsRef::as_ref) - .chain(once(pdu.event_id())), - state_lock, - &room_id, - ) - .boxed() - .await?; + let pdu_id = self.append_pdu(&pdu, pdu_json, &room_id).boxed().await; // Process admin commands for locally sent events if *pdu.kind() == TimelineEventType::RoomMessage { diff --git a/src/service/rooms/timeline/create.rs b/src/service/rooms/timeline/create.rs index 2f33db721..daf99fac0 100644 --- a/src/service/rooms/timeline/create.rs +++ b/src/service/rooms/timeline/create.rs @@ -54,7 +54,7 @@ pub fn pdu_fits(owned_obj: &CanonicalJsonObject) -> bool { } // Now check the full PDU size match serde_json::to_string(owned_obj) { - | Ok(s) => s.len() <= 65535, + | Ok(s) => s.len() <= 65536, | Err(_) => false, } } @@ -193,7 +193,8 @@ impl super::Service { let redacts = match redacts { // If this isn't a real redaction event, there's no redacts field. | _ if event_type != TimelineEventType::RoomRedaction || state_key.is_some() => None, - // If the redaction is itself in the event content, we don't set the top-level field. + // If the redaction is itself in the event content, we don't set the + // top-level field. | Some(_) if room_version_rules.redaction.content_field_redacts => None, // Otherwise, we do if it's present | other => other, @@ -255,15 +256,10 @@ impl super::Service { | _ => create_pdu.as_ref().unwrap().as_pdu(), }; - let auth_check = state_res::auth_check( - &room_version_rules, - &pdu, - None, // TODO: third_party_invite - auth_fetch, - create_event, - ) - .await - .map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?; + let auth_check = + state_res::auth_check(&room_version_rules, &pdu, auth_fetch, create_event) + .await + .map_err(|e| err!(Request(Forbidden(warn!("Auth check failed: {e:?}")))))?; if !auth_check { return Err!(Request(Forbidden("Event is not authorized."))); @@ -309,7 +305,7 @@ impl super::Service { { return match e { | Error::SignatureJson(ruma::signatures::JsonError::PduTooLarge) => { - Err!(Request(TooLarge("Message/PDU is too long (exceeds 65535 bytes)"))) + Err!(Request(TooLarge("Message/PDU is too long (exceeds 65536 bytes)"))) }, | _ => Err!(Request(Unknown(warn!("Signing event failed: {e}")))), }; @@ -334,9 +330,9 @@ impl super::Service { pdu_json .insert("event_id".into(), CanonicalJsonValue::String(pdu.event_id.clone().into())); // Verify that the *full* PDU isn't over 64KiB. - if !pdu_fits(&pdu_json.clone()) { + if !pdu_fits(&pdu_json) { // feckin huge PDU mate - return Err!(Request(TooLarge("Message/PDU is too long (exceeds 65535 bytes)"))); + return Err!(Request(TooLarge("Message/PDU is too long (exceeds 65536 bytes)"))); } // Check with the policy server diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index 560bbae84..f0184533b 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -3,11 +3,20 @@ use std::sync::Arc; use conduwuit::{ Err, PduCount, PduEvent, Result, at, err, result::NotFound, - utils::{self, stream::TryReadyExt}, + utils::{ + self, + stream::{ReadyExt, TryReadyExt}, + }, }; use database::{Database, Deserialized, Json, KeyVal, Map}; -use futures::{FutureExt, Stream, TryFutureExt, TryStreamExt, future::select_ok, pin_mut}; -use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, api::Direction}; +use futures::{ + FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::select_ok, pin_mut, +}; +use ruma::{ + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedUserId, RoomId, api::Direction, +}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue as RawJsonValue; use super::{PduId, RawPduId}; use crate::{Dep, rooms, rooms::short::ShortRoomId}; @@ -16,7 +25,9 @@ pub(super) struct Data { eventid_outlierpdu: Arc, eventid_pduid: Arc, pduid_pdu: Arc, + pduid_unredactedcontent: Arc, roomid_lasttimelinecount: Arc, + roomts_pduid: Arc, userroomid_highlightcount: Arc, userroomid_notificationcount: Arc, pub(super) db: Arc, @@ -29,6 +40,12 @@ struct Services { pub type PdusIterItem = (PduCount, PduEvent); +#[derive(Deserialize, Serialize)] +pub(super) struct UnredactedContent { + pub(super) created: u64, + pub(super) content: Box, +} + impl Data { pub(super) fn new(args: &crate::Args<'_>) -> Self { let db = &args.db; @@ -36,7 +53,9 @@ impl Data { eventid_outlierpdu: db["eventid_outlierpdu"].clone(), eventid_pduid: db["eventid_pduid"].clone(), pduid_pdu: db["pduid_pdu"].clone(), + pduid_unredactedcontent: db["pduid_unredactedcontent"].clone(), roomid_lasttimelinecount: db["roomid_lasttimelinecount"].clone(), + roomts_pduid: db["roomts_pduid"].clone(), userroomid_highlightcount: db["userroomid_highlightcount"].clone(), userroomid_notificationcount: db["userroomid_notificationcount"].clone(), db: args.db.clone(), @@ -198,10 +217,12 @@ impl Data { room_id: &RoomId, json: &CanonicalJsonObject, count: PduCount, + index_ts: MilliSecondsSinceUnixEpoch, ) { debug_assert!(matches!(count, PduCount::Normal(_)), "PduCount not Normal"); self.pduid_pdu.raw_put(pdu_id, Json(json)); + self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []); self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id); self.eventid_outlierpdu.remove(pdu.event_id.as_bytes()); self.roomid_lasttimelinecount @@ -213,8 +234,10 @@ impl Data { pdu_id: &RawPduId, event_id: &EventId, json: &CanonicalJsonObject, + index_ts: MilliSecondsSinceUnixEpoch, ) { self.pduid_pdu.raw_put(pdu_id, Json(json)); + self.roomts_pduid.insert(&roomts_key(pdu_id, index_ts), []); self.eventid_pduid.insert(event_id, pdu_id); self.eventid_outlierpdu.remove(event_id); } @@ -234,6 +257,44 @@ impl Data { Ok(()) } + pub(super) fn save_unredacted_content(&self, pdu_id: &RawPduId, content: &RawJsonValue) { + let entry = UnredactedContent { + created: utils::millis_since_unix_epoch(), + content: content.to_owned(), + }; + + self.pduid_unredactedcontent.raw_put(pdu_id, Json(&entry)); + } + + pub(super) async fn get_unredacted_content( + &self, + pdu_id: &RawPduId, + ) -> Result { + self.pduid_unredactedcontent + .get(pdu_id) + .await + .deserialized() + } + + pub(super) async fn purge_unredacted_content(&self, cutoff: u64) -> usize { + let expired: Vec<_> = self + .pduid_unredactedcontent + .raw_stream() + .ready_filter_map(Result::ok) + .ready_filter_map(|(key, val)| { + let entry: UnredactedContent = serde_json::from_slice(val).ok()?; + (entry.created < cutoff).then(|| key.to_vec()) + }) + .collect() + .await; + + for key in &expired { + self.pduid_unredactedcontent.remove(key); + } + + expired.len() + } + /// Returns an iterator over all events and their tokens in a room that /// happened before the event with id `until` in reverse-chronological /// order. @@ -269,6 +330,49 @@ impl Data { .try_flatten_stream() } + pub(super) fn pdus_by_timestamp<'a>( + &'a self, + room_id: &'a RoomId, + timestamp: MilliSecondsSinceUnixEpoch, + dir: Direction, + ) -> impl Stream> + Send + 'a { + self.services + .short + .get_shortroomid(room_id) + .map_err(move |e| err!(Request(NotFound("Room {room_id:?} not found: {e:?}")))) + .map_ok(move |shortroomid| { + let seek = |shorteventid| { + roomts_key(&PduId { shortroomid, shorteventid }.into(), timestamp) + }; + let keys = match dir { + | Direction::Forward => self + .roomts_pduid + .raw_keys_from(&seek(PduCount::min())) + .left_stream(), + | Direction::Backward => self + .roomts_pduid + .rev_raw_keys_from(&seek(PduCount::max())) + .right_stream(), + }; + + keys.ready_try_take_while(move |key| { + Ok(key.starts_with(&shortroomid.to_be_bytes())) + }) + .map_ok(roomts_key_to_pdu_id) + .and_then(async move |pdu_id| { + Ok((pdu_id.pdu_count(), self.get_pdu_from_id(&pdu_id).await?)) + }) + }) + .try_flatten_stream() + } + + pub(super) async fn timestamp_index_ready(&self) -> bool { + self.db["global"] + .exists(TIMESTAMP_INDEX_MIGRATION) + .await + .is_ok() + } + fn from_json_slice((pdu_id, pdu): KeyVal<'_>) -> Result { let pdu_id: RawPduId = pdu_id.into(); @@ -323,9 +427,52 @@ impl Data { } } +pub const TIMESTAMP_INDEX_MIGRATION: &str = "populate_roomts_pduid"; + +#[must_use] +pub fn roomts_key(pdu_id: &RawPduId, ts: MilliSecondsSinceUnixEpoch) -> Vec { + let count = pdu_id.pdu_count().into_signed().cast_unsigned() ^ (1 << 63); + [pdu_id.shortroomid(), u64::from(ts.get()).to_be_bytes(), count.to_be_bytes()].concat() +} + +fn roomts_key_to_pdu_id(key: &[u8]) -> RawPduId { + let shortroomid = u64::from_be_bytes(key[0..8].try_into().expect("roomts key shortroomid")); + let count = u64::from_be_bytes(key[16..24].try_into().expect("roomts key count")) ^ (1 << 63); + + PduId { + shortroomid, + shorteventid: PduCount::from_signed(count.cast_signed()), + } + .into() +} + //TODO: this is an ABA fn increment(db: &Arc, key: &[u8]) { let old = db.get_blocking(key); let new = utils::increment(old.ok().as_deref()); db.insert(key, new); } + +#[cfg(test)] +mod tests { + use ruma::uint; + + use super::*; + + #[test] + fn roomts_key_orders_by_ts_then_count() { + let ids = [ + (PduCount::Normal(9), uint!(1)), + (PduCount::Backfilled(-5), uint!(2)), + (PduCount::Normal(3), uint!(2)), + (PduCount::Normal(1), uint!(3)), + ] + .map(|(count, ts)| (RawPduId::from(PduId { shortroomid: 7, shorteventid: count }), ts)); + let keys = ids.map(|(id, ts)| roomts_key(&id, MilliSecondsSinceUnixEpoch(ts))); + + assert!(keys.is_sorted()); + for ((id, _), key) in ids.iter().zip(&keys) { + assert_eq!(roomts_key_to_pdu_id(key), *id); + } + } +} diff --git a/src/service/rooms/timeline/helpers.rs b/src/service/rooms/timeline/helpers.rs index 170b35889..dc5db990e 100644 --- a/src/service/rooms/timeline/helpers.rs +++ b/src/service/rooms/timeline/helpers.rs @@ -48,13 +48,7 @@ impl super::Service { PartialPdu { event_type: event_type.to_string().into(), content, - sticky: self - .services - .config - .allow_sticky_events - .then_some(sticky_duration_ms) - .flatten() - .map(sticky::object), + sticky: sticky_duration_ms.map(sticky::object), state_key: Some(state_key.into()), timestamp, ..Default::default() diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 715d52855..15774c2e5 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -6,28 +6,36 @@ mod data; mod helpers; mod redact; -use std::{fmt::Write, sync::Arc}; +use std::{fmt::Write, sync::Arc, time::Duration}; use async_trait::async_trait; pub use conduwuit_core::matrix::pdu::{PduId, RawPduId}; use conduwuit_core::{ - Result, Server, at, err, + Err, Result, Server, at, debug, err, matrix::{ event::Event, pdu::{PduCount, PduEvent}, }, - utils::{MutexMap, MutexMapGuard, future::TryExtExt, stream::TryIgnore}, + utils::{self, MutexMap, MutexMapGuard, future::TryExtExt, stream::TryIgnore}, warn, }; use futures::{Future, Stream, TryStreamExt, pin_mut}; use ruma::{ - CanonicalJsonObject, EventId, OwnedEventId, OwnedRoomId, RoomId, - events::room::encrypted::Relation, + CanonicalJsonObject, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, RoomId, + api::Direction, events::room::encrypted::Relation, }; use serde::Deserialize; +use serde_json::value::RawValue as RawJsonValue; +use tokio::{ + sync::Notify, + time::{MissedTickBehavior, interval}, +}; use self::data::Data; -pub use self::{create::pdu_fits, data::PdusIterItem}; +pub use self::{ + create::pdu_fits, + data::{PdusIterItem, TIMESTAMP_INDEX_MIGRATION, roomts_key}, +}; use crate::{ Dep, account_data, admin, appservice, config, globals, pusher, rooms, sending, server_keys, sync, users, @@ -56,6 +64,7 @@ struct ExtractBody { } pub struct Service { + interrupt: Notify, services: Services, db: Data, pub mutex_insert: RoomMutexMap, @@ -87,6 +96,8 @@ struct Services { users: Dep, } +const PURGE_INTERVAL_SECS: u64 = 3600; + type RoomMutexMap = MutexMap; pub type RoomMutexGuard = MutexMapGuard; @@ -124,9 +135,35 @@ impl crate::Service for Service { }, db: Data::new(&args), mutex_insert: RoomMutexMap::new(), + interrupt: Notify::new(), })) } + #[tracing::instrument(skip_all, name = "unredacted_content_purge", level = "debug")] + async fn worker(self: Arc) -> Result<()> { + // Runs while disabled too, so old retained content still ages out. + let mut i = interval(Duration::from_secs(PURGE_INTERVAL_SECS)); + i.set_missed_tick_behavior(MissedTickBehavior::Delay); + loop { + tokio::select! { + () = self.interrupt.notified() => break, + _ = i.tick() => (), + } + + let purged = self + .db + .purge_unredacted_content(self.unredacted_content_cutoff()) + .await; + if purged > 0 { + debug!("Purged {purged} expired unredacted event contents"); + } + } + + Ok(()) + } + + fn interrupt(&self) { self.interrupt.notify_waiters(); } + async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result { let mutex_insert = self.mutex_insert.len(); writeln!(out, "insert_mutex: {mutex_insert}")?; @@ -242,6 +279,27 @@ impl Service { self.db.replace_pdu(pdu_id, pdu_json).await } + pub async fn get_unredacted_content(&self, pdu_id: &RawPduId) -> Result> { + let entry = self.db.get_unredacted_content(pdu_id).await?; + + if entry.created < self.unredacted_content_cutoff() { + return Err!(Request(NotFound("Unredacted content has expired."))); + } + + Ok(entry.content) + } + + fn unredacted_content_cutoff(&self) -> u64 { + let max_age = self + .services + .config + .experiments + .msc2815 + .map_or_default(|c| c.unredacted_content_max_age_secs); + + utils::millis_since_unix_epoch().saturating_sub(max_age.saturating_mul(1000)) + } + /// Returns an iterator over all PDUs in a room. Unknown rooms produce no /// items. #[inline] @@ -252,6 +310,17 @@ impl Service { self.pdus(room_id, None).ignore_err() } + pub fn pdus_by_timestamp<'a>( + &'a self, + room_id: &'a RoomId, + timestamp: MilliSecondsSinceUnixEpoch, + dir: Direction, + ) -> impl Stream> + Send + 'a { + self.db.pdus_by_timestamp(room_id, timestamp, dir) + } + + pub async fn timestamp_index_ready(&self) -> bool { self.db.timestamp_index_ready().await } + /// Reverse iteration starting after `until`. #[tracing::instrument(skip(self), level = "debug")] pub fn pdus_rev<'a>( diff --git a/src/service/rooms/timeline/redact.rs b/src/service/rooms/timeline/redact.rs index efa19dff5..0fbe4aba0 100644 --- a/src/service/rooms/timeline/redact.rs +++ b/src/service/rooms/timeline/redact.rs @@ -1,11 +1,8 @@ -use conduwuit_core::{ - Result, err, - matrix::event::Event, - utils::{self}, -}; -use ruma::EventId; +use conduwuit::config::experiments::ToggledExperiment; +use conduwuit_core::{Err, Result, err, matrix::event::Event, utils, warn}; +use ruma::{EventId, events::room::encrypted::Relation, signatures::content_hash}; -use super::ExtractBody; +use super::{ExtractBody, ExtractRelatesTo}; use crate::rooms::short::ShortRoomId; impl super::Service { @@ -31,6 +28,18 @@ impl super::Service { err!(Database(error!(?pdu_id, %event_id, ?e, "PDU ID points to invalid PDU."))) })?; + if pdu.room_id() != reason.room_id() { + return Err!(Request(Forbidden( + "Cannot redact an event that belongs to a different room." + ))); + } + + let thread_root = match pdu.get_content::() { + | Ok(ExtractRelatesTo { relates_to: Relation::Thread(thread) }) => + Some(thread.event_id), + | _ => None, + }; + if let Ok(content) = pdu.get_content::() { if let Some(body) = content.body { self.services @@ -45,12 +54,37 @@ impl super::Service { .get_room_version(&pdu.room_id_or_hash()) .await?; + if self.services.config.experiments.msc2815.is_enabled() { + let mut pdu_json = self.get_pdu_json_from_id(&pdu_id).await?; + pdu_json.remove("event_id"); + if content_hash(&pdu_json) + .is_ok_and(|hash| hash.encode() == pdu.hashes.sha256.trim_end_matches('=')) + { + self.db.save_unredacted_content(&pdu_id, &pdu.content); + } + } + pdu.redact(&room_version_id, Some(reason.event_id()))?; let obj = utils::to_canonical_object(&pdu).map_err(|e| { err!(Database(error!(%event_id, ?e, "Failed to convert PDU to canonical JSON"))) })?; - self.replace_pdu(&pdu_id, &obj).await + self.replace_pdu(&pdu_id, &obj).await?; + + // So the thread's root doesn't keep the original content in its + // `latest_event` aggregation + if let Some(thread_root) = thread_root { + self.services + .threads + .remove_from_thread(&thread_root, &pdu) + .await + .inspect_err(|e| { + warn!("Failed to remove redacted event from thread {thread_root}: {e:?}"); + }) + .ok(); + } + + Ok(()) } } diff --git a/src/service/rooms/typing/mod.rs b/src/service/rooms/typing/mod.rs index 113b3cebf..0cd6385fa 100644 --- a/src/service/rooms/typing/mod.rs +++ b/src/service/rooms/typing/mod.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeMap, sync::Arc}; use conduwuit::{ - Result, Server, debug_info, + Result, Server, SyncRwLock, debug_info, result::LogErr, utils::{self, IterStream}, }; @@ -14,7 +14,6 @@ use ruma::{ }, events::{EphemeralRoomEvent, SyncEphemeralRoomEvent, typing::TypingEventContent}, }; -use tokio::sync::RwLock; use crate::{Dep, globals, sending, sending::EduBuf, sync, users}; @@ -22,9 +21,9 @@ pub struct Service { server: Arc, services: Services, /// u64 is unix timestamp of timeout - pub typing: RwLock>>, + pub typing: SyncRwLock>>, /// timestamp of the last change to typing users - pub last_typing_update: RwLock>, + pub last_typing_update: SyncRwLock>, } struct Services { @@ -44,8 +43,8 @@ impl crate::Service for Service { sync: args.depend::("sync"), users: args.depend::("users"), }, - typing: RwLock::new(BTreeMap::new()), - last_typing_update: RwLock::new(BTreeMap::new()), + typing: SyncRwLock::new(BTreeMap::new()), + last_typing_update: SyncRwLock::new(BTreeMap::new()), })) } @@ -65,14 +64,12 @@ impl Service { // update clients self.typing .write() - .await .entry(room_id.to_owned()) .or_default() .insert(user_id.to_owned(), timeout); self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -94,14 +91,12 @@ impl Service { // update clients self.typing .write() - .await .entry(room_id.to_owned()) .or_default() .remove(user_id); self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -123,7 +118,7 @@ impl Service { let mut removable = Vec::new(); { - let typing = self.typing.read().await; + let typing = self.typing.read(); let Some(room) = typing.get(room_id) else { return Ok(()); }; @@ -139,7 +134,7 @@ impl Service { return Ok(()); } { - let mut typing = self.typing.write().await; + let mut typing = self.typing.write(); let room = typing.entry(room_id.to_owned()).or_default(); for user in &removable { debug_info!("typing timeout {user:?} in {room_id:?}"); @@ -150,7 +145,6 @@ impl Service { // update clients self.last_typing_update .write() - .await .insert(room_id.to_owned(), self.services.globals.next_count()?); self.services.sync.wake_all_joined(room_id).await; @@ -174,15 +168,14 @@ impl Service { Ok(self .last_typing_update .read() - .await .get(room_id) .copied() .unwrap_or(0)) } /// Returns a new typing EDU's content. - pub async fn typings_content(&self, room_id: &RoomId) -> TypingEventContent { - let room_typing_indicators = self.typing.read().await.get(room_id).cloned(); + pub fn typings_content(&self, room_id: &RoomId) -> TypingEventContent { + let room_typing_indicators = self.typing.read().get(room_id).cloned(); let Some(typing_indicators) = room_typing_indicators else { return TypingEventContent::new(Vec::new()); @@ -203,7 +196,7 @@ impl Service { room_id: &RoomId, sender_user: &UserId, ) -> Result> { - let room_typing_indicators = self.typing.read().await.get(room_id).cloned(); + let room_typing_indicators = self.typing.read().get(room_id).cloned(); let Some(typing_indicators) = room_typing_indicators else { return Ok(Vec::new()); @@ -265,7 +258,7 @@ impl Service { async fn appservice_send(&self, room_id: &RoomId) -> Result<()> { let edu = EphemeralData::Typing(EphemeralRoomEvent::new( room_id.to_owned(), - self.typings_content(room_id).await, + self.typings_content(room_id), )); let mut buf = EduBuf::new(); diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index 59f5c0647..afb08439c 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -3,6 +3,7 @@ use std::{fmt::Debug, sync::Arc}; use conduwuit::{ Error, Result, at, utils, utils::{ReadyExt, stream::TryIgnore}, + warn, }; use database::{Database, Deserialized, Map}; use futures::{Stream, StreamExt}; @@ -169,6 +170,51 @@ impl Data { }) } + /// Destinations with at least one queued request not yet in flight. + /// + /// Seeks past each destination's key prefix so large per-destination + /// backlogs are skipped in O(destinations) seeks rather than scanning + /// every queued event. + pub(super) async fn queued_destinations(&self) -> Vec { + let mut dests = Vec::new(); + let mut cursor = Vec::new(); + + while let Some(key) = self + .servernameevent_data + .raw_keys_from(&cursor) + .ignore_err() + .next() + .await + { + match parse_destination(key) { + | Ok((dest, _)) => { + let prefix = dest.get_prefix(); + dests.push(dest); + let Some(next) = next_prefix(&prefix) else { + break; + }; + cursor = next; + }, + | Err(e) => { + warn!(?key, "invalid queued request key: {e}"); + cursor = key.to_vec(); + cursor.push(0); + }, + } + } + + dests + } + + /// Estimated number of requests waiting to be sent and in flight. + pub(crate) fn request_counts(&self) -> [(&'static str, Option); 2] { + [ + ("queued", &self.servernameevent_data), + ("active", &self.servercurrentevent_data), + ] + .map(|(state, map)| (state, map.property_integer(c"rocksdb.estimate-num-keys").ok())) + } + pub(super) fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) { self.servername_educount.raw_put(server_name, last_count); } @@ -182,9 +228,17 @@ impl Data { } } -fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> { +/// Smallest byte slice strictly greater than every key starting with `prefix`. +fn next_prefix(prefix: &[u8]) -> Option> { + let pos = prefix.iter().rposition(|&b| b < u8::MAX)?; + let mut next = prefix[..=pos].to_vec(); + next[pos] = next[pos].saturating_add(1); + Some(next) +} + +fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> { // Appservices start with a plus - Ok::<_, Error>(if key.starts_with(b"+") { + if key.starts_with(b"+") { let mut parts = key[1..].splitn(2, |&b| b == 0xFF); let server = parts.next().expect("splitn always returns one element"); @@ -196,14 +250,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se Error::bad_database("Invalid server bytes in server_currenttransaction") })?; - ( - Destination::Appservice(server), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - SendingEvent::Edu(value.into()) - }, - ) + Ok((Destination::Appservice(server), event)) } else if key.starts_with(b"$") { let mut parts = key[1..].splitn(3, |&b| b == 0xFF); @@ -223,15 +270,7 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se .next() .ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; - ( - Destination::Push(user_id, pushkey_string), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - // I'm pretty sure this should never be called - SendingEvent::Edu(value.into()) - }, - ) + Ok((Destination::Push(user_id, pushkey_string), event)) } else { let mut parts = key.splitn(2, |&b| b == 0xFF); @@ -244,15 +283,22 @@ fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, Se Error::bad_database("Invalid server bytes in server_currenttransaction") })?; - ( + Ok(( Destination::Federation(ServerName::parse(&server).map_err(|_| { Error::bad_database("Invalid server string in server_currenttransaction") })?), - if value.is_empty() { - SendingEvent::Pdu(event.into()) - } else { - SendingEvent::Edu(value.into()) - }, - ) - }) + event, + )) + } +} + +fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> { + let (dest, event) = parse_destination(key)?; + let event = if value.is_empty() { + SendingEvent::Pdu(event.into()) + } else { + SendingEvent::Edu(value.into()) + }; + + Ok((dest, event)) } diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 8cb1010cf..21196e91c 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -3,12 +3,19 @@ mod appservice; mod data; mod dest; mod sender; +#[cfg(test)] +mod tests; use std::{ + collections::HashMap, fmt::Debug, hash::{DefaultHasher, Hash, Hasher}, iter::once, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::{Duration, Instant}, }; use async_trait::async_trait; @@ -19,17 +26,15 @@ use conduwuit::{ utils::{ReadyExt, TryReadyExt, available_parallelism, math::usize_from_u64_truncated}, warn, }; -use futures::{FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered}; use ruma::{ OwnedServerName, RoomId, ServerName, UserId, api::{ - OutgoingRequest, - auth_scheme::{NoAccessToken, NoAuthentication, SendAccessToken}, - federation::authentication::ServerSignatures, - path_builder::PathBuilder, + OutgoingRequest, auth_scheme::NoAuthentication, + federation::authentication::ServerSignatures, path_builder::PathBuilder, }, }; -use tokio::{task, task::JoinSet}; +use tokio::{task, task::JoinSet, time::sleep}; use self::data::Data; pub use self::{ @@ -51,6 +56,7 @@ pub struct Service { server: Arc, services: Services, channels: Vec<(loole::Sender, loole::Receiver)>, + workers_alive: AtomicUsize, } struct Services { @@ -89,6 +95,8 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>; const EDU_BUF_CAP: usize = 128; const EDU_VEC_CAP: usize = 1; +const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500); +const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(30); #[async_trait] impl crate::Service for Service { @@ -113,36 +121,67 @@ impl crate::Service for Service { federation: args.depend::("federation"), }, channels: (0..num_senders).map(|_| loole::unbounded()).collect(), + workers_alive: AtomicUsize::new(0), })) } async fn worker(self: Arc) -> Result { - let mut senders = - self.channels - .iter() - .enumerate() - .fold(JoinSet::new(), |mut joinset, (id, _)| { - let self_ = self.clone(); - let worker = self_.sender(id); - let worker = if self.unconstrained() { - task::unconstrained(worker).boxed() - } else { - worker.boxed() + if self.server.config.startup_netburst { + self.dispatch_queued(None).await; + } + + let num_senders = self.channels.len(); + let mut senders = JoinSet::new(); + let mut shards = HashMap::new(); + let mut started = vec![Instant::now(); num_senders]; + let mut failures = vec![0_u32; num_senders]; + let mut restarts = FuturesUnordered::new(); + for id in 0..num_senders { + self.spawn_sender(&mut senders, &mut shards, id, false); + } + + loop { + tokio::select! { + Some(ret) = senders.join_next_with_id() => { + self.workers_alive.fetch_sub(1, Ordering::Relaxed); + let (task_id, panicked) = match &ret { + | Ok((task_id, _)) => (*task_id, false), + | Err(error) => (error.id(), error.is_panic()), }; + let shard = shards.remove(&task_id).expect("sender worker has a shard"); - let runtime = self.server.runtime(); - let _abort = joinset.spawn_on(worker, runtime); - joinset - }); + if panicked { + self.server + .metrics + .instruments + .sender_panics + .add(1, &[KeyValue::new("scope", "worker")]); + } - while let Some(ret) = senders.join_next_with_id().await { - match ret { - | Ok((id, error)) => { - debug!(?id, ?error, "sender worker finished"); + if self.channels[shard].1.is_closed() || !self.server.running() { + debug!(shard, ?ret, "sender worker finished"); + continue; + } + + // A worker that ran a while before failing starts over from + // the shortest delay. + failures[shard] = if started[shard].elapsed() > WORKER_RESTART_DELAY_MAX { + 1 + } else { + failures[shard].saturating_add(1) + }; + let delay = restart_delay(failures[shard]); + error!(shard, ?ret, ?delay, "sender worker unexpectedly finished, restarting"); + restarts.push(sleep(delay).map(move |()| shard)); }, - | Err(error) => { - error!(id = ?error.id(), ?error, "sender worker failed"); + Some(shard) = restarts.next() => { + if !self.channels[shard].1.is_closed() && self.server.running() { + started[shard] = Instant::now(); + self.spawn_sender(&mut senders, &mut shards, shard, true); + } }, + () = self.server.until_shutdown(), if !restarts.is_empty() => restarts.clear(), + else => break, } } @@ -163,6 +202,25 @@ impl crate::Service for Service { } impl Service { + fn spawn_sender( + self: &Arc, + senders: &mut JoinSet, + shards: &mut HashMap, + id: usize, + restarted: bool, + ) { + let worker = self.clone().sender(id, restarted); + let worker = if crate::Service::unconstrained(&**self) { + task::unconstrained(worker).boxed() + } else { + worker.boxed() + }; + + let handle = senders.spawn_on(worker, self.server.runtime()); + shards.insert(handle.id(), id); + self.workers_alive.fetch_add(1, Ordering::Relaxed); + } + #[tracing::instrument(skip(self, pdu_id, user, pushkey), level = "debug")] pub fn send_pdu_push(&self, pdu_id: &RawPduId, user: &UserId, pushkey: String) -> Result { let dest = Destination::Push(user.to_owned(), pushkey); @@ -270,7 +328,6 @@ impl Service { .services .appservice .read() - .await .values() .filter(|appservice| appservice.registration.receive_ephemeral && filter(appservice)) .cloned() @@ -421,26 +478,6 @@ impl Service { .await } - /// Send an unauthenticated federation request with no X-Matrix header. - #[inline] - pub async fn send_legacy_media_request<'i, T>( - &self, - dest: &ServerName, - request: T, - ) -> Result - where - T: OutgoingRequest< - Authentication = NoAccessToken, - PathBuilder: PathBuilder: FederationPathBuilderInput>, - > + Debug - + Send, - { - self.services - .federation - .execute_on(&self.services.client.federation, dest, request, SendAccessToken::None) - .await - } - /// Clean up queued sending event data /// /// Used after we remove an appservice registration or a user deletes a push @@ -503,10 +540,32 @@ impl Service { sender.send(msg).map_err(|e| err!("{e}")) } + /// Wakes workers for every destination that has unsent queued requests, so + /// a backlog with nothing in flight is drained without waiting for a new + /// event. Uses `SendingEvent::Flush` so a message racing with already- + /// buffered channel items cannot re-insert and duplicate a sent request. + async fn dispatch_queued(&self, shard: Option) { + for dest in self.db.queued_destinations().await { + let id = self.shard_id(&dest); + if shard.is_none_or(|shard| shard == id) { + self.channels[id] + .0 + .send(Msg { + dest, + event: SendingEvent::Flush, + queue_id: Vec::new(), + }) + .ok(); + } + } + } + pub fn queue_depth(&self) -> usize { self.channels.iter().map(|(sender, _)| sender.len()).sum() } + pub fn workers_alive(&self) -> usize { self.workers_alive.load(Ordering::Relaxed) } + pub(super) fn shard_id(&self, dest: &Destination) -> usize { if self.channels.len() <= 1 { return 0; @@ -542,3 +601,11 @@ fn num_senders(args: &crate::Args<'_>) -> usize { worker_count.clamp(MIN_SENDERS, max_senders) } } + +/// Delay before restarting a worker after its `failures`-th consecutive +/// failure, doubling each time. +fn restart_delay(failures: u32) -> Duration { + WORKER_RESTART_DELAY + .saturating_mul(2_u32.saturating_pow(failures.saturating_sub(1))) + .min(WORKER_RESTART_DELAY_MAX) +} diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 308dcbd79..bb6be5f2f 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -1,6 +1,7 @@ use std::{ collections::{BTreeMap, HashMap, HashSet}, fmt::Debug, + panic::AssertUnwindSafe, sync::{ Arc, atomic::{AtomicU64, AtomicUsize, Ordering}, @@ -55,11 +56,17 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value}; use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem}; +#[cfg(test)] +mod tests; + #[derive(Debug)] enum TransactionStatus { Running, - Failed(u32, Instant), // number of times failed, time of last failure - Retrying(u32), // number of times failed + /// Number of times failed, time of last failure, and whether local backoff + /// applies even for federation destinations (e.g. after a local panic when + /// the remote was not marked unhealthy). + Failed(u32, Instant, bool), + Retrying(u32), // number of times failed } type SendingError = (Destination, Box); @@ -78,12 +85,18 @@ pub const EDU_LIMIT: usize = 100; impl Service { #[tracing::instrument(skip(self), level = "debug")] - pub(super) async fn sender(self: Arc, id: usize) -> Result { + pub(super) async fn sender(self: Arc, id: usize, restarted: bool) -> Result { let mut statuses: CurTransactionStatus = CurTransactionStatus::new(); let mut futures: SendingFutures<'_> = FuturesUnordered::new(); + // The previous worker of this shard may have dropped requests it had + // taken from the channel. + if restarted { + self.dispatch_queued(Some(id)).await; + } + info!(shard = id, "Running startup netburst"); - self.startup_netburst(id, &mut futures, &mut statuses) + self.startup_netburst(id, restarted, &mut futures, &mut statuses) .boxed() .await; info!(shard = id, "Finished startup netburst"); @@ -142,33 +155,46 @@ impl Service { ) { match response { | Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await, + // A bug on our side, not the remote's fault: retry with local + // backoff without marking the remote unhealthy. + | Err((dest, e)) if e.is_panic() => + Self::handle_response_err(dest, statuses, &e, true), | Err((dest, e)) => { + let mut local_backoff = false; if let Destination::Federation(dest) = &dest { if self.services.federation.should_mark_stale(&e) || e.status_code() == StatusCode::NOT_FOUND { debug!("{dest} is now unhealthy & stale due to a connect error: {e:?}"); self.services.federation.mark_destination_stale(dest); - self.services.federation.hit_unhealthy(dest.clone()); + self.services.federation.hit_unhealthy(dest.clone(), None); } else if e.status_code() != StatusCode::OK { debug!("{dest} is now unhealthy due to error response: {e:?}"); - self.services.federation.hit_unhealthy(dest.clone()); + self.services.federation.hit_unhealthy(dest.clone(), None); + } else { + local_backoff = true; } } - Self::handle_response_err(dest, statuses, &e); + Self::handle_response_err(dest, statuses, &e, local_backoff); }, } } /// Handles a response error, incrementing the backoff factor. - fn handle_response_err(dest: Destination, statuses: &mut CurTransactionStatus, er: &Error) { + fn handle_response_err( + dest: Destination, + statuses: &mut CurTransactionStatus, + er: &Error, + local_backoff: bool, + ) { debug!(dest = ?dest, "{er:?}"); let dest2 = dest.clone(); statuses.entry(dest).and_modify(|e| { *e = match e { - | TransactionStatus::Running => TransactionStatus::Failed(1, Instant::now()), + | TransactionStatus::Running => + TransactionStatus::Failed(1, Instant::now(), local_backoff), | &mut TransactionStatus::Retrying(ref n) => - TransactionStatus::Failed(n.saturating_add(1), Instant::now()), + TransactionStatus::Failed(n.saturating_add(1), Instant::now(), local_backoff), | TransactionStatus::Failed(..) => { panic!( "Request to {dest2:?} that was not even running ({e:?}) failed: {er:?}" @@ -274,7 +300,8 @@ impl Service { } /// Performs startup netburst, which sends any previously queued up but not - /// yet sent requests immediately. + /// yet sent requests immediately. A restarted worker always resends its + /// shard's requests in flight. #[tracing::instrument( name = "netburst", level = "debug", @@ -285,9 +312,11 @@ impl Service { async fn startup_netburst<'a>( &'a self, id: usize, + restarted: bool, futures: &mut SendingFutures<'a>, statuses: &mut CurTransactionStatus, ) { + let delivering = restarted || self.server.config.startup_netburst; let keep = usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX); let mut txns = HashMap::>::new(); @@ -302,7 +331,7 @@ impl Service { let over_budget = self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep; - if over_budget && !self.survives_netburst_trim(&event).await { + if over_budget && !self.survives_netburst_trim(&event, delivering).await { warn!( startup_netburst_keep = self.server.config.startup_netburst_keep, queue_size = entry.len(), @@ -315,8 +344,12 @@ impl Service { } } + if !delivering { + return; + } + for (dest, events) in txns { - if self.server.config.startup_netburst && !events.is_empty() { + if !events.is_empty() { statuses.insert(dest.clone(), TransactionStatus::Running); futures.push(self.send_events(dest, events)); } @@ -324,10 +357,10 @@ impl Service { } /// Whether this event skips the netburst budget, which MSC4354 asks of - /// still-sticky events. Only netburst delivers this queue, so with it - /// disabled there is nothing to keep the event for. - async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool { - if !self.server.config.allow_sticky_events || !self.server.config.startup_netburst { + /// still-sticky events. Only a delivering netburst drains this queue, so + /// when nothing will deliver it there is nothing to keep the event for. + async fn survives_netburst_trim(&self, event: &SendingEvent, delivering: bool) -> bool { + if !delivering { return false; } @@ -425,12 +458,17 @@ impl Service { allow = false; // already running trace!("Transaction is already running for {dest:?}"); }, - | TransactionStatus::Failed(tries, _) => { - if allow { + | TransactionStatus::Failed(tries, time, local_backoff) => { + if *local_backoff + && time.elapsed() < self.server.config.sender_retry_backoff(*tries) + { + allow = false; + trace!("{dest:?} is in local backoff, refusing send"); + } else { *e = TransactionStatus::Retrying(*tries); trace!("Previous transaction failed for {dest:?} ({e:?}), will retry"); + retry = true; } - retry = true; }, }); @@ -449,7 +487,7 @@ impl Service { statuses .entry(dest.clone()) .and_modify(|e| match e { - | TransactionStatus::Failed(tries, time) => { + | TransactionStatus::Failed(tries, time, _) => { let retry_after = self.server.config.sender_retry_backoff(*tries); if time.elapsed() < retry_after { debug_warn!("Not retrying destination for another {retry_after:?}"); @@ -579,21 +617,21 @@ impl Service { since: (u64, u64), max_edu_count: &AtomicU64, ) -> Option { - let mut num = 0; + let num = AtomicUsize::new(0); let receipts: BTreeMap = self .services .state_cache .server_rooms(server_name) - .broad_filter_map(|room_id| async move { + .broad_filter_map(|room_id| async { + if num.load(Ordering::Relaxed) >= SELECT_RECEIPT_LIMIT { + return None; + } + let receipt_map = self - .select_edus_receipts_room(&room_id, since, max_edu_count, &mut num) + .select_edus_receipts_room(&room_id, since, max_edu_count, &num) .await; - receipt_map - .read - .is_empty() - .eq(&false) - .then_some((room_id, receipt_map)) + (!receipt_map.read.is_empty()).then_some((room_id, receipt_map)) }) .collect() .await; @@ -612,13 +650,17 @@ impl Service { } /// Look for read receipts in this room - #[tracing::instrument(name = "receipts", level = "trace", skip(self, since, max_edu_count))] + #[tracing::instrument( + name = "receipts", + level = "trace", + skip(self, since, max_edu_count, num) + )] async fn select_edus_receipts_room( &self, room_id: &RoomId, since: (u64, u64), max_edu_count: &AtomicU64, - num: &mut usize, + num: &AtomicUsize, ) -> ReceiptMap { let receipts = self .services @@ -647,24 +689,23 @@ impl Service { continue; }; - let (event_id, mut receipt) = r - .content - .0 - .into_iter() - .next() - .expect("we only use one event per read receipt"); + let Some((event_id, mut receipt)) = r.content.0.into_iter().next() else { + error!(%user_id, %count, "Empty content in read_receipts"); + continue; + }; - let receipt = receipt + let Some(receipt) = receipt .remove(&ReceiptType::Read) - .expect("our read receipts always set this") - .remove(&user_id) - .expect("our read receipts always have the user here"); + .and_then(|mut u| u.remove(&user_id)) + else { + error!(%user_id, %count, "Missing user receipt for ReceiptType::Read in read_receipts"); + continue; + }; let receipt_data = ReceiptData::new(receipt, vec![event_id]); if read.insert(user_id, receipt_data).is_none() { - *num = num.saturating_add(1); - if *num >= SELECT_RECEIPT_LIMIT { + if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT { break; } } @@ -769,6 +810,7 @@ impl Service { }); let start = Instant::now(); + let panic_dest = dest.clone(); let send = match dest { | Destination::Federation(server) => self.send_events_dest_federation(server, events).boxed(), @@ -777,24 +819,42 @@ impl Service { self.send_events_dest_push(user_id, pushkey, events).boxed(), }; - send.inspect(move |result| { - let instruments = &self.server.metrics.instruments; - let outcome = - KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" }); - instruments - .sender_transaction_duration - .record(start.elapsed().as_secs_f64(), &[destination.clone(), outcome.clone()]); - for (kind, count) in [("pdu", pdus), ("edu", edus)] { - if count > 0 { - instruments.sender_events.add(count, &[ + AssertUnwindSafe(send) + .catch_unwind() + .map(move |result| { + result.unwrap_or_else(|panic| { + let error = Error::from_panic(panic); + error!(dest = ?panic_dest, ?error, "Panicked while sending transaction"); + self.server + .metrics + .instruments + .sender_panics + .add(1, &[KeyValue::new("scope", "transaction")]); + + Err((panic_dest, Box::new(error))) + }) + }) + .inspect(move |result| { + let instruments = &self.server.metrics.instruments; + let outcome = + KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" }); + instruments + .sender_transaction_duration + .record(start.elapsed().as_secs_f64(), &[ destination.clone(), - KeyValue::new("kind", kind), outcome.clone(), ]); + for (kind, count) in [("pdu", pdus), ("edu", edus)] { + if count > 0 { + instruments.sender_events.add(count, &[ + destination.clone(), + KeyValue::new("kind", kind), + outcome.clone(), + ]); + } } - } - }) - .boxed() + }) + .boxed() } #[tracing::instrument( @@ -810,7 +870,7 @@ impl Service { id: String, events: Vec, ) -> SendingResult { - let Some(appservice) = self.services.appservice.get_registration(&id).await else { + let Some(appservice) = self.services.appservice.get_registration(&id) else { return Err(( Destination::Appservice(id.clone()), Box::new(err!(Database(warn!(?id, "Missing appservice registration")))), diff --git a/src/service/sending/sender/tests.rs b/src/service/sending/sender/tests.rs new file mode 100644 index 000000000..1864f318d --- /dev/null +++ b/src/service/sending/sender/tests.rs @@ -0,0 +1,198 @@ +use std::iter::once; + +use conduwuit::{ + Error, + matrix::{PartialPdu, pdu::sticky}, +}; +use futures::{StreamExt, stream::FuturesUnordered}; +use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name}; +use serde_json::{json, value::to_raw_value}; + +use super::{CurTransactionStatus, TransactionStatus}; +use crate::{ + sending::{Destination, EduBuf, SendingEvent}, + test_utils::{test_services, test_services_with}, +}; + +#[tokio::test] +async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() { + let (services, path, _database) = test_services().await; + let sending = &services.sending; + let server = server_name!("remote.example"); + let dest = Destination::Federation(server.to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + sending.db.queue_requests(once((&event, &dest))); + let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(in_flight.iter()); + + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]); + let panic = Error::from_panic(Box::new("boom")); + sending + .handle_response(Err((dest.clone(), Box::new(panic))), &mut futures, &mut statuses) + .await; + + let active: Vec<_> = sending + .db + .active_requests_for(&dest) + .map(|(key, _)| key) + .collect() + .await; + let retry_after = sending.services.federation.retry_after(server); + let sending_next = futures.len(); + let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _, true))); + let immediate_retry = sending.should_attempt_send(&dest, &mut statuses).unwrap(); + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!( + active, + in_flight + .into_iter() + .map(|(key, _)| key) + .collect::>() + ); + assert_eq!(sending_next, 0); + assert!(failed); + assert_eq!(immediate_retry, (false, false)); + assert_eq!(retry_after, None); +} + +#[tokio::test] +async fn restarted_worker_resends_trimmed_in_flight_requests() { + let (services, path, _database) = + test_services_with(json!({ "startup_netburst_keep": 1 })).await; + let sending = &services.sending; + let dest = Destination::Federation(server_name!("remote.example").to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + for _ in 0..3 { + sending.db.queue_requests(once((&event, &dest))); + } + let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(queued.iter()); + + let id = sending.shard_id(&dest); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, true, &mut futures, &mut statuses) + .await; + let active = sending.db.active_requests_for(&dest).count().await; + let sending_now = futures.len(); + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(active, 1); + assert_eq!(sending_now, 1); +} + +#[tokio::test] +async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled() { + let (services, path, _database) = + test_services_with(json!({ "startup_netburst": false, "startup_netburst_keep": 0 })) + .await; + let alice = UserId::parse("@alice:test.example").unwrap(); + let bootstrap = services + .rooms + .state + .mutex + .lock("!bootstrap:test.example") + .await; + let create_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.create".into(), + content: to_raw_value(&json!({ "room_version": "12" })).unwrap(), + state_key: Some("".into()), + ..Default::default() + }, + &alice, + None, + &bootstrap, + ) + .await + .unwrap(); + drop(bootstrap); + + let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap(); + let lock = services.rooms.state.mutex.lock(&room).await; + services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.member".into(), + content: to_raw_value(&json!({ "membership": "join" })).unwrap(), + state_key: Some(alice.as_str().into()), + ..Default::default() + }, + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + let sticky_id = services + .rooms + .timeline + .build_and_append_pdu( + PartialPdu { + event_type: "m.room.message".into(), + content: to_raw_value(&json!({ "msgtype": "m.text", "body": "sticky" })).unwrap(), + sticky: Some(sticky::object(StickyDurationMs::new_clamped(600_000_u32))), + ..Default::default() + }, + &alice, + Some(&room), + &lock, + ) + .await + .unwrap(); + drop(lock); + + let raw_pdu_id = services + .rooms + .timeline + .get_pdu_id(&sticky_id) + .await + .unwrap(); + let sending = &services.sending; + let dest = Destination::Federation(server_name!("remote.example").to_owned()); + let event = SendingEvent::Pdu(raw_pdu_id); + + sending.db.queue_requests(once((&event, &dest))); + let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await; + sending.db.mark_as_active(queued.iter()); + + let id = sending.shard_id(&dest); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, true, &mut futures, &mut statuses) + .await; + let active_after_restart = sending.db.active_requests_for(&dest).count().await; + let sending_after_restart = futures.len(); + + drop(futures); + let mut futures = FuturesUnordered::new(); + let mut statuses = CurTransactionStatus::new(); + sending + .startup_netburst(id, false, &mut futures, &mut statuses) + .await; + let active_after_startup = sending.db.active_requests_for(&dest).count().await; + let sending_after_startup = futures.len(); + + drop(futures); + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(active_after_restart, 1); + assert_eq!(sending_after_restart, 1); + assert_eq!(active_after_startup, 0); + assert_eq!(sending_after_startup, 0); +} diff --git a/src/service/sending/tests.rs b/src/service/sending/tests.rs new file mode 100644 index 000000000..0e59f1921 --- /dev/null +++ b/src/service/sending/tests.rs @@ -0,0 +1,41 @@ +use std::{iter::once, time::Duration}; + +use futures::StreamExt; +use ruma::server_name; + +use super::{Destination, EduBuf, SendingEvent, restart_delay}; +use crate::test_utils::test_services; + +#[tokio::test] +async fn queued_destinations_lists_each_destination_with_unsent_requests() { + let (services, path, _database) = test_services().await; + let db = &services.sending.db; + let queued_sub = Destination::Federation(server_name!("queued.example.org").to_owned()); + let queued = Destination::Federation(server_name!("queued.example").to_owned()); + let appservice = Destination::Appservice("bridge".to_owned()); + let active = Destination::Federation(server_name!("active.example").to_owned()); + let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#)); + + db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &queued))); + db.queue_requests(once((&event, &queued_sub))); + db.queue_requests(once((&event, &appservice))); + db.queue_requests(once((&event, &active))); + let in_flight: Vec<_> = db.queued_requests(&active).collect().await; + db.mark_as_active(in_flight.iter()); + + let dests = db.queued_destinations().await; + + drop(services); + std::fs::remove_dir_all(path).unwrap(); + assert_eq!(dests, [appservice, queued_sub, queued]); +} + +#[test] +fn restart_delay_doubles_up_to_the_cap() { + assert_eq!(restart_delay(1), Duration::from_millis(2500)); + assert_eq!(restart_delay(2), Duration::from_secs(5)); + assert_eq!(restart_delay(4), Duration::from_secs(20)); + assert_eq!(restart_delay(5), Duration::from_secs(30)); + assert_eq!(restart_delay(u32::MAX), Duration::from_secs(30)); +} diff --git a/src/service/server_keys/get.rs b/src/service/server_keys/get.rs index 5011171c4..a94213c44 100644 --- a/src/service/server_keys/get.rs +++ b/src/service/server_keys/get.rs @@ -241,9 +241,9 @@ impl super::Service { continue; } }; - trace!(?origin_response, "Got signing key response from origin"); + trace!(?origin_response.raw, "Got signing key response from origin"); self.add_signing_keys(&origin_response); - Self::track_result(&mut result, &mut still_missing, &origin_response); + Self::track_result(&mut result, &mut still_missing, &origin_response.parsed); if still_missing.is_empty() { break; } @@ -262,9 +262,9 @@ impl super::Service { "Got signing keys response from a notary" ); for server_keys in notary_response { - trace!(?server_keys, "Adding response from notary"); + trace!(?server_keys.raw, "Adding response from notary"); self.add_signing_keys(&server_keys); - Self::track_result(&mut result, &mut still_missing, &server_keys); + Self::track_result(&mut result, &mut still_missing, &server_keys.parsed); if still_missing.is_empty() { break; } @@ -285,9 +285,9 @@ impl super::Service { continue; }; for server_keys in res { - trace!(?server_keys, "Adding response from notary"); + trace!(?server_keys.raw, "Adding response from notary"); self.add_signing_keys(&server_keys); - Self::track_result(&mut result, &mut still_missing, &server_keys); + Self::track_result(&mut result, &mut still_missing, &server_keys.parsed); } if still_missing.is_empty() { break; @@ -300,9 +300,9 @@ impl super::Service { debug_warn!(err=?res.err(), "Got error response from origin"); continue; }; - trace!(response=?res, "Got signing key response from origin"); + trace!(response=?res.raw, "Got signing key response from origin"); self.add_signing_keys(&res); - Self::track_result(&mut result, &mut still_missing, &res); + Self::track_result(&mut result, &mut still_missing, &res.parsed); if still_missing.is_empty() { break; } @@ -400,7 +400,7 @@ impl super::Service { .inspect_err(|e| info!("Could not acquire signing key from origin server: {e:?}")) .ok()?; - verify_key_from_response(key_id, &response, min_valid_ts) + verify_key_from_response(key_id, &response.parsed, min_valid_ts) .inspect(|_| self.add_signing_keys(&response)) } } diff --git a/src/service/server_keys/mod.rs b/src/service/server_keys/mod.rs index ea93b5cc8..b14edd9b4 100644 --- a/src/service/server_keys/mod.rs +++ b/src/service/server_keys/mod.rs @@ -29,6 +29,7 @@ use ruma::{ signatures::{Ed25519KeyPair, PublicKeyMap, PublicKeySet}, }; use serde_json::value::to_raw_value; +use verify::IncomingServerKeys; pub use verify::strip_extraneous_signatures; use crate::{Dep, globals, sending, server_keys::util::required_keys}; @@ -99,19 +100,22 @@ impl Service { } /// Adds a signing key response to the database. - fn add_signing_keys(&self, new_keys: &ServerSigningKeys) { + fn add_signing_keys(&self, new_keys: &IncomingServerKeys) { // TODO(nex): this results in massive amounts of data duplication. // Perhaps a sliding approach would be better? where we just update the // last known response if the only thing that changed was the // valid_until_ts. This would require a more complex data structure // though. For now, just storing the duplicated data is fine. for key in new_keys + .parsed .verify_keys .keys() - .chain(new_keys.old_verify_keys.keys()) + .chain(new_keys.parsed.old_verify_keys.keys()) { - let db_key = (new_keys.server_name.as_str(), key.as_str()); - self.db.servernamekeyid_response.put(db_key, Json(new_keys)); + let db_key = (new_keys.parsed.server_name.as_str(), key.as_str()); + self.db + .servernamekeyid_response + .put(db_key, Json(&new_keys.raw)); } } @@ -186,7 +190,7 @@ impl Service { let mut keys = self .signing_keys_for(origin) .ready_fold(BTreeMap::new(), |mut base, keys| { - base.extend(keys.verify_keys); + base.extend(keys.parsed.verify_keys); base }) .await; @@ -204,12 +208,13 @@ impl Service { pub fn signing_keys_for<'a>( &'a self, origin: &'a ServerName, - ) -> impl Stream + Send + 'a { + ) -> impl Stream + Send + 'a { self.db .servernamekeyid_response .stream_prefix(&(origin, Interfix)) .ignore_err() - .map(|(_, v): (Ignore, ServerSigningKeys)| v) + .map(|(_, v): (Ignore, Raw)| v.try_into().map_err(Into::into)) + .ignore_err() } /// Determines if the server may contact the origin server to fetch keys @@ -260,7 +265,7 @@ impl Service { // We need to verify that this response is still trusted based on // the current configuration. It's possible we got this response // from a notary who we no longer trust. - if resp.valid_until_ts > in_one_week() || resp.valid_until_ts < now { + if resp.parsed.valid_until_ts > in_one_week() || resp.valid_until_ts < now { continue; } let trusted = self @@ -279,8 +284,8 @@ impl Service { if !trusted { continue; } - for (old_key_id, old_key) in resp.old_verify_keys { - if old_key.expired_ts > resp.valid_until_ts { + for (old_key_id, old_key) in resp.parsed.old_verify_keys { + if old_key.expired_ts > resp.parsed.valid_until_ts { // This key expired in the future which is probably illegal continue; } diff --git a/src/service/server_keys/request.rs b/src/service/server_keys/request.rs index d6d3ddcda..62344234d 100644 --- a/src/service/server_keys/request.rs +++ b/src/service/server_keys/request.rs @@ -4,7 +4,6 @@ use conduwuit::{Err, Result, trace, utils::millis_since_unix_epoch, warn}; use ruma::{ MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId, ServerName, UInt, api::federation::discovery::{ - ServerSigningKeys, get_remote_server_keys_batch::{ self, v2::{QueryCriteria, Response as NotaryResponse}, @@ -15,6 +14,8 @@ use ruma::{ uint, }; +use crate::server_keys::verify::IncomingServerKeys; + pub(crate) type ServerKeysQuery = BTreeMap; pub(crate) type ServerKeysQuerySet = BTreeMap; @@ -27,7 +28,7 @@ impl super::Service { &self, target: OwnedServerName, min_valid_ts: MilliSecondsSinceUnixEpoch, - ) -> Result { + ) -> Result { use get_server_keys::v2::Request; if target == self.services.server.name { @@ -47,29 +48,30 @@ impl super::Service { self.last_lookup .write() .insert(target.clone(), Instant::now()); - let server_signing_key = self + let raw_server_key = self .services .sending .send_unauthenticated_request(&target, Request::new()) .await - .map(|response| response.server_key) - .and_then(|key| key.deserialize().map_err(Into::into))?; + .map(|response| response.server_key)?; - if server_signing_key.server_name != target { + let server_signing_key: IncomingServerKeys = raw_server_key.try_into()?; + + if server_signing_key.parsed.server_name != target { return Err!(BadServerResponse(debug_warn!( requested = ?target, - response = ?server_signing_key.server_name, + response = ?server_signing_key.parsed.server_name, "Origin server responded with bogus server_name" ))); } - if server_signing_key.valid_until_ts < min_valid_ts - || server_signing_key.valid_until_ts > in_one_week() + if server_signing_key.parsed.valid_until_ts < min_valid_ts + || server_signing_key.parsed.valid_until_ts > in_one_week() { return Err!(BadServerResponse(debug_warn!( ?target, ?min_valid_ts, - ?server_signing_key.valid_until_ts, + ?server_signing_key.parsed.valid_until_ts, "Origin server responded with server keys that are not in-date" ))); } @@ -100,7 +102,7 @@ impl super::Service { &self, notary: &ServerName, batch: ServerKeysQuery, - ) -> Result> { + ) -> Result> { use get_remote_server_keys_batch::v2::Request; let is_empty = batch.is_empty() || batch.values().all(BTreeMap::is_empty); @@ -116,8 +118,7 @@ impl super::Service { .trusted_servers .iter() .find(|n| n.server_name() == notary) - .map(|nk| nk.verify_keys().to_owned()) - .unwrap_or_default(); + .map_or_default(|nk| nk.verify_keys().to_owned()); let keys = self .services .sending @@ -133,12 +134,12 @@ impl super::Service { } /// Parses a notary response, returning a vec of server signing key - /// responses. Drops any chunks that cannot be deserialized. - fn parse_notary_response(raw: &NotaryResponse) -> Vec { + /// responses, each paired with its raw JSON (which is what the signatures + /// were made over). Drops any chunks that cannot be deserialized. + fn parse_notary_response(raw: &NotaryResponse) -> Vec { raw.server_keys .iter() - .map(ruma::serde::Raw::deserialize) - .filter_map(Result::ok) + .filter_map(|chunk| chunk.try_into().ok()) .collect() } @@ -146,12 +147,15 @@ impl super::Service { /// if the response should be dropped, true if it should be kept. fn validate_notary_chunk( batch: &ServerKeysQuery, - keys: &ServerSigningKeys, + incoming: &IncomingServerKeys, notary_name: &ServerName, notary_keys: &[Base64], ) -> bool { - let Some(expected_keys) = batch.get(&keys.server_name) else { - trace!("Dropping signing keys chunk for unrequested server: {}", keys.server_name); + let Some(expected_keys) = batch.get(&incoming.parsed.server_name) else { + trace!( + "Dropping signing keys chunk for unrequested server: {}", + incoming.parsed.server_name + ); return false; }; let min_valid_ts = expected_keys @@ -165,13 +169,15 @@ impl super::Service { // If this notary response is older than any of the min_valid_ts we // requested, then we should drop it. - if keys.valid_until_ts < min_valid_ts || keys.valid_until_ts > in_one_week() { + if incoming.parsed.valid_until_ts < min_valid_ts + || incoming.parsed.valid_until_ts > in_one_week() + { trace!( ?min_valid_ts, - ?keys.valid_until_ts, + ?incoming.parsed.valid_until_ts, "Dropping signing keys chunk for server {} because it is older than the minimum \ valid timestamp we requested", - keys.server_name + incoming.parsed.server_name ); return false; } @@ -179,38 +185,39 @@ impl super::Service { // Does this chunk even contain any keys we asked for? // Note that this enforces min_valid_ts per-key, instead of using the // lowest denominator. - let all_key_ids = keys + let all_key_ids = incoming + .parsed .verify_keys .keys() - .chain(keys.old_verify_keys.keys()) + .chain(incoming.parsed.old_verify_keys.keys()) .map(ToOwned::to_owned) .collect::>(); let interesting = expected_keys.iter().any(|(k, q)| { all_key_ids.contains(k) && q.minimum_valid_until_ts - .is_none_or(|m| m <= keys.valid_until_ts) + .is_none_or(|m| m <= incoming.parsed.valid_until_ts) }); if !interesting { trace!( "Dropping signing keys chunk for server {} because it does not contain any keys \ we requested", - keys.server_name + incoming.parsed.server_name ); return false; } - Self::verify_server_keys_response(keys, Some((notary_name, notary_keys))) + Self::verify_server_keys_response(incoming, Some((notary_name, notary_keys))) .inspect_err(|e| { trace!( ?e, - ?keys, + ?incoming.raw, ?notary_name, ?notary_keys, "Dropping illegal server signing keys response chunk" ); warn!( %notary_name, - server_name=%keys.server_name, + server_name=%incoming.parsed.server_name, "Dropping illegal server signing keys response chunk: {e:?}" ); }) diff --git a/src/service/server_keys/verify.rs b/src/service/server_keys/verify.rs index cc3f104a2..f956e10d8 100644 --- a/src/service/server_keys/verify.rs +++ b/src/service/server_keys/verify.rs @@ -5,11 +5,36 @@ use ruma::{ CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, ServerName, SigningKeyAlgorithm, api::federation::discovery::ServerSigningKeys, room_version_rules::RoomVersionRules, - serde::{Base64, base64::Standard}, + serde::{Base64, Raw, base64::Standard}, signatures::Verified, }; use serde_json::value::RawValue as RawJsonValue; +pub struct IncomingServerKeys { + pub raw: Raw, + pub parsed: ServerSigningKeys, +} + +impl TryFrom> for IncomingServerKeys { + type Error = serde_json::Error; + + fn try_from(value: Raw) -> std::result::Result { + value + .deserialize() + .map(|parsed| Self { raw: value, parsed }) + } +} + +impl TryFrom<&Raw> for IncomingServerKeys { + type Error = serde_json::Error; + + fn try_from(value: &Raw) -> std::result::Result { + value + .deserialize() + .map(|parsed| Self { raw: value.to_owned(), parsed }) + } +} + impl super::Service { /// Validates the incoming event only using locally known verification keys. /// Inserts the calculated event ID into the event_id field upon success. @@ -58,34 +83,38 @@ impl super::Service { /// `notary` must either be empty or have ONE entry. Extraneous notaries /// will be ignored. pub fn verify_server_keys_response( - server_keys: &ServerSigningKeys, + incoming: &IncomingServerKeys, notary: Option<(&ServerName, &[Base64])>, ) -> Result<()> { if let Some((notary_name, notary_keys)) = notary { if !notary_keys.is_empty() { - Self::verify_notary_signature(server_keys, notary_name, notary_keys)?; + Self::verify_notary_signature(incoming, notary_name, notary_keys)?; } } // NOTE: old_verify_keys aren't considered here because old keys can't // be used to sign key responses. let mut set = ruma::signatures::PublicKeySet::new(); - server_keys.verify_keys.iter().for_each(|(key_id, key)| { - set.insert(key_id.to_string(), key.key.clone()); - }); + incoming + .parsed + .verify_keys + .iter() + .for_each(|(key_id, key)| { + set.insert(key_id.to_string(), key.key.clone()); + }); let mut pubkey_map = ruma::signatures::PublicKeyMap::new(); - pubkey_map.insert(server_keys.server_name.to_string(), set); + pubkey_map.insert(incoming.parsed.server_name.to_string(), set); - let mut canonical = to_canonical_object(server_keys)?; - strip_extraneous_signatures(&mut canonical, &server_keys.server_name, &[]); + let mut canonical = to_canonical_object(&incoming.raw)?; + strip_extraneous_signatures(&mut canonical, &incoming.parsed.server_name, &[]); ruma::signatures::verify_json(&pubkey_map, &canonical).map_err(Into::into) } /// Verifies that the notary has at least one valid signature present with /// the provided signing keys. fn verify_notary_signature( - server_keys: &ServerSigningKeys, + incoming: &IncomingServerKeys, notary_name: &ServerName, notary_keys: &[Base64], ) -> Result<()> { @@ -94,18 +123,16 @@ impl super::Service { // certificate has been compromised, which would otherwise allow // them to produce attacker-controlled signing keys with valid // self-signatures. - let Some(notary_signatures) = server_keys.signatures.get(notary_name) else { + let Some(notary_signatures) = incoming.parsed.signatures.get(notary_name) else { return Err!(Request(Forbidden( "Missing notary server signature from {notary_name}" ))); }; - let mut canonical_object = to_canonical_object(notary_signatures)?; - strip_extraneous_signatures(&mut canonical_object, &server_keys.server_name, &[ - notary_name, - ]); - let for_verify = - ruma::signatures::to_canonical_json_string_for_signing(&canonical_object) - .expect("canonical JSON must be stringable"); + // The notary signed the response as the origin served it, so verify + // over the raw JSON, not a re-serialised `ServerSigningKeys`. + let for_verify = ruma::signatures::to_canonical_json_string_for_signing( + &to_canonical_object(&incoming.raw)?, + )?; let raw_notary_keys = notary_keys.iter().map(Base64::as_bytes).collect::>(); let raw_notary_signatures = notary_signatures @@ -125,7 +152,7 @@ impl super::Service { trace!( "Valid signature from {notary_name} present on signing keys response \ for {}", - server_keys.server_name + incoming.parsed.server_name ); return Ok(()); } @@ -180,9 +207,9 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) + Service::verify_server_keys_response(&response_data, None) .expect("Self-signature of real key response is valid"); } @@ -207,9 +234,9 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) + Service::verify_server_keys_response(&response_data, None) .expect("Self-signature of real key response is valid"); } @@ -234,11 +261,11 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); + )).map(Raw::from_json).unwrap().try_into().unwrap(); let starstruck_pubkey = Base64::::parse("Z4oHuEjdUbtC5W/z/gzc5B8raxNk+8gGwbNwgxHqW8Y").unwrap(); Service::verify_server_keys_response( - &response_data.deserialize().unwrap(), + &response_data, Some((server_name!("starstruck.systems"), &[starstruck_pubkey])), ) .expect("Server keys from notary are valid"); @@ -264,8 +291,8 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) + )).map(Raw::from_json).unwrap().try_into().unwrap(); + Service::verify_server_keys_response(&response_data, None) .expect_err("Tampered response should fail self-signature check"); } @@ -302,8 +329,45 @@ mod tests { } } } - )).map(Raw::from_json).unwrap(); - Service::verify_server_keys_response(&response_data.deserialize().unwrap(), None) + )).map(Raw::from_json).unwrap().try_into().unwrap(); + Service::verify_server_keys_response(&response_data, None) .expect_err("Intercepted notary response should fail strict validation"); } + + #[test] + fn verify_response_with_extra_fields() { + let response_data = serde_json::from_value(serde_json::json!( + { + "old_verify_keys": {}, + "server_name": "origin.example", + "signatures": { + "notary.example": { + "ed25519:a_RBdc": "ozlc2T5TlUa9XAsmeam+ESr20573vqFJvYHonj3nG8x+m6v7K5TSlEKTAlTRrJYiC6T/aWB+yxMae6FYR6nqCA" + }, + "origin.example": { + "ed25519:a_jUhC": "+8xKspAfqI8SfrioOVliQ/jCPRDZEuag6JfkN5dXx9gsCX2rSnbvVTJlTJXFiDYUSyIJZg8ilq1QaPsT85ltBA" + } + }, + "tls_fingerprints": [], + "valid_until_ts": 1900000000000_i64, + "verify_keys": { + "ed25519:a_jUhC": { + "key": "idcPtcSpRB5Chnlv1azhL3rMlcTawgQhoGNZWKaNFGI" + } + } + } + )).map(Raw::from_json).unwrap().try_into().unwrap(); + + let notary_pubkey = + Base64::::parse("0ocHGigwa/ap6gSZzzspDQhhOkVkloaf9apolOvwqo8").unwrap(); + + Service::verify_server_keys_response(&response_data, None) + .expect("Self-signature must verify over the raw response"); + + Service::verify_server_keys_response( + &response_data, + Some((server_name!("notary.example"), &[notary_pubkey])), + ) + .expect("Notary signature must verify over the raw response"); + } } diff --git a/src/service/services.rs b/src/service/services.rs index b2cd60b1b..79a1ced78 100644 --- a/src/service/services.rs +++ b/src/service/services.rs @@ -11,8 +11,8 @@ use crate::{ account_data, admin, announcements, antispam, appservice, client, config, emergency, federation, firstrun, globals, key_backups, mailer, manager::Manager, - media, moderation, oauth, oidc, presence, pusher, registration_tokens, rooms, sending, - server_keys, + media, moderation, oauth, oidc, presence, pusher, registration_tokens, rendezvous, rooms, + sending, server_keys, service::{self, Args, Map, Service}, sync, threepid, transactions, uiaa, users, }; @@ -33,6 +33,7 @@ pub struct Services { pub presence: Arc, pub pusher: Arc, pub registration_tokens: Arc, + pub rendezvous: Arc, pub rooms: rooms::Service, pub federation: Arc, pub firstrun: Arc, @@ -89,6 +90,7 @@ impl Services { presence: build!(presence::Service), pusher: build!(pusher::Service), registration_tokens: build!(registration_tokens::Service), + rendezvous: build!(rendezvous::Service), rooms: rooms::Service { alias: build!(rooms::alias::Service), auth_chain: build!(rooms::auth_chain::Service), @@ -142,13 +144,8 @@ impl Services { super::migrations::migrations(self) .await .inspect_err(|e| error!("Migrations failed: {e}"))?; - self.manager - .lock() - .await - .insert(Manager::new(self)) - .clone() - .start() - .await?; + let manager = self.manager.lock().await.insert(Manager::new(self)).clone(); + manager.start().await?; // reset dormant online/away statuses to offline, and set the server // user as online @@ -177,7 +174,8 @@ impl Services { } self.interrupt(); - if let Some(manager) = self.manager.lock().await.as_ref() { + let manager = self.manager.lock().await.clone(); + if let Some(manager) = manager { manager.stop().await; } @@ -187,7 +185,8 @@ impl Services { } pub async fn poll(&self) -> Result<()> { - if let Some(manager) = self.manager.lock().await.as_ref() { + let manager = self.manager.lock().await.clone(); + if let Some(manager) = manager { return manager.poll().await; } diff --git a/src/service/state.rs b/src/service/state.rs index 9f18ad73a..61234a4e6 100644 --- a/src/service/state.rs +++ b/src/service/state.rs @@ -11,7 +11,15 @@ pub struct Guard { services: Arc, } -pub fn create(services: Arc) -> (State, Guard) { +/// Create a raw-pointer `State` handle paired with a `Guard` that keeps +/// `Services` alive. +/// +/// # Safety +/// `State` is `Copy` and dereferences its raw pointer without reference +/// counting. The caller must ensure that no `State` (nor any copy of it) is +/// dereferenced after `Guard` and all other `Arc` clones have been +/// dropped. +pub unsafe fn create(services: Arc) -> (State, Guard) { let state = State { services: Arc::into_raw(services.clone()), }; diff --git a/src/service/sync/mod.rs b/src/service/sync/mod.rs index 5b50b38de..46e56894b 100644 --- a/src/service/sync/mod.rs +++ b/src/service/sync/mod.rs @@ -6,9 +6,10 @@ use std::{ use conduwuit::{Result, SyncMutex, trace}; use futures::StreamExt; use ruma::{ - OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, api::client::sync::sync_events::v5, + OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId, + api::client::sync::sync_events::msc4186, }; -use tokio::sync::{Mutex, watch}; +use tokio::sync::watch; use crate::{Dep, rooms}; @@ -24,21 +25,32 @@ struct Services { #[allow(unused, reason = "TODO refactor")] struct SlidingSyncCache { - lists: BTreeMap, - subscriptions: BTreeMap, + lists: BTreeMap, + subscriptions: BTreeMap, // For every room, the roomsince number known_rooms: BTreeMap>, - extensions: v5::request::Extensions, + extensions: msc4186::request::Extensions, } +/// For every in-scope room, the stream position up to which sticky events +/// have been delivered on this connection. +pub type StickyDelivered = BTreeMap; + #[derive(Default)] struct SnakeSyncCache { - lists: BTreeMap, - subscriptions: BTreeMap, + lists: BTreeMap, + subscriptions: BTreeMap, known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, acknowledged_pos: u64, - pending: BTreeMap>>, - extensions: v5::request::Extensions, + pending: BTreeMap, + extensions: msc4186::request::Extensions, +} + +#[derive(Default)] +struct PendingState { + known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, } impl SnakeSyncCache { @@ -47,13 +59,19 @@ impl SnakeSyncCache { } fn acknowledge(&mut self, pos: u64) { - if let Some(known_rooms) = self.pending.remove(&pos) { - self.known_rooms = known_rooms; + if let Some(pending) = self.pending.remove(&pos) { + self.known_rooms = pending.known_rooms; + self.sticky_delivered = pending.sticky_delivered; self.acknowledged_pos = pos; } } - fn stage_pending(&mut self, pos: u64, known_rooms: BTreeMap>) { + fn stage_pending( + &mut self, + pos: u64, + known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, + ) { let mut pending_rooms = self.known_rooms.clone(); for (list_id, rooms) in known_rooms { let list = pending_rooms.entry(list_id).or_default(); @@ -61,7 +79,10 @@ impl SnakeSyncCache { list.insert(room_id, pos); } } - self.pending.insert(pos, pending_rooms); + self.pending.insert(pos, PendingState { + known_rooms: pending_rooms, + sticky_delivered, + }); } } @@ -71,28 +92,27 @@ pub type SnakeConnectionsKey = (OwnedUserId, OwnedDeviceId, Option); type SnakeConnectionsVal = Arc>; #[derive(Default)] -struct Wakers(Mutex>>); +struct Wakers(SyncMutex>>); impl Wakers { - async fn subscribe(&self, user: &UserId) -> watch::Receiver { + fn subscribe(&self, user: &UserId) -> watch::Receiver { self.0 .lock() - .await .entry(user.to_owned()) .or_insert_with(|| watch::channel(0).0) .subscribe() } - async fn wake(&self, user: &UserId) { - let mut wakers = self.0.lock().await; + fn wake(&self, user: &UserId) { + let mut wakers = self.0.lock(); wake_waker(&mut wakers, user); } - async fn wake_all(&self, users: I) + fn wake_all(&self, users: I) where - I: IntoIterator + Send, + I: IntoIterator, { - let mut wakers = self.0.lock().await; + let mut wakers = self.0.lock(); for user in users { wake_waker(&mut wakers, &user); } @@ -129,8 +149,8 @@ impl crate::Service for Service { } impl Service { - pub async fn subscribe_to_wake(&self, user: &UserId) -> watch::Receiver { - self.wakers.subscribe(user).await + pub fn subscribe_to_wake(&self, user: &UserId) -> watch::Receiver { + self.wakers.subscribe(user) } /// Wake the target user's sync loop. Call this when something @@ -143,7 +163,7 @@ impl Service { pub async fn wake(&self, user: &UserId) { trace!(?user, "Waking user's sync loops"); - self.wakers.wake(user).await; + self.wakers.wake(user); } /// Wake all of our users who are joined to the specified room. @@ -156,7 +176,7 @@ impl Service { .collect() .await; - self.wakers.wake_all(users).await; + self.wakers.wake_all(users); } pub fn snake_connection_cached(&self, key: &SnakeConnectionsKey) -> bool { @@ -178,8 +198,8 @@ impl Service { &self, snake_key: &SnakeConnectionsKey, pos: u64, - request: &mut v5::Request, - ) -> BTreeMap> { + request: &mut msc4186::Request, + ) -> (BTreeMap>, StickyDelivered) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( cache @@ -191,7 +211,7 @@ impl Service { cached.acknowledge(pos); - //v5::Request::try_from_http_request(req, path_args); + //msc4186::Request::try_from_http_request(req, path_args); for (list_id, list) in &mut request.lists { if let Some(cached_list) = cached.lists.get(list_id) { list_or_sticky( @@ -225,18 +245,6 @@ impl Service { .room_subscriptions .extend(cached.subscriptions.clone()); - request.extensions.e2ee.enabled = request - .extensions - .e2ee - .enabled - .or(cached.extensions.e2ee.enabled); - - request.extensions.to_device.enabled = request - .extensions - .to_device - .enabled - .or(cached.extensions.to_device.enabled); - request.extensions.account_data.enabled = request .extensions .account_data @@ -276,9 +284,25 @@ impl Service { &mut request.extensions.receipts.lists, cached.extensions.receipts.lists.clone(), ); + some_or_sticky( + &mut request.extensions.sticky_events.enabled, + cached.extensions.sticky_events.enabled, + ); + some_or_sticky( + &mut request.extensions.sticky_events.limit, + cached.extensions.sticky_events.limit, + ); + some_or_sticky( + &mut request.extensions.sticky_events.rooms, + cached.extensions.sticky_events.rooms.clone(), + ); + some_or_sticky( + &mut request.extensions.sticky_events.lists, + cached.extensions.sticky_events.lists.clone(), + ); cached.extensions = request.extensions.clone(); - cached.known_rooms.clone() + (cached.known_rooms.clone(), cached.sticky_delivered.clone()) } pub fn store_snake_sync_pending( @@ -286,6 +310,7 @@ impl Service { key: &SnakeConnectionsKey, pos: u64, known_rooms: BTreeMap>, + sticky_delivered: StickyDelivered, ) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( @@ -296,13 +321,13 @@ impl Service { let cached = &mut cached.lock(); drop(cache); - cached.stage_pending(pos, known_rooms); + cached.stage_pending(pos, known_rooms, sticky_delivered); } pub fn update_snake_sync_subscriptions( &self, key: &SnakeConnectionsKey, - subscriptions: BTreeMap, + subscriptions: BTreeMap, ) { let mut cache = self.snake_connections.lock(); let cached = Arc::clone( @@ -359,11 +384,11 @@ mod tests { async fn wake_after_subscription_is_observable() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut receiver = wakers.subscribe(&user).await; + let mut receiver = wakers.subscribe(&user); let generation = *receiver.borrow_and_update(); - wakers.wake(&user).await; - wakers.wake(&user).await; + wakers.wake(&user); + wakers.wake(&user); receiver.changed().await.unwrap(); assert_eq!(*receiver.borrow_and_update(), generation.wrapping_add(2)); @@ -373,10 +398,10 @@ mod tests { async fn wake_notifies_all_subscribers() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut first = wakers.subscribe(&user).await; - let mut second = wakers.subscribe(&user).await; + let mut first = wakers.subscribe(&user); + let mut second = wakers.subscribe(&user); - wakers.wake(&user).await; + wakers.wake(&user); first.changed().await.unwrap(); second.changed().await.unwrap(); @@ -387,24 +412,24 @@ mod tests { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - wakers.wake(&user).await; - assert!(wakers.0.lock().await.is_empty()); + wakers.wake(&user); + assert!(wakers.0.lock().is_empty()); - drop(wakers.subscribe(&user).await); - assert_eq!(wakers.0.lock().await.len(), 1); + drop(wakers.subscribe(&user)); + assert_eq!(wakers.0.lock().len(), 1); - wakers.wake(&user).await; - assert!(wakers.0.lock().await.is_empty()); + wakers.wake(&user); + assert!(wakers.0.lock().is_empty()); } #[tokio::test] async fn subscriber_still_woken_after_a_sibling_disconnects() { let wakers = Wakers::default(); let user = UserId::parse("@alice:example.com").unwrap(); - let mut receiver = wakers.subscribe(&user).await; - drop(wakers.subscribe(&user).await); + let mut receiver = wakers.subscribe(&user); + drop(wakers.subscribe(&user)); - wakers.wake(&user).await; + wakers.wake(&user); receiver.changed().await.unwrap(); } @@ -413,10 +438,13 @@ mod tests { fn pending_rooms_are_committed_only_when_the_response_pos_is_acknowledged() { let room_id = OwnedRoomId::try_from("!room:example.com").unwrap(); let mut cache = SnakeSyncCache { - pending: BTreeMap::from([( - 42, - BTreeMap::from([("list".to_owned(), BTreeMap::from([(room_id, 42)]))]), - )]), + pending: BTreeMap::from([(42, PendingState { + known_rooms: BTreeMap::from([( + "list".to_owned(), + BTreeMap::from([(room_id, 42)]), + )]), + sticky_delivered: StickyDelivered::new(), + })]), ..Default::default() }; @@ -439,7 +467,11 @@ mod tests { let dropped = OwnedRoomId::try_from("!dropped:example.com").unwrap(); let mut cache = SnakeSyncCache::default(); let stage = |cache: &mut SnakeSyncCache, pos, rooms: BTreeSet| { - cache.stage_pending(pos, BTreeMap::from([("all_rooms".to_owned(), rooms)])); + cache.stage_pending( + pos, + BTreeMap::from([("all_rooms".to_owned(), rooms)]), + StickyDelivered::new(), + ); cache.acknowledge(pos); }; @@ -459,7 +491,10 @@ mod tests { fn overlapping_responses_accept_either_response_position() { let mut cache = SnakeSyncCache { acknowledged_pos: 100, - pending: BTreeMap::from([(200, BTreeMap::new()), (201, BTreeMap::new())]), + pending: BTreeMap::from([ + (200, PendingState::default()), + (201, PendingState::default()), + ]), ..Default::default() }; diff --git a/src/service/test_utils.rs b/src/service/test_utils.rs new file mode 100644 index 000000000..e71fd2959 --- /dev/null +++ b/src/service/test_utils.rs @@ -0,0 +1,52 @@ +use std::{path::PathBuf, sync::Arc}; + +use conduwuit::{ + Config, Server, + log::{Log, LogLevelReloadHandles}, + metrics::Metrics, +}; +use serde_json::json; +use tokio::sync::{Mutex, MutexGuard}; + +/// RocksDB's default `Env` is shared by the whole process and closing a +/// database stops its background threads, so tests must not keep databases +/// open in parallel. Hold the returned guard until the services are dropped. +static DATABASE: Mutex<()> = Mutex::const_new(()); + +type TestServices = (Arc, PathBuf, MutexGuard<'static, ()>); + +pub(crate) async fn test_services() -> TestServices { test_services_with(json!({})).await } + +pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices { + let guard = DATABASE.lock().await; + let _ = rustls::crypto::ring::default_provider().install_default(); + let path = std::env::temp_dir() + .join(format!("continuwuity-shared-state-{:016x}", rand::random::())); + std::fs::create_dir(&path).unwrap(); + let mut config = json!({ + "server_name": "test.example", + "database_path": path, + "db_cache_capacity_mb": 16.0, + "rocksdb_write_buffer_capacity_mb": 4.0, + "allow_local_presence": false, + "dns_servers": ["127.0.0.1"], + "allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true + }); + config + .as_object_mut() + .unwrap() + .extend(overrides.as_object().unwrap().clone()); + let config: Config = serde_json::from_value(config).unwrap(); + let runtime = tokio::runtime::Handle::current(); + let server = Arc::new(Server::new( + config, + Some(runtime.clone()), + Log { + reload: LogLevelReloadHandles::default(), + capture: Arc::default(), + }, + Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None), + )); + let services = crate::Services::build(server).await.unwrap(); + (services, path, guard) +} diff --git a/src/service/threepid/mod.rs b/src/service/threepid/mod.rs index db0d08d9f..ea39ef552 100644 --- a/src/service/threepid/mod.rs +++ b/src/service/threepid/mod.rs @@ -1,6 +1,8 @@ use std::{borrow::Cow, collections::HashMap, sync::Arc}; -use conduwuit::{Err, Error, Result, config::OidcProfileKeyImportMode, result::FlatOk}; +use conduwuit::{ + Err, Error, Result, SyncMutex, config::OidcProfileKeyImportMode, result::FlatOk, +}; use database::{Deserialized, Map}; use governor::{DefaultKeyedRateLimiter, Quota, RateLimiter}; use lettre::{Address, message::Mailbox}; @@ -9,7 +11,6 @@ use ruma::{ ClientSecret, OwnedClientSecret, OwnedSessionId, SessionId, api::error::{ErrorKind, LimitExceededErrorData}, }; -use tokio::sync::MutexGuard; pub mod session; @@ -22,8 +23,8 @@ use crate::{ pub struct Service { db: Data, services: Services, - sessions: tokio::sync::Mutex, - send_attempts: std::sync::Mutex>, + sessions: SyncMutex, + send_attempts: SyncMutex>, ratelimiter: DefaultKeyedRateLimiter
, } @@ -71,8 +72,8 @@ impl crate::Service for Service { config: args.depend("config"), mailer: args.depend("mailer"), }, - sessions: tokio::sync::Mutex::default(), - send_attempts: std::sync::Mutex::default(), + sessions: SyncMutex::default(), + send_attempts: SyncMutex::default(), ratelimiter: RateLimiter::keyed(Self::EMAIL_RATELIMIT), })) } @@ -121,64 +122,69 @@ impl Service { send_attempt: usize, ) -> Result { let mailer = self.services.mailer.expect_mailer()?; - let mut sessions = self.sessions.lock().await; + let (session_id, token_str) = { + let mut sessions = self.sessions.lock(); - let session = match sessions.get_session_by_client_secret(client_secret) { - // If a validation session already exists for this client secret, we can either - // reuse it with a new token or return early because it's already valid. - | Some(session) => { - if session.email != recipient.email { - return Err!(Request(InvalidParam("Wrong email for session."))); - } + let session = match sessions.get_session_by_client_secret(client_secret) { + // If a validation session already exists for this client + // secret, we can either reuse it with a new token or return + // early because it's already valid. + | Some(session) => { + if session.email != recipient.email { + return Err!(Request(InvalidParam("Wrong email for session."))); + } - match session.validation_state { - | ValidationState::Validated => { - // If the existing session is already valid, don't send - // an email. - return Ok(session.session_id.clone()); - }, - | ValidationState::Pending(ref mut token) => { - // Check ratelimiting for the target address. - if self.ratelimiter.check_key(&session.email).is_err() { - return Err(Error::BadRequest( - ErrorKind::LimitExceeded(LimitExceededErrorData::new()), - "You're sending emails too fast, try again in a few minutes.", - )); - } - - // Check the send attempt for this session. - let mut send_attempts = self.send_attempts.lock().unwrap(); - - let last_send_attempt = send_attempts - .entry((session.client_secret.clone(), session.email.clone())) - .or_default(); - - if send_attempt <= *last_send_attempt { - // If the supplied send attempt isn't higher than - // the last one, don't send an email. + match session.validation_state { + | ValidationState::Validated => { + // If the existing session is already valid, don't + // send an email. return Ok(session.session_id.clone()); - } + }, + | ValidationState::Pending(ref mut token) => { + // Check ratelimiting for the target address. + if self.ratelimiter.check_key(&session.email).is_err() { + return Err(Error::BadRequest( + ErrorKind::LimitExceeded(LimitExceededErrorData::new()), + "You're sending emails too fast, try again in a few minutes.", + )); + } - // Save this send attempt. - *last_send_attempt = send_attempt; - drop(send_attempts); + // Check the send attempt for this session. + let mut send_attempts = self.send_attempts.lock(); - // Create a new token for the existing session. - *token = ValidationToken::new_random(); + let last_send_attempt = send_attempts + .entry((session.client_secret.clone(), session.email.clone())) + .or_default(); - session - }, - } - }, - // If no session exists, create a new one. - | None => sessions.create_session(recipient.email.clone(), client_secret.to_owned()), - }; + if send_attempt <= *last_send_attempt { + // If the supplied send attempt isn't higher + // than the last + // one, don't send an email. + return Ok(session.session_id.clone()); + } - // Clone this so it can outlive the lock we're holding on `sessions` - let session_id = session.session_id.clone(); + // Save this send attempt. + *last_send_attempt = send_attempt; + drop(send_attempts); - let ValidationState::Pending(token) = &session.validation_state else { - unreachable!("session should be pending") + // Create a new token for the existing session. + *token = ValidationToken::new_random(); + + session + }, + } + }, + // If no session exists, create a new one. + | None => + sessions.create_session(recipient.email.clone(), client_secret.to_owned()), + }; + + let session_id = session.session_id.clone(); + let ValidationState::Pending(token) = &session.validation_state else { + unreachable!("session should be pending") + }; + + (session_id, token.token.clone()) }; let mut validation_url = self @@ -191,11 +197,7 @@ impl Service { validation_url .query_pairs_mut() .append_pair("session", session_id.as_str()) - .append_pair("token", &token.token); - - // Once the validation URL is built, we don't need any data borrowed - // from `sessions` anymore and can release our lock - drop(sessions); + .append_pair("token", &token_str); let message = prepare_body(validation_url.to_string()); @@ -205,12 +207,12 @@ impl Service { } /// Attempt to mark a validation session as valid using a validation token. - pub async fn try_validate_session( + pub fn try_validate_session( &self, session_id: &SessionId, supplied_token: &str, ) -> Result<(), Cow<'static, str>> { - let mut sessions = self.sessions.lock().await; + let mut sessions = self.sessions.lock(); let Some(session) = sessions.get_session(session_id) else { return Err("Validation session does not exist".into()); @@ -239,12 +241,12 @@ impl Service { } /// Get a validated validation session. - pub async fn get_valid_session( + pub fn get_valid_session( &self, session_id: &SessionId, client_secret: &ClientSecret, ) -> Result, Cow<'static, str>> { - let mut sessions = self.sessions.lock().await; + let mut sessions = self.sessions.lock(); let Some(session) = sessions.get_session(session_id) else { return Err("Validation session does not exist".into()); @@ -258,7 +260,7 @@ impl Service { Ok(ValidSession { email, session_id: session_id.to_owned(), - sessions, + service: self, }) } else { Err("This email address has not been validated. Did you use the link that was sent \ @@ -336,18 +338,21 @@ impl Service { } } -pub struct ValidSession<'lock> { +pub struct ValidSession<'a> { pub email: Address, session_id: OwnedSessionId, - sessions: MutexGuard<'lock, ValidationSessions>, + service: &'a Service, } impl ValidSession<'_> { /// Consume this session, removing it from the database and releasing the /// lock it holds. #[must_use] - pub fn consume(mut self) -> Address { - self.sessions.remove_session(&self.session_id); + pub fn consume(self) -> Address { + self.service + .sessions + .lock() + .remove_session(&self.session_id); self.email } diff --git a/src/service/transactions/mod.rs b/src/service/transactions/mod.rs index 094317c8b..9664abd00 100644 --- a/src/service/transactions/mod.rs +++ b/src/service/transactions/mod.rs @@ -143,7 +143,7 @@ impl Service { ) { let mut key = user_id.as_bytes().to_vec(); key.push(0xFF); - key.extend_from_slice(device_id.map(DeviceId::as_bytes).unwrap_or_default()); + key.extend_from_slice(device_id.map_or_default(DeviceId::as_bytes)); key.push(0xFF); key.extend_from_slice(txn_id.as_bytes()); diff --git a/src/service/uiaa/mod.rs b/src/service/uiaa/mod.rs index f78bbe923..96a92eb0f 100644 --- a/src/service/uiaa/mod.rs +++ b/src/service/uiaa/mod.rs @@ -278,8 +278,6 @@ impl Service { params: Box, initiator: Option>, ) -> Result { - let mut uiaa_sessions = self.uiaa_sessions.lock().await; - let session_id = utils::random_string(Self::SESSION_ID_LENGTH); let mut info = assign!(UiaaInfo::new(flows), { params: Some(params), session: Some(session_id.clone()) }); @@ -355,7 +353,10 @@ impl Service { ))); } - uiaa_sessions.insert(session_id, UiaaSession { session_metadata, info: info.clone() }); + self.uiaa_sessions + .lock() + .await + .insert(session_id, UiaaSession { session_metadata, info: info.clone() }); Ok(info) } @@ -492,31 +493,24 @@ impl Service { | AuthData::EmailIdentity(EmailIdentity { thirdparty_id_creds: ThirdpartyIdCredentials { client_secret, sid, .. }, .. - }) => { - match self - .services - .threepid - .get_valid_session(sid, client_secret) - .await - { - | Ok(session) => { - let email = session.consume(); + }) => match self.services.threepid.get_valid_session(sid, client_secret) { + | Ok(session) => { + let email = session.consume(); - if let Some(localpart) = - self.services.threepid.get_localpart_for_email(&email).await - { - identity.try_set_localpart(localpart)?; - } + if let Some(localpart) = + self.services.threepid.get_localpart_for_email(&email).await + { + identity.try_set_localpart(localpart)?; + } - identity.try_set_email(email)?; + identity.try_set_email(email)?; - Ok(AuthType::EmailIdentity) - }, - | Err(message) => Err(StandardErrorBody::new( - ErrorKind::ThreepidAuthFailed, - message.into_owned(), - )), - } + Ok(AuthType::EmailIdentity) + }, + | Err(message) => Err(StandardErrorBody::new( + ErrorKind::ThreepidAuthFailed, + message.into_owned(), + )), }, #[allow(clippy::useless_let_if_seq)] | AuthData::Password(Password { identifier, password, .. }) => { diff --git a/src/service/users/account.rs b/src/service/users/account.rs index 39cadab32..3c5f1486c 100644 --- a/src/service/users/account.rs +++ b/src/service/users/account.rs @@ -4,7 +4,9 @@ use std::{ }; use conduwuit::{ - Err, Result, debug, debug_error, debug_warn, err, error, info, trace, + Err, Result, + config::experiments::ToggledExperiment, + debug, debug_error, debug_warn, err, error, info, trace, utils::{self, stream::TryIgnore}, warn, }; @@ -107,6 +109,27 @@ impl super::Service { if stable.is_err() && unstable.is_err() { return FilterLevel::Default; } + let msc4494_enabled = self.services.config.experiments.msc4494.is_enabled(); + if !self.services.config.experiments.msc4155.is_enabled() { + // Only MSC4380 should be checked here, since it's in spec. + let Some(action) = stable.ok().and_then(|c| c.content.default_action) else { + return FilterLevel::Default; + }; + return match action { + | InvitePermissionAction::Block => FilterLevel::Block, + | InvitePermissionAction::DenyPublic if msc4494_enabled => { + if !self + .check_msc4494_mutual_room(sender_user, recipient_user) + .await + { + FilterLevel::Block + } else { + FilterLevel::Default + } + }, + | _ => FilterLevel::Allow, + }; + } let content = stable.unwrap_or_else(|_| unstable.unwrap()).content; let verdict = content.user_filter_level(sender_user); if verdict != FilterLevel::Default { @@ -114,7 +137,8 @@ impl super::Service { } // Apply other layers of invite blocking first, so that user/server // denies take priority over implicit allows. - if content.default_action == Some(InvitePermissionAction::DenyPublic) + if msc4494_enabled + && content.default_action == Some(InvitePermissionAction::DenyPublic) && !self .check_msc4494_mutual_room(sender_user, recipient_user) .await @@ -405,11 +429,7 @@ impl super::Service { "Username is not in this appservice's namespace." ))); } - } else if self - .services - .appservice - .is_exclusive_user_id(&user_id) - .await + } else if self.services.appservice.is_exclusive_user_id(&user_id) && !emergency_mode_enabled { return Err!(Request(Exclusive("Username is reserved by an appservice."))); diff --git a/src/service/users/dehydrated_device.rs b/src/service/users/dehydrated_device.rs index 83ab1b343..065d9013e 100644 --- a/src/service/users/dehydrated_device.rs +++ b/src/service/users/dehydrated_device.rs @@ -3,7 +3,7 @@ use conduwuit_database::{Deserialized, Json}; use ruma::{ DeviceId, OwnedDeviceId, UserId, api::client::dehydrated_device::{ - DehydratedDeviceData, put_dehydrated_device::unstable::Request, + DehydratedDeviceData, put_dehydrated_device::msc3814::Request, }, serde::Raw, }; diff --git a/src/service/users/device.rs b/src/service/users/device.rs index f5f40c57c..be666d7ca 100644 --- a/src/service/users/device.rs +++ b/src/service/users/device.rs @@ -175,13 +175,7 @@ impl super::Service { } // Check for token collision with appservices - if self - .services - .appservice - .find_from_token(&token) - .await - .is_ok() - { + if self.services.appservice.find_from_token(&token).is_ok() { return Err!(Request(InvalidParam( "Token conflicts with an existing appservice token" ))); @@ -222,17 +216,19 @@ impl super::Service { event_type: &str, content: serde_json::Value, ) { - let count = self.services.globals.next_count().unwrap(); - - let key = (target_user_id, target_device_id, count); - self.db.todeviceid_events.put( - key, - Json(json!({ - "type": event_type, - "sender": sender, - "content": content, - })), - ); + let event = Json(json!({ + "type": event_type, + "sender": sender, + "content": content, + })); + self.services + .globals + .next_count_with(|count| { + self.db + .todeviceid_events + .put((target_user_id, target_device_id, count), event); + }) + .unwrap(); self.services.sync.wake(target_user_id).await; } diff --git a/src/service/users/keys.rs b/src/service/users/keys.rs index 2f0227d14..682bfb02b 100644 --- a/src/service/users/keys.rs +++ b/src/service/users/keys.rs @@ -442,9 +442,8 @@ impl super::Service { /// Marks that a user's device keys have been updated, so that other users /// can be notified of the change. pub async fn mark_device_key_update(&self, user_id: &UserId) { - let count = self.services.globals.next_count().unwrap(); - - self.services + let encrypted_rooms: Vec<_> = self + .services .state_cache .rooms_joined(user_id) // Don't send key updates to unencrypted rooms @@ -460,16 +459,26 @@ impl super::Service { None } }) - .for_each(async |room_id| { - let key = (&room_id, count); - self.db.keychangeid_userid.put_raw(key, user_id); - - self.services.sync.wake_all_joined(&room_id).await; - }) + .collect() .await; - let key = (user_id, count); - self.db.keychangeid_userid.put_raw(key, user_id); + self.services + .globals + .next_count_with(|count| { + self.db + .keychangeid_userid + .put_raw((user_id, count), user_id); + for room_id in &encrypted_rooms { + self.db + .keychangeid_userid + .put_raw((room_id, count), user_id); + } + }) + .unwrap(); + + for room_id in &encrypted_rooms { + self.services.sync.wake_all_joined(room_id).await; + } } /// Returns the device identity keys for a given device. diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs index 09ade8a97..c02ff8647 100644 --- a/src/service/users/mod.rs +++ b/src/service/users/mod.rs @@ -9,10 +9,7 @@ pub(super) mod remote; use std::{mem, sync::Arc}; pub use account::{AccessTokenStatus, AccountStatus}; -use conduwuit::{ - Err, Error, Result, err, - utils::{self}, -}; +use conduwuit::{Err, Error, Result, err, utils}; use database::Map; pub use device::DeviceToken; pub use profile::ProfileFieldChange; diff --git a/src/service/users/profile.rs b/src/service/users/profile.rs index 954b0eac4..cad67765c 100644 --- a/src/service/users/profile.rs +++ b/src/service/users/profile.rs @@ -51,12 +51,8 @@ impl super::Service { let field_name = change.field_name(); - // TODO: The spec mentions special error codes (M_PROFILE_TOO_LARGE, - // M_KEY_TOO_LARGE) for profile field size limits, but they're not in - // its list of error codes and Ruma doesn't have them. Should we - // return those, or is M_TOO_LARGE okay? if field_name.as_str().len() > MAX_KEY_LENGTH_BYTES { - return Err!(Request(TooLarge( + return Err!(Request(KeyTooLarge( "Individual profile keys must not exceed {MAX_KEY_LENGTH_BYTES} bytes in length." ))); } @@ -84,10 +80,10 @@ impl super::Service { .len() > MAX_PROFILE_LENGTH_BYTES { - return Err!( + return Err!(Request(ProfileTooLarge( "Profile data must not exceed {MAX_PROFILE_LENGTH_BYTES} bytes in \ length." - ); + ))); } } else { return Err!(Request(BadJson("Failed to canonicalize profile."))); diff --git a/src/web/Cargo.toml b/src/web/Cargo.toml index c40c461e6..dd7187de9 100644 --- a/src/web/Cargo.toml +++ b/src/web/Cargo.toml @@ -30,7 +30,7 @@ conduwuit-service.workspace = true form_urlencoded = "1.2.2" futures.workspace = true lettre.workspace = true -memory-serve = "2.1.0" +memory-serve = "2.4.0" openidconnect.workspace = true ruma.workspace = true serde.workspace = true @@ -38,7 +38,7 @@ serde_json.workspace = true serde_urlencoded.workspace = true thiserror.workspace = true tower-http.workspace = true -tower-sec-fetch = { features = ["tracing"], version = "0.1.2" } +tower-sec-fetch = { features = ["tracing"], version = "0.2.0" } tower-sessions = { default-features = false, features = [ "axum-core", ], version = "0.15.0" } @@ -48,17 +48,17 @@ url.workspace = true validator = { version = "0.21.0", features = ["derive"] } [build-dependencies] -memory-serve = "2.1.0" +memory-serve = "2.4.0" [lints] workspace = true [package.metadata.cargo-shear] +# All of these dependencies are only used in Askama templates, +# which are transformed into Rust by a proc macro. +# cargo-shear can't see them because it doesn't expand macros. ignored = [ "conduwuit_build_metadata", "form_urlencoded", - "reqwest_recaptcha", "serde_json", - "tower-sessions-core", - "tracing", ] diff --git a/src/web/mod.rs b/src/web/mod.rs index ac881c26b..5593ac017 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -11,7 +11,8 @@ use axum::{ use conduwuit_service::{Services, state}; use tower_http::catch_panic::CatchPanicLayer; use tower_sec_fetch::SecFetchLayer; -use tower_sessions::{ExpiredDeletion, SessionManagerLayer, cookie::SameSite}; +use tower_sessions::{SessionManagerLayer, cookie::SameSite}; +use tower_sessions_core::ExpiredDeletion; use crate::{ pages::TemplateContext, @@ -94,7 +95,8 @@ impl IntoResponse for WebError { error: self, status, context: TemplateContext { - // Statically set false to prevent error pages from being indexed. + // Statically set false to prevent error pages from being + // indexed. allow_indexing: false, csp_nonce: String::new(), }, diff --git a/src/web/pages/account/email.rs b/src/web/pages/account/email.rs index 1d9ca64b2..bace631df 100644 --- a/src/web/pages/account/email.rs +++ b/src/web/pages/account/email.rs @@ -167,7 +167,6 @@ async fn get_change_email_validate( let Ok(session) = services .threepid .get_valid_session(&session_id, &client_secret) - .await else { return response!(ChangeEmailValidate::new( context, diff --git a/src/web/pages/account/password/reset.rs b/src/web/pages/account/password/reset.rs index 20b2732d9..917c86cc9 100644 --- a/src/web/pages/account/password/reset.rs +++ b/src/web/pages/account/password/reset.rs @@ -189,7 +189,6 @@ async fn route_reset_password_validate( let body = match services .threepid .get_valid_session(&query.threepid.session_id, &query.threepid.client_secret) - .await { | Ok(session) => { let Some(localpart) = services diff --git a/src/web/pages/account/register.rs b/src/web/pages/account/register.rs index 5abff481e..0bd686adb 100644 --- a/src/web/pages/account/register.rs +++ b/src/web/pages/account/register.rs @@ -289,7 +289,6 @@ async fn get_register_email_validate( let Ok(session) = services .threepid .get_valid_session(&session_id, &client_secret) - .await else { return response!(RegisterEmailValidate::new(context, session_id, client_secret, true)); }; @@ -314,6 +313,7 @@ async fn get_register_email_validate( Some(email), &client ) + .boxed() .await? ) } @@ -505,6 +505,7 @@ async fn begin_registration( // If email isn't required we can immediately complete registration Ok(response!( complete_registration(services, session_store, completed_registration, None, client) + .boxed() .await? )) } diff --git a/src/web/pages/components/form.rs b/src/web/pages/components/form.rs index 55b07bda3..4880efd6c 100644 --- a/src/web/pages/components/form.rs +++ b/src/web/pages/components/form.rs @@ -48,11 +48,12 @@ pub(crate) struct FormInput<'a> { pub autocomplete: &'a str, // This is a hack to make the form! macro's support for client-only fields - // work properly. Client-only fields are specified in the macro without a type and aren't - // included in the POST body or as a field in the generated struct. - // To keep the field from being included in the POST body, its `name` property needs not to - // be set in the template. Because of limitations of macro_rules!'s repetition feature, this - // field needs to exist to allow the template to check if the field is client-only. + // work properly. Client-only fields are specified in the macro without a + // type and aren't included in the POST body or as a field in the generated + // struct. To keep the field from being included in the POST body, its + // `name` property needs not to be set in the template. Because of + // limitations of macro_rules!'s repetition feature, this field needs to + // exist to allow the template to check if the field is client-only. #[doc(hidden)] pub type_name: Option<&'static str>, } diff --git a/src/web/pages/mod.rs b/src/web/pages/mod.rs index a9c169810..28a442785 100644 --- a/src/web/pages/mod.rs +++ b/src/web/pages/mod.rs @@ -61,9 +61,10 @@ pub(super) async fn template_context_middleware( response.headers_mut().insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_str(&format!( - // TODO: `unsafe-inline` for `style-src` defeats the purpose of having it, but - // it's necessary to set CSS variables using the `style` attribute without - // JavaScript. Come back to this once there's a less shitty solution. + // TODO: `unsafe-inline` for `style-src` defeats the purpose of + // having it, but it's necessary to set CSS variables using the + // `style` attribute without JavaScript. Come back to this once + // there's a less shitty solution. "default-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; \ script-src 'nonce-{csp_nonce}'; child-src {child_src};" )) diff --git a/src/web/pages/oauth/grant.rs b/src/web/pages/oauth/grant.rs index bde0b7d48..1cb268102 100644 --- a/src/web/pages/oauth/grant.rs +++ b/src/web/pages/oauth/grant.rs @@ -242,7 +242,6 @@ async fn route_device_code( services .oauth .validate_device_code(user_id, &device_code) - .await .map_err(WebError::BadRequest)?; response!(DeviceCodeGrant::new(context, user_card, DeviceCodeGrantBody::Success)) diff --git a/src/web/pages/oidc/complete.rs b/src/web/pages/oidc/complete.rs index 32a0d342d..f2e116eb8 100644 --- a/src/web/pages/oidc/complete.rs +++ b/src/web/pages/oidc/complete.rs @@ -6,6 +6,7 @@ use axum::{ response::Redirect, routing::on, }; +use conduwuit_api::client_ip::ClientIp; use conduwuit_service::{ oauth::grant::AuthorizationCodeResponse, oidc::{ClaimedLocalUser, SessionCompletionStatus}, @@ -63,6 +64,7 @@ async fn route_complete( Expect(Query(query)): Expect>, session_store: Session, user: User, + ClientIp(client_ip): ClientIp, PostForm(form): PostForm, ) -> Result { let user_id = user.into_session().map(|session| session.user_id); @@ -104,7 +106,10 @@ async fn route_complete( .await .expect("should be able to serialize oidc session"); - services.oidc.complete_session(&claims, None).await + services + .oidc + .complete_session(&claims, None, &client_ip) + .await }, | OidcSessionState::Authorized { claims } => { let supplied_user_id = if let Some(form) = form { @@ -163,7 +168,7 @@ async fn route_complete( services .oidc - .complete_session(&claims, supplied_user_id) + .complete_session(&claims, supplied_user_id, &client_ip) .await }, } diff --git a/src/web/pages/templates/_components/device_card.html.j2 b/src/web/pages/templates/_components/device_card.html.j2 index b145f6635..7a4272c57 100644 --- a/src/web/pages/templates/_components/device_card.html.j2 +++ b/src/web/pages/templates/_components/device_card.html.j2 @@ -23,7 +23,7 @@ {% endif %} diff --git a/src/web/pages/templates/account.html.j2 b/src/web/pages/templates/account.html.j2 index 5efd122da..a1f478f99 100644 --- a/src/web/pages/templates/account.html.j2 +++ b/src/web/pages/templates/account.html.j2 @@ -67,7 +67,6 @@ Your account Settings here may affect the integrity of your account.

diff --git a/src/web/pages/templates/index.html.j2 b/src/web/pages/templates/index.html.j2 index cf0c97b0f..54a41d702 100644 --- a/src/web/pages/templates/index.html.j2 +++ b/src/web/pages/templates/index.html.j2 @@ -11,8 +11,9 @@

Continuwuity is successfully installed and working.

{%- if first_run %} -

To get started, check the server logs for instructions on how to create the first account.

+

To get started, create the first account through your Matrix client or through Continuwuity.

For support, take a look at the documentation or join the Continuwuity Matrix room.

+

Create the first account

{%- else %}

To get started, choose a client and connect to {{ server_name }}.

Manage your account

diff --git a/src/web/pages/threepid.rs b/src/web/pages/threepid.rs index 5aefcf6f0..3d8b8b746 100644 --- a/src/web/pages/threepid.rs +++ b/src/web/pages/threepid.rs @@ -33,7 +33,6 @@ async fn threepid_validation( services .threepid .try_validate_session(&query.session, &query.token) - .await .map_err(|message| WebError::BadRequest(message.into_owned()))?; Ok(ThreepidValidation::new(context)) diff --git a/src/web/session/store.rs b/src/web/session/store.rs index a05adb6cd..c7e051dd2 100644 --- a/src/web/session/store.rs +++ b/src/web/session/store.rs @@ -32,6 +32,19 @@ impl SessionStore for RocksDbSessionStore { Ok(()) } + async fn create(&self, session: &mut Record) -> Result<(), Error> { + while self + .websessionid_session + .exists(&session.id.0.to_be_bytes()) + .await + .is_ok() + { + session.id = Id::default(); + } + + self.save(session).await + } + async fn load(&self, session_id: &Id) -> Result, Error> { let Some(session) = self .websessionid_session diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index f11953fdc..bbd903840 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -13,8 +13,13 @@ version.workspace = true conduwuit-admin.workspace = true clap.workspace = true -askama = "0.16.0" +askama = "0.16.1" cargo_metadata = "0.23.1" [lints] workspace = true + +[package.metadata.cargo-shear] +# Task modules are linked by a macro that cargo-shear doesn't expand, +# so we tell it to ignore them specifically. +ignored-paths = ["src/tasks/*/mod.rs"]