Compare commits

..

1 Commits

Author SHA1 Message Date
strawberry a94bf2cf9f unfinished untested impl of room deletion
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-02-20 22:40:46 -05:00
235 changed files with 33649 additions and 39774 deletions
-15
View File
@@ -1,15 +0,0 @@
# EditorConfig is awesome: https://EditorConfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
tab_width = 4
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 120
[*.nix]
indent_size = 2
-7
View File
@@ -1,7 +0,0 @@
# .git-blame-ignore-revs
# adds a proper rustfmt.toml and formats the entire codebase
1d1ac065141181438e744e7d8abd0e45f75a2f91
f419c64aca300a338096b4e0db4c73ace54f23d0
# use chain_width 60
162948313c212193965dece50b816ef0903172ba
5998a0d883d31b866f7c8c46433a8857eae51a89
+136 -175
View File
@@ -5,40 +5,28 @@ on:
push: push:
branches: branches:
- main - main
- dev
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env: env:
# Required to make some things output color # Required to make some things output color
TERM: ansi TERM: ansi
# Publishing to my nix binary cache
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }} ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
# Just in case incremental is still being set to true, speeds up CI
CARGO_INCREMENTAL: 0
# Custom nix binary cache if fork is being used
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
permissions:
packages: write
contents: read
jobs: jobs:
setup: ci:
name: CI Setup name: CI and Artifacts
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Sync repository - name: Sync repository
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Install Nix (with flakes and nix-command enabled) - name: Install Nix (with flakes and nix-command enabled)
uses: cachix/install-nix-action@v26 uses: cachix/install-nix-action@v25
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
# Add `nix-community`, Crane, upstream Conduit, and conduwuit binary caches # Add the `nix-community` cachix to speed up things that leverage it
extra_nix_config: | extra_nix_config: |
experimental-features = nix-command flakes experimental-features = nix-command flakes
extra-substituters = https://nix-community.cachix.org extra-substituters = https://nix-community.cachix.org
@@ -52,12 +40,6 @@ jobs:
extra-substituters = https://attic.kennel.juneis.dog/conduwuit extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw= extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
- name: Add alternative Nix binary caches if specified
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
run: |
echo "extra-substituters = ${{ env.ATTIC_ENDPOINT }}" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}" >> /etc/nix/nix.conf
- name: Pop/push Magic Nix Cache - name: Pop/push Magic Nix Cache
uses: DeterminateSystems/magic-nix-cache-action@main uses: DeterminateSystems/magic-nix-cache-action@main
@@ -84,183 +66,162 @@ jobs:
- name: Populate `/nix/store` - name: Populate `/nix/store`
run: nix develop --command true run: nix develop --command true
- name: Allow direnv
run: direnv allow
- name: Cache x86_64 inputs for devShell
run: |
./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
build-and-test:
name: CI and Artifacts
needs: setup
runs-on: ubuntu-latest
strategy:
matrix:
target: [
"static-x86_64-unknown-linux-musl",
"static-x86_64-unknown-linux-musl-jemalloc",
"static-x86_64-unknown-linux-musl-hmalloc",
"static-aarch64-unknown-linux-musl",
"static-aarch64-unknown-linux-musl-jemalloc",
"static-aarch64-unknown-linux-musl-hmalloc",
]
oci-target: [
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-linux-musl-jemalloc",
"x86_64-unknown-linux-musl-hmalloc",
"aarch64-unknown-linux-musl",
"aarch64-unknown-linux-musl-jemalloc",
"aarch64-unknown-linux-musl-hmalloc",
]
steps:
- name: Perform continuous integration - name: Perform continuous integration
run: direnv exec . engage
- name: Build static artifacts
run: | run: |
./bin/nix-build-and-cache .#${{ matrix.target }} direnv allow
mkdir -p target/release direnv exec . engage
cp -v -f result/bin/conduit target/release
direnv exec . cargo deb --no-build --output target/debian/${{ matrix.target }}.deb
- name: Upload static artifacts - name: Build static-x86_64-unknown-linux-musl
run: |
./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
- name: Upload artifact static-x86_64-unknown-linux-musl
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: ${{ matrix.target }} name: static-x86_64-unknown-linux-musl
path: result/bin/conduit path: result/bin/conduit
if-no-files-found: error if-no-files-found: error
- name: Upload static deb artifacts - name: Build static-aarch64-unknown-linux-musl
run: |
./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
- name: Upload artifact static-aarch64-unknown-linux-musl
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: ${{ matrix.target }}.deb name: static-aarch64-unknown-linux-musl
path: target/debian/${{ matrix.target }}.deb path: result/bin/conduit
if-no-files-found: error if-no-files-found: error
- name: Build oci-image-x86_64-unknown-linux-gnu
- name: Build OCI images
run: | run: |
./bin/nix-build-and-cache .#oci-image-${{ matrix.oci-target }} ./bin/nix-build-and-cache .#oci-image
cp -v -f result oci-image-${{ matrix.oci-target }}.tar.gz cp -f result oci-image-amd64.tar.gz
- name: Upload OCI image artifacts - name: Upload artifact oci-image-x86_64-unknown-linux-gnu
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: oci-image-${{ matrix.oci-target }} name: oci-image-x86_64-unknown-linux-gnu
path: oci-image-${{ matrix.oci-target }}.tar.gz path: oci-image-amd64.tar.gz
# don't compress again
compression-level: 0
- name: Build oci-image-aarch64-unknown-linux-musl
run: |
./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
cp -f result oci-image-arm64v8.tar.gz
- name: Upload artifact oci-image-aarch64-unknown-linux-musl
uses: actions/upload-artifact@v4
with:
name: oci-image-aarch64-unknown-linux-musl
path: oci-image-arm64v8.tar.gz
if-no-files-found: error if-no-files-found: error
# don't compress again # don't compress again
compression-level: 0 compression-level: 0
- name: Build deb-x86_64-unknown-linux-gnu
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libclang-dev
cargo install cargo-deb
cargo deb
- name: Upload artifact deb-x86_64-unknown-linux-gnu
uses: actions/upload-artifact@v4
with:
name: deb-x86_64-unknown-linux-gnu
path: target/debian/*.deb
if-no-files-found: error
- name: Extract metadata for Dockerhub
env:
REGISTRY: registry.hub.docker.com
IMAGE_NAME: ${{ github.repository }}
id: meta-dockerhub
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
publish: - name: Extract metadata for GitHub Container Registry
needs: build-and-test env:
runs-on: ubuntu-latest REGISTRY: ghcr.io
steps: IMAGE_NAME: ${{ github.repository }}
- name: Extract metadata for Dockerhub id: meta-ghcr
env: uses: docker/metadata-action@v5
REGISTRY: registry.hub.docker.com with:
IMAGE_NAME: ${{ github.repository }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
id: meta-dockerhub
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Extract metadata for GitHub Container Registry - name: Login to Dockerhub
env: if: github.event_name != 'pull_request'
REGISTRY: ghcr.io uses: docker/login-action@v3
IMAGE_NAME: ${{ github.repository }} with:
id: meta-ghcr username: girlbossceo
uses: docker/metadata-action@v5 password: ${{ secrets.DOCKERHUB_TOKEN }}
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Login to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
env:
REGISTRY: ghcr.io
with:
registry: ${{ env.REGISTRY }}
username: girlbossceo
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Dockerhub - name: Publish to Dockerhub
env: if: github.event_name != 'pull_request'
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} env:
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }} IMAGE_NAME: docker.io/${{ github.repository }}
if: ${{ (github.event_name != 'pull_request') && (env.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }} IMAGE_SUFFIX_AMD64: amd64
uses: docker/login-action@v3 IMAGE_SUFFIX_ARM64V8: arm64v8
with: run: |
# username is not really a secret docker load -i oci-image-amd64.tar.gz
username: ${{ vars.DOCKER_USERNAME }} IMAGE_ID_AMD64=$(docker images -q conduit:main)
password: ${{ secrets.DOCKERHUB_TOKEN }} docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
- name: Login to GitHub Container Registry # Tag and push the architecture specific images
if: github.event_name != 'pull_request' docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
uses: docker/login-action@v3 docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
env: docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
REGISTRY: ghcr.io docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
with: # Tag the multi-arch image
registry: ${{ env.REGISTRY }} docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
username: ${{ github.repository_owner }} docker manifest push $IMAGE_NAME:$GITHUB_SHA
password: ${{ secrets.GITHUB_TOKEN }} # Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag git tags as 'latest'
if [[ -n "$GITHUB_REF_NAME" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
- name: Publish to GitHub Container Registry
if: github.event_name != 'pull_request'
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
- name: Publish to Dockerhub # Tag and push the architecture specific images
env: docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }} docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }} docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
IMAGE_NAME: docker.io/${{ github.repository }} docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
IMAGE_SUFFIX_AMD64: amd64 # Tag the multi-arch image
IMAGE_SUFFIX_ARM64V8: arm64v8 docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
if: ${{ (github.event_name != 'pull_request') && (env.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }} docker manifest push $IMAGE_NAME:$GITHUB_SHA
run: | # Tag and push the git ref
docker load -i oci-image-amd64.tar.gz docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
IMAGE_ID_AMD64=$(docker images -q conduit:main) docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
docker load -i oci-image-arm64v8.tar.gz # Tag git tags as 'latest'
IMAGE_ID_ARM64V8=$(docker images -q conduit:main) if [[ -n "$GITHUB_REF_NAME" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag and push the architecture specific images docker manifest push $IMAGE_NAME:latest
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 fi
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag "main" as latest (stable branch)
if [[ "$GITHUB_REF_NAME" = "main" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
- name: Publish to GitHub Container Registry
if: github.event_name != 'pull_request'
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
# Tag and push the architecture specific images
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag "main" as latest (stable branch)
if [[ "$GITHUB_REF_NAME" = "main" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
-117
View File
@@ -1,117 +0,0 @@
name: Documentation and GitHub Pages
on:
pull_request:
push:
branches:
- main
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env:
# Required to make some things output color
TERM: ansi
# Publishing to my nix binary cache
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
# Custom nix binary cache if fork is being used
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
docs:
name: Documentation and GitHub Pages
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Sync repository
uses: actions/checkout@v4
- name: Setup GitHub Pages
if: github.event_name != 'pull_request'
uses: actions/configure-pages@v5
- name: Install Nix (with flakes and nix-command enabled)
uses: cachix/install-nix-action@v26
with:
nix_path: nixpkgs=channel:nixos-unstable
# Add `nix-community`, Crane, upstream Conduit, and conduwuit binary caches
extra_nix_config: |
experimental-features = nix-command flakes
extra-substituters = https://nix-community.cachix.org
extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=
extra-substituters = https://crane.cachix.org
extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=
extra-substituters = https://nix.computer.surgery/conduit
extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=
extra-substituters = https://attic.kennel.juneis.dog/conduit
extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
- name: Add alternative Nix binary caches if specified
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
run: |
echo "extra-substituters = ${{ env.ATTIC_ENDPOINT }}" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}" >> /etc/nix/nix.conf
- name: Pop/push Magic Nix Cache
uses: DeterminateSystems/magic-nix-cache-action@main
- name: Configure `nix-direnv`
run: |
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
- name: Install `direnv` and `nix-direnv`
run: nix-env -f "<nixpkgs>" -iA direnv -iA nix-direnv
# Do this to shorten the logs for the real CI step
- name: Populate `/nix/store`
run: nix develop --command true
- name: Allow direnv
run: direnv allow
- name: Cache x86_64 inputs for devShell
run: |
./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
- name: Build documentation (book)
run: |
./bin/nix-build-and-cache .#book
cp -r --dereference result public
- name: Upload generated documentation (book) as normal artifact
uses: actions/upload-artifact@v4
with:
name: public
path: public
if-no-files-found: error
# don't compress again
compression-level: 0
- name: Upload generated documentation (book) as GitHub Pages artifact
if: github.event_name != 'pull_request'
uses: actions/upload-pages-artifact@v3
with:
path: public
- name: Deploy to GitHub Pages
if: github.event_name != 'pull_request'
id: deployment
uses: actions/deploy-pages@v4
+2 -2
View File
@@ -24,7 +24,7 @@ jobs:
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Run Trivy code and vulnerability scanner on repo - name: Run Trivy code and vulnerability scanner on repo
uses: aquasecurity/trivy-action@0.19.0 uses: aquasecurity/trivy-action@0.17.0
with: with:
scan-type: repo scan-type: repo
format: sarif format: sarif
@@ -32,7 +32,7 @@ jobs:
severity: CRITICAL,HIGH,MEDIUM,LOW severity: CRITICAL,HIGH,MEDIUM,LOW
- name: Run Trivy code and vulnerability scanner on filesystem - name: Run Trivy code and vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@0.19.0 uses: aquasecurity/trivy-action@0.17.0
with: with:
scan-type: fs scan-type: fs
format: sarif format: sarif
-9
View File
@@ -74,12 +74,3 @@ test-conduit.toml
# Gitlab CI cache # Gitlab CI cache
/.gitlab-ci.d /.gitlab-ci.d
# mdbook output
public/
# macOS
.DS_Store
# Zed
.zed/
+90 -109
View File
@@ -6,45 +6,22 @@ stages:
variables: variables:
# Makes some things print in color # Makes some things print in color
TERM: ansi TERM: ansi
NIX_CONFIG: |
# Avoid duplicate pipelines experimental-features = nix-command flake
# See: https://docs.gitlab.com/ee/ci/yaml/workflow.html#switch-between-branch-pipelines-and-merge-request-pipelines extra-substituters = https://nix.computer.surgery/conduit
workflow: extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=
rules: extra-substituters = https://crane.cachix.org
- if: $CI_PIPELINE_SOURCE == "merge_request_event" extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS extra-substituters = https://nix-community.cachix.org
when: never extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=
- if: $CI extra-substituters = https://attic.kennel.juneis.dog/conduit
extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
before_script: before_script:
# Enable nix-command and flakes
- if command -v nix > /dev/null; then echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf; fi
# Add conduwuit binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://attic.kennel.juneis.dog/conduwuit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-substituters = https://attic.kennel.juneis.dog/conduit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=" >> /etc/nix/nix.conf; fi
# Add upstream Conduit binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://nix.computer.surgery/conduit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=" >> /etc/nix/nix.conf; fi
# Add alternate binary cache
- if command -v nix > /dev/null && [ -n "$ATTIC_ENDPOINT" ]; then echo "extra-substituters = $ATTIC_ENDPOINT" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null && [ -n "$ATTIC_PUBLIC_KEY" ]; then echo "extra-trusted-public-keys = $ATTIC_PUBLIC_KEY" >> /etc/nix/nix.conf; fi
# Add crane binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://crane.cachix.org" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=" >> /etc/nix/nix.conf; fi
# Add nix-community binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://nix-community.cachix.org" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=" >> /etc/nix/nix.conf; fi
# Install direnv and nix-direnv # Install direnv and nix-direnv
- if command -v nix > /dev/null; then nix-env -iA nixpkgs.direnv nixpkgs.nix-direnv; fi - if command -v nix > /dev/null; then nix-env -iA nixpkgs.direnv nixpkgs.nix-direnv nixpkgs.engage; fi
# Allow .envrc # Allow .envrc
- if command -v nix > /dev/null; then direnv allow; fi - if command -v nix > /dev/null; then direnv allow; fi
@@ -54,87 +31,109 @@ before_script:
ci: ci:
stage: ci stage: ci
image: nixos/nix:2.21.2 image: nixos/nix:2.20.2
script: script:
# Cache the inputs required for the devShell
- ./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
- direnv exec . engage - direnv exec . engage
cache: cache:
key: nix key: nix
paths: paths:
- target - target
- .gitlab-ci.d - .gitlab-ci.d
rules:
# CI on upstream runners (only available for maintainers)
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $IS_UPSTREAM_CI == "true"
# Manual CI on unprotected branches that are not MRs
- if: $CI_PIPELINE_SOURCE != "merge_request_event" && $CI_COMMIT_REF_PROTECTED == "false"
when: manual
# Manual CI on forks
- if: $IS_UPSTREAM_CI != "true"
when: manual
- if: $CI
interruptible: true
artifacts: static:x86_64-unknown-linux-musl:
stage: artifacts stage: artifacts
image: nixos/nix:2.21.2 image: nixos/nix:2.20.2
script: script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl - ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
- cp result/bin/conduit x86_64-unknown-linux-musl
- mkdir -p target/release # Make the output less difficult to find
- cp result/bin/conduit target/release - cp result/bin/conduit conduit
- direnv exec . cargo deb --no-build artifacts:
- mv target/debian/*.deb x86_64-unknown-linux-musl.deb paths:
- conduit
static:aarch64-unknown-linux-musl:
stage: artifacts
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
# Make the output less difficult to find
- cp result/bin/conduit conduit
artifacts:
paths:
- conduit
# Note that although we have an `oci-image-x86_64-unknown-linux-musl` output,
# we don't build it because it would be largely redundant to this one since it's
# all containerized anyway.
oci-image:x86_64-unknown-linux-gnu:
stage: artifacts
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
#
# Since the OCI image package is based on the binary package, this has the # Since the OCI image package is based on the binary package, this has the
# fun side effect of uploading the normal binary too. Conduit users who are # fun side effect of uploading the normal binary too. Conduit users who are
# deploying with Nix can leverage this fact by adding our binary cache to # deploying with Nix can leverage this fact by adding our binary cache to
# their systems. # their systems.
#
# Note that although we have an `oci-image-x86_64-unknown-linux-musl`
# output, we don't build it because it would be largely redundant to this
# one since it's all containerized anyway.
- ./bin/nix-build-and-cache .#oci-image - ./bin/nix-build-and-cache .#oci-image
# Make the output less difficult to find
- cp result oci-image-amd64.tar.gz - cp result oci-image-amd64.tar.gz
- ./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
- cp result/bin/conduit aarch64-unknown-linux-musl
- ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
- cp result oci-image-arm64v8.tar.gz
- ./bin/nix-build-and-cache .#book
# We can't just copy the symlink, we need to dereference it https://gitlab.com/gitlab-org/gitlab/-/issues/19746
- cp -r --dereference result public
artifacts: artifacts:
paths: paths:
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-musl
- x86_64-unknown-linux-musl.deb
- oci-image-amd64.tar.gz - oci-image-amd64.tar.gz
- oci-image-arm64v8.tar.gz
- public
rules:
# CI required for all MRs
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
# Optional CI on forks
- if: $IS_UPSTREAM_CI != "true"
when: manual
allow_failure: true
- if: $CI
interruptible: true
.push-oci-image: oci-image:aarch64-unknown-linux-musl:
stage: artifacts
needs:
# Wait for the static binary job to finish before starting so we don't have
# to build that twice for no reason
- static:aarch64-unknown-linux-musl
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
# Make the output less difficult to find
- cp result oci-image-arm64v8.tar.gz
artifacts:
paths:
- oci-image-arm64v8.tar.gz
debian:x86_64-unknown-linux-gnu:
stage: artifacts
# See also `rust-toolchain.toml`
image: rust:1.75.0
script:
- cargo install cargo-deb
- cargo deb
# Make the output less difficult to find
- mv target/debian/*.deb conduit.deb
artifacts:
paths:
- conduit.deb
cache:
key: debian
paths:
- target
- .gitlab-ci.d
docker-publish:
stage: publish stage: publish
image: docker:26.0.1 image: docker:25.0.3
services: services:
- docker:26.0.1-dind - docker:25.0.3-dind
variables: variables:
IMAGE_NAME: $CI_REGISTRY_IMAGE/conduwuit
IMAGE_SUFFIX_AMD64: amd64 IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8 IMAGE_SUFFIX_ARM64V8: arm64v8
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script: script:
- docker load -i oci-image-amd64.tar.gz - docker load -i oci-image-amd64.tar.gz
- IMAGE_ID_AMD64=$(docker images -q conduit:main) - IMAGE_ID_AMD64=$(docker images -q conduit:main)
@@ -158,26 +157,8 @@ artifacts:
docker manifest push $IMAGE_NAME:latest docker manifest push $IMAGE_NAME:latest
fi fi
dependencies: dependencies:
- artifacts - oci-image:x86_64-unknown-linux-gnu
- oci-image:aarch64-unknown-linux-musl
only: only:
- main - main
- tags - tags
oci-image:push-gitlab:
extends: .push-oci-image
variables:
IMAGE_NAME: $CI_REGISTRY_IMAGE/conduwuit
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
pages:
stage: publish
dependencies:
- artifacts
only:
- next
script:
- "true"
artifacts:
paths:
- public
-3
View File
@@ -1,3 +0,0 @@
# Docs: Map markdown to html files
- source: /docs/(.+)\.md/
public: '\1.html'
-1
View File
@@ -1,7 +1,6 @@
{ {
"recommendations": [ "recommendations": [
"rust-lang.rust-analyzer", "rust-lang.rust-analyzer",
"editorconfig.editorconfig",
"ms-azuretools.vscode-docker", "ms-azuretools.vscode-docker",
"eamodio.gitlens", "eamodio.gitlens",
"serayuzgur.crates", "serayuzgur.crates",
+4 -4
View File
@@ -23,11 +23,11 @@
"args": [], "args": [],
"env": { "env": {
"RUST_BACKTRACE": "1", "RUST_BACKTRACE": "1",
"CONDUIT_DATABASE_PATH": "/tmp/awawawa", "CONDUIT_CONFIG": "",
"CONDUIT_SERVER_NAME": "localhost",
"CONDUIT_DATABASE_PATH": "/tmp",
"CONDUIT_ADDRESS": "0.0.0.0", "CONDUIT_ADDRESS": "0.0.0.0",
"CONDUIT_PORT": "55551", "CONDUIT_PORT": "6167"
"CONDUIT_SERVER_NAME": "your.server.name",
"CONDUIT_LOG": "debug"
}, },
"cwd": "${workspaceFolder}" "cwd": "${workspaceFolder}"
} }
+5 -5
View File
@@ -2,7 +2,7 @@
## Getting help ## Getting help
If you run into any problems while setting up an Appservice: ask us in [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay) or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new). If you run into any problems while setting up an Appservice, write an email to `timo@koesters.xyz`, ask us in [#conduit:fachschaften.org](https://matrix.to/#/#conduit:fachschaften.org) or [open an issue on GitLab](https://gitlab.com/famedly/conduit/-/issues/new).
## Set up the appservice - general instructions ## Set up the appservice - general instructions
@@ -31,9 +31,9 @@ the room like this:
``` ```
You can confirm it worked by sending a message like this: You can confirm it worked by sending a message like this:
`@conduit:your.server.name: appservices list` `@conduit:your.server.name: list-appservices`
The `@conduit` bot should answer with `Appservices (1): your-bridge` The @conduit bot should answer with `Appservices (1): your-bridge`
Then you are done. Conduit will send messages to the appservices and the Then you are done. Conduit will send messages to the appservices and the
appservice can send requests to the homeserver. You don't need to restart appservice can send requests to the homeserver. You don't need to restart
@@ -46,9 +46,9 @@ could help.
To remove an appservice go to your admin room and execute To remove an appservice go to your admin room and execute
`@conduit:your.server.name: appservices unregister <name>` `@conduit:your.server.name: unregister-appservice <name>`
where `<name>` one of the output of `appservices list`. where `<name>` one of the output of `list-appservices`.
### Tested appservices ### Tested appservices
Generated
+395 -996
View File
File diff suppressed because it is too large Load Diff
+121 -476
View File
@@ -2,375 +2,133 @@
name = "conduit" name = "conduit"
description = "a cool fork of Conduit, a Matrix homeserver written in Rust" description = "a cool fork of Conduit, a Matrix homeserver written in Rust"
license = "Apache-2.0" license = "Apache-2.0"
authors = [ authors = ["strawberry <strawberry@puppygock.gay>", "timokoesters <timo@koesters.xyz>"]
"strawberry <strawberry@puppygock.gay>",
"timokoesters <timo@koesters.xyz>",
]
homepage = "https://puppygock.gay/conduwuit" homepage = "https://puppygock.gay/conduwuit"
repository = "https://github.com/girlbossceo/conduwuit" repository = "https://gitlab.com/girlbossceo/conduwuit"
readme = "README.md" readme = "README.md"
version = "0.7.0+conduwuit-0.2.0" version = "0.7.0-alpha+conduwuit-0.1.3"
edition = "2021" edition = "2021"
# See also `rust-toolchain.toml` # See also `rust-toolchain.toml`
rust-version = "1.75.0" rust-version = "1.75.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
# Used for secure identifiers
rand = "0.8.5"
# Used for conduit::Error type
thiserror = "1.0.58"
# Used to encode server public key
base64 = "0.22.0"
# Used when hashing the state
ring = "0.17.8"
# Used to find matching events for appservices
regex = "1.10.4"
# Used to load forbidden room/user regex from config
serde_regex = "1.1.0"
# Used to make working with iterators easier, was already a transitive depdendency
itertools = "0.12.1"
# jwt jsonwebtokens
jsonwebtoken = "9.3.0"
lru-cache = "0.1.2"
# Used for ruma wrapper
serde_html_form = "0.2.6"
# used for TURN server authentication
hmac = "0.12.1"
sha-1 = "0.10.1"
async-trait = "0.1.80"
# used for checking if an IP is in specific subnets / CIDR ranges easier
ipaddress = "0.1.3"
# to encode/decode percent URIs when conduwuit is running without a reverse proxy
#urlencoding = "2.1.3"
# to get the client IP address of requests
#axum-client-ip = "0.4.2"
# to parse user-friendly time durations in admin commands
cyborgtime = "2.1.1"
# all the web/HTTP dependencies
# Used for the http request / response body type for Ruma endpoints used with reqwest
bytes = "1.6.0"
http = "0.2.12"
# used to replace the channels of the tokio runtime
loole = "0.3.0"
# Validating urls in config, was already a transitive dependency
url = { version = "2", features = ["serde"] }
# standard date and time tools
[dependencies.chrono]
version = "0.4.38"
features = ["alloc"]
default-features = false
# Web framework # Web framework
[dependencies.axum] axum = { version = "0.6.20", default-features = false, features = ["form", "headers", "http1", "http2", "json", "matched-path"], optional = true }
version = "0.6.20" axum-server = { version = "0.5.1", features = ["tls-rustls"] }
default-features = false tower = { version = "0.4.13", features = ["util"] }
features = ["form", "headers", "http1", "http2", "json", "matched-path"] tower-http = { version = "0.4.4", features = ["add-extension", "cors", "sensitive-headers", "trace", "util", "compression-zstd"] }
[dependencies.axum-server]
version = "0.5.1"
features = ["tls-rustls"]
[dependencies.tower]
version = "0.4.13"
features = ["util"]
[dependencies.tower-http]
version = "0.4.4"
features = ["add-extension", "cors", "sensitive-headers", "trace", "util"]
[dependencies.hyper]
version = "0.14"
features = ["server", "http1", "http2"]
[dependencies.reqwest]
#version = "0.11.27"
git = "https://github.com/girlbossceo/reqwest"
rev = "319335e000fdea2e3d01f44245c8a21864d0c1c3"
default-features = false
features = ["rustls-tls-native-roots", "socks", "hickory-dns"]
# all the serde stuff
# Used for pdu definition
[dependencies.serde]
version = "1.0.197"
features = ["rc"]
# Used for appservice registration files
[dependencies.serde_yaml]
version = "0.9.34"
# Used for ruma wrapper
[dependencies.serde_json]
version = "1.0.116"
features = ["raw_value"]
# Used for password hashing
[dependencies.argon2]
version = "0.5.3"
features = ["alloc", "rand"]
default-features = false
# Used to generate thumbnails for images
[dependencies.image]
version = "0.25.1"
default-features = false
features = ["jpeg", "png", "gif", "webp"]
# logging
[dependencies.log]
version = "0.4.21"
default-features = false
features = ["max_level_trace", "release_max_level_info"]
[dependencies.tracing]
version = "0.1.40"
default-features = false
features = ["max_level_trace", "release_max_level_info"]
[dependencies.tracing-subscriber]
version = "0.3.18"
features = ["env-filter"]
# optional SHA256 media keys feature
[dependencies.sha2]
version = "0.10.8"
optional = true
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[dependencies.opentelemetry]
version = "0.21.0"
optional = true
[dependencies.tracing-flame]
version = "0.2.0"
optional = true
[dependencies.tracing-opentelemetry]
version = "0.22.0"
optional = true
[dependencies.opentelemetry_sdk]
version = "0.21.2"
optional = true
features = ["rt-tokio"]
[dependencies.opentelemetry-jaeger]
version = "0.20.0"
optional = true
features = ["rt-tokio"]
# optional sentry metrics for crash/panic reporting
[dependencies.sentry]
version = "0.32.3"
optional = true
default-features = false
features = [
"backtrace",
"contexts",
"debug-images",
"panic",
"rustls",
"tower",
"tower-http",
"tracing",
"reqwest",
"log",
]
[dependencies.sentry-tracing]
version = "0.32.3"
optional = true
[dependencies.sentry-tower]
version = "0.32.3"
optional = true
# optional jemalloc usage
[dependencies.tikv-jemallocator]
version = "0.5.4"
optional = true
default-features = false
features = ["unprefixed_malloc_on_supported_platforms"]
[dependencies.tikv-jemalloc-ctl]
version = "0.5.4"
optional = true
default-features = false
features = ["use_std"]
# for URL previews
[dependencies.webpage]
version = "2.0"
default-features = false
# to support multiple variations of setting a config option
[dependencies.either]
version = "1.11.0"
features = ["serde"]
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
[dependencies.axum-server-dual-protocol]
version = "0.5.2"
optional = true
# used for conduit's CLI and admin room command parsing
[dependencies.clap]
version = "4.5.4"
default-features = false
features = ["std", "derive", "help", "usage", "error-context", "string"]
[dependencies.futures-util]
version = "0.3.30"
default-features = false
# Used for reading the configuration from conduit.toml & environment variables
[dependencies.figment]
version = "0.10.17"
features = ["env", "toml"]
# Used for matrix spec type definitions and helpers # Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/ruma/ruma", rev = "4d9f754657a099df8e61533787b8eebd12946435", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] } #ruma = { git = "https://github.com/ruma/ruma", rev = "4d9f754657a099df8e61533787b8eebd12946435", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] }
ruma = { git = "https://github.com/girlbossceo/ruma", rev = "788ea6b00fab49b04a17d88caa0c840b7d74aa13", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] } #ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
[dependencies.ruma]
git = "https://github.com/girlbossceo/ruma"
#rev = "c988b5ff158ede9c10aeffc76ad5e31604f19ddb"
branch = "conduwuit-changes"
#path = "../ruma/crates/ruma"
features = [
"compat",
"rand",
"appservice-api-c",
"client-api",
"federation-api",
"push-gateway-api-c",
"state-res",
"unstable-exhaustive-types",
"ring-compat",
"unstable-unspecified",
"unstable-msc2448",
"unstable-msc2666",
"unstable-msc2867",
"unstable-msc2870",
"unstable-msc3026",
"unstable-msc3061",
"unstable-msc3575",
"unstable-msc4121",
"unstable-msc4125",
"unstable-extensible-events",
]
[dependencies.hickory-resolver] # Async runtime and utilities
git = "https://github.com/hickory-dns/hickory-dns"
rev = "94ac564c3f677e038f7255ddb762e9301d0f2c5d"
[dependencies.rust-rocksdb]
git = "https://github.com/zaidoon1/rust-rocksdb"
branch = "master"
#rev = "60f783b06b49d2f6fcf1d3dda66c7194e49095d4"
optional = true
default-features = true
features = ["multi-threaded-cf", "zstd"]
[dependencies.rusqlite]
git = "https://github.com/rusqlite/rusqlite"
#branch = "master"
rev = "e00b626e2b1c67347d789fb7f600281705c89381"
optional = true
features = ["bundled"]
# used only by rusqlite
[dependencies.parking_lot]
version = "0.12.1"
optional = true
# used only by rusqlite
[dependencies.thread_local]
version = "1.1.8"
optional = true
# used only by rusqlite and rust-rocksdb
[dependencies.num_cpus]
version = "1.16.0"
optional = true
[dependencies.tokio]
version = "1.37.0"
features = ["fs", "macros", "sync", "signal"]
# *nix-specific dependencies
[target.'cfg(unix)'.dependencies]
nix = { version = "0.28.0", features = ["resource"] }
sd-notify = { version = "0.4.1", optional = true } # systemd is only available/relevant on *nix platforms
hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = [ hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = [
"server", "server",
] } # unix socket support ] }
hyper = { version = "0.14", features = ["server", "http1", "http2"] }
tokio = { version = "1.36.0", features = ["fs", "macros", "signal", "sync"] }
[target.'cfg(all(not(target_env = "msvc"), not(target_os = "macos"), target_os = "linux"))'.dependencies] # Used for the http request / response body type for Ruma endpoints used with reqwest
hardened_malloc-rs = { version = "0.1", optional = true, features = [ bytes = "1.5.0"
"static", http = "0.2.11"
"clang", # Used for ruma wrapper
"light", serde_json = { version = "1.0.114", features = ["raw_value"] }
], default-features = false } # Used for appservice registration files
#hardened_malloc-rs = { optional = true, features = ["static","clang","light"], path = "../hardened_malloc-rs", default-features = false } serde_yaml = "0.9.32"
# Used for pdu definition
serde = { version = "1.0.197", features = ["rc"] }
# Used for secure identifiers
rand = "0.8.5"
# Used to hash passwords
argon2 = "0.5.3"
reqwest = { version = "0.11.24", default-features = false, features = ["rustls-tls-native-roots", "socks"] }
# Used for conduit::Error type
thiserror = "1.0.57"
# Used to generate thumbnails for images
image = { version = "0.24.8", default-features = false, features = ["jpeg", "png", "gif", "webp"] }
# Used to encode server public key
base64 = "0.21.7"
# Used when hashing the state
ring = "0.17.8"
# Used when querying the SRV record of other servers
trust-dns-resolver = "0.23.2"
# Used to find matching events for appservices
regex = "1.10.3"
# Used to load forbidden room/user regex from config
serde_regex = "1.1.0"
itertools = "0.12.1"
# jwt jsonwebtokens
jsonwebtoken = "9.2.0"
# Performance measurements
tracing = { version = "0.1.40", features = [] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing-flame = "0.2.0"
opentelemetry = "0.21.0"
opentelemetry_sdk = { version = "0.21.2", features = ["rt-tokio"] }
opentelemetry-jaeger = { version = "0.20.0", features = ["rt-tokio"] }
tracing-opentelemetry = "0.22.0"
lru-cache = "0.1.2"
rusqlite = { git = "https://github.com/rusqlite/rusqlite", rev = "ccfbc28ae1edc3090fb1b331fdc145f052ec73b9", optional = true, features = ["bundled"] }
parking_lot = { version = "0.12.1", optional = true }
num_cpus = "1.16.0"
threadpool = "1.8.1"
# Used for ruma wrapper
serde_html_form = "0.2.4"
thread_local = "1.1.7"
# used for TURN server authentication
hmac = "0.12.1"
sha-1 = "0.10.1"
sha2 = { version = "0.10.8" }
# used for conduit's CLI and admin room command parsing
clap = { version = "4.5.1", default-features = false, features = ["std", "derive", "help", "usage", "error-context"] }
futures-util = { version = "0.3.30", default-features = false }
# Used for reading the configuration from conduit.toml & environment variables
figment = { version = "0.10.14", features = ["env", "toml"] }
tikv-jemalloc-ctl = { version = "0.5.4", features = ["use_std"], optional = true }
tikv-jemallocator = { version = "0.5.4", features = ["unprefixed_malloc_on_supported_platforms"], optional = true }
lazy_static = "1.4.0"
async-trait = "0.1.77"
# used for checking if an IP is in specific subnets / CIDR ranges
ipaddress = "0.1.3"
sd-notify = { version = "0.4.1", optional = true }
webpage = { version = "2.0", default-features = false }
rocksdb = { version = "0.22.0", default-features = true, features = ["multi-threaded-cf", "zstd"], optional = true }
[target.'cfg(unix)'.dependencies]
nix = { version = "0.27.1", features = ["resource"] }
[features] [features]
default = [ default = ["conduit_bin", "backend_rocksdb", "systemd", "zstd_compression"]
"backend_rocksdb",
"systemd",
"element_hacks",
"sentry_telemetry",
"gzip_compression",
"brotli_compression",
"zstd_compression",
]
backend_sqlite = ["sqlite"] backend_sqlite = ["sqlite"]
backend_rocksdb = ["rocksdb"] backend_rocksdb = ["rocksdb"]
rocksdb = ["rust-rocksdb", "num_cpus"] jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator"]
jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator", "rust-rocksdb/jemalloc"] sqlite = ["rusqlite", "parking_lot", "tokio/signal"]
sqlite = ["rusqlite", "parking_lot", "thread_local", "num_cpus"] conduit_bin = ["axum"]
systemd = ["sd-notify"] systemd = ["sd-notify"]
sentry_telemetry = ["sentry", "sentry-tracing", "sentry-tower"] #gzip_compression = ["tower-http/compression-gzip"]
zstd_compression = []
gzip_compression = ["tower-http/compression-gzip", "reqwest/gzip"] #brotli_compression = ["tower-http/compression-br"]
zstd_compression = ["tower-http/compression-zstd"] #compression = ["tower-http/compression-full"]
brotli_compression = ["tower-http/compression-br", "reqwest/brotli"] sha256_media = []
io_uring = ["rocksdb/io-uring"]
sha256_media = ["sha2"]
io_uring = ["rust-rocksdb/io-uring"]
axum_dual_protocol = ["axum-server-dual-protocol"]
perf_measurements = [
"opentelemetry",
"tracing-flame",
"tracing-opentelemetry",
"opentelemetry_sdk",
"opentelemetry-jaeger",
]
hardened_malloc = ["hardened_malloc-rs"]
# client/server interopability hacks
#
## element has various non-spec compliant behaviour
element_hacks = []
[[bin]] [[bin]]
name = "conduit" name = "conduit"
path = "src/main.rs" path = "src/main.rs"
required-features = ["conduit_bin"]
[lib] [lib]
name = "conduit" name = "conduit"
@@ -387,44 +145,20 @@ a cool fork of Conduit, a Matrix homeserver written in Rust"""
section = "net" section = "net"
priority = "optional" priority = "optional"
assets = [ assets = [
[ ["debian/README.md", "usr/share/doc/matrix-conduit/README.Debian", "644"],
"debian/README.md", ["README.md", "usr/share/doc/matrix-conduit/", "644"],
"usr/share/doc/matrix-conduit/README.Debian", ["target/release/conduit", "usr/sbin/matrix-conduit", "755"],
"644", ]
], conf-files = [
[ "/etc/matrix-conduit/conduit.toml"
"README.md",
"usr/share/doc/matrix-conduit/",
"644",
],
[
"target/release/conduit",
"usr/sbin/matrix-conduit",
"755",
],
[
"conduwuit-example.toml",
"etc/matrix-conduit/conduit.toml",
"640",
],
] ]
conf-files = ["/etc/matrix-conduit/conduit.toml"]
maintainer-scripts = "debian/" maintainer-scripts = "debian/"
systemd-units = { unit-name = "matrix-conduit" } systemd-units = { unit-name = "matrix-conduit" }
[profile.dev] [profile.dev]
debug = 0 debug = 0
lto = 'off' lto = 'off'
codegen-units = 512
incremental = true incremental = true
# seems to speed up continuous debug compilations
[profile.dev.build-override]
opt-level = 3
[profile.dev.package."*"] # external dependencies
opt-level = 1
[profile.dev.package."tokio"]
opt-level = 3
# default release profile # default release profile
[profile.release] [profile.release]
@@ -433,7 +167,7 @@ incremental = false
opt-level = 3 opt-level = 3
overflow-checks = true overflow-checks = true
strip = "symbols" strip = "symbols"
control-flow-guard = true # Windows only panic = "abort"
debug = 0 debug = 0
# high performance release profile which uses fat LTO across all crates, 1 codegen unit, max opt-level, and optimises across all crates # high performance release profile which uses fat LTO across all crates, 1 codegen unit, max opt-level, and optimises across all crates
@@ -441,7 +175,6 @@ debug = 0
inherits = "release" inherits = "release"
lto = 'fat' lto = 'fat'
codegen-units = 1 codegen-units = 1
panic = "abort"
# For releases also try to max optimizations for dependencies: # For releases also try to max optimizations for dependencies:
[profile.release-high-perf.build-override] [profile.release-high-perf.build-override]
@@ -454,46 +187,29 @@ debug = 0
opt-level = 3 opt-level = 3
codegen-units = 1 codegen-units = 1
[lints] [lints]
workspace = true workspace = true
[workspace.lints.rust] [workspace.lints.rust]
missing_abi = "warn" missing_abi = "warn"
# missing_docs = "warn"
noop_method_call = "warn" noop_method_call = "warn"
pointer_structural_match = "warn" pointer_structural_match = "warn"
explicit_outlives_requirements = "warn" explicit_outlives_requirements = "warn"
# unreachable_pub = "warn"
unused_extern_crates = "warn" unused_extern_crates = "warn"
unused_import_braces = "warn" unused_import_braces = "warn"
unused_lifetimes = "warn" # unused_lifetimes = "warn"
unused_qualifications = "warn" unused_qualifications = "warn"
unused_macro_rules = "warn"
dead_code = "warn" dead_code = "warn"
elided_lifetimes_in_paths = "warn"
macro_use_extern_crate = "warn"
single_use_lifetimes = "warn"
unsafe_op_in_unsafe_fn = "warn"
# not in rust 1.75.0 (doesn't break CI but won't check for it)
unit_bindings = "warn"
# this seems to suggest broken code and is not working correctly
unused_braces = "allow"
# some sadness
unreachable_pub = "allow"
missing_docs = "allow"
[workspace.lints.clippy] [workspace.lints.clippy]
# pedantic = "warn"
suspicious = "warn" # assume deny in practice suspicious = "warn" # assume deny in practice
perf = "warn" # assume deny in practice perf = "warn" # assume deny in practice
redundant_clone = "warn" redundant_clone = "warn"
cloned_instead_of_copied = "warn" cloned_instead_of_copied = "warn"
expl_impl_clone_on_copy = "warn" expl_impl_clone_on_copy = "warn"
# pedantic = "warn"
unnecessary_cast = "warn" unnecessary_cast = "warn"
cast_lossless = "warn" cast_lossless = "warn"
ptr_as_ptr = "warn" ptr_as_ptr = "warn"
@@ -502,99 +218,28 @@ char_lit_as_u8 = "warn"
dbg_macro = "warn" dbg_macro = "warn"
empty_structs_with_brackets = "warn" empty_structs_with_brackets = "warn"
get_unwrap = "warn" get_unwrap = "warn"
# if_then_some_else_none = "warn"
# let_underscore_must_use = "warn"
# map_err_ignore = "warn"
# missing_docs_in_private_items = "warn"
negative_feature_names = "warn" negative_feature_names = "warn"
pub_without_shorthand = "warn" pub_without_shorthand = "warn"
rc_buffer = "warn" rc_buffer = "warn"
rc_mutex = "warn" rc_mutex = "warn"
redundant_feature_names = "warn" redundant_feature_names = "warn"
redundant_type_annotations = "warn" redundant_type_annotations = "warn"
# ref_patterns = "warn"
rest_pat_in_fully_bound_structs = "warn" rest_pat_in_fully_bound_structs = "warn"
str_to_string = "warn" str_to_string = "warn"
# string_add = "warn"
# string_slice = "warn"
string_to_string = "warn" string_to_string = "warn"
tests_outside_test_module = "warn" tests_outside_test_module = "warn"
undocumented_unsafe_blocks = "warn" undocumented_unsafe_blocks = "warn"
unneeded_field_pattern = "warn" unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn" unseparated_literal_suffix = "warn"
# unwrap_used = "warn"
# expect_used = "warn"
wildcard_dependencies = "warn" wildcard_dependencies = "warn"
or_fun_call = "warn" # or_fun_call = "warn"
unnecessary_lazy_evaluations = "warn" unnecessary_lazy_evaluations = "warn"
assertions_on_result_states = "warn"
default_union_representation = "warn"
deref_by_slicing = "warn"
empty_drop = "warn"
exit = "warn"
filetype_is_file = "warn"
float_cmp_const = "warn"
format_push_string = "warn"
impl_trait_in_params = "warn"
ref_to_mut = "warn"
lossy_float_literal = "warn"
mem_forget = "warn"
missing_assert_message = "warn"
mutex_atomic = "warn"
semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn"
string_lit_chars_any = "warn"
suspicious_xor_used_as_pow = "warn"
try_err = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn"
verbose_file_reads = "warn"
cast_possible_wrap = "warn"
redundant_closure_for_method_calls = "warn"
large_futures = "warn"
semicolon_if_nothing_returned = "warn"
match_bool = "warn"
struct_excessive_bools = "warn"
must_use_candidate = "warn"
collapsible_else_if = "warn"
inconsistent_struct_constructor = "warn"
manual_string_new = "warn"
zero_sized_map_values = "warn"
unnecessary_box_returns = "warn"
map_unwrap_or = "warn"
implicit_clone = "warn"
match_wildcard_for_single_variants = "warn"
unnecessary_wraps = "warn"
match_same_arms = "warn"
ignored_unit_patterns = "warn"
redundant_else = "warn"
explicit_into_iter_loop = "warn"
used_underscore_binding = "warn"
needless_pass_by_value = "warn"
too_many_lines = "warn"
let_underscore_untyped = "warn"
single_match = "warn"
single_match_else = "warn"
explicit_deref_methods = "warn"
explicit_iter_loop = "warn"
manual_let_else = "warn"
trivially_copy_pass_by_ref = "warn"
wildcard_imports = "warn"
checked_conversions = "warn"
# some sadness
missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
if_not_else = "allow"
doc_markdown = "allow"
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
same_name_method = "allow"
mod_module_files = "allow"
unwrap_used = "allow"
expect_used = "allow"
if_then_some_else_none = "allow"
let_underscore_must_use = "allow"
map_err_ignore = "allow"
missing_docs_in_private_items = "allow"
multiple_inherent_impl = "allow"
error_impl_error = "allow"
as_conversions = "allow"
string_add = "allow"
string_slice = "allow"
ref_patterns = "allow"
+330
View File
@@ -0,0 +1,330 @@
# Deploying Conduit
### Please note that this documentation is not fully representative of conduwuit at the moment. Assume majority of it is outdated.
> ## Getting help
>
> If you run into any problems while setting up conduwuit, ask us
> in `#conduwuit:puppygock.gay` or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
## Installing conduwuit
You may simply download the binary that fits your machine. Run `uname -m` to see what you need. Now copy the appropriate URL:
**Stable versions:**
| CPU Architecture | Download stable version |
| ------------------------------------------- | --------------------------------------------------------------- |
| x84_64 / amd64 (Most servers and computers) | [Binary][x84_64-glibc-master] / [.deb][x84_64-glibc-master-deb] |
| armv7 (e.g. Raspberry Pi by default) | [Binary][armv7-glibc-master] / [.deb][armv7-glibc-master-deb] |
| armv8 / aarch64 | [Binary][armv8-glibc-master] / [.deb][armv8-glibc-master-deb] |
[x84_64-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_amd64/conduit?job=docker:master
[armv7-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm_v7/conduit?job=docker:master
[armv8-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm64/conduit?job=docker:master
[x84_64-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_amd64/conduit.deb?job=docker:master
[armv7-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm_v7/conduit.deb?job=docker:master
[armv8-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm64/conduit.deb?job=docker:master
**Latest versions:**
| Target | Type | Download |
|-|-|-|
| `x86_64-unknown-linux-gnu` | Dynamically linked Debian package | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit.deb?job=debian:x86_64-unknown-linux-gnu) |
| `x86_64-unknown-linux-musl` | Statically linked binary | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit?job=static:x86_64-unknown-linux-musl) |
| `aarch64-unknown-linux-musl` | Statically linked binary | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit?job=static:aarch64-unknown-linux-musl) |
| `x86_64-unknown-linux-musl` | OCI image | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/oci-image-amd64.tar.gz?job=oci-image:x86_64-unknown-linux-musl) |
| `aarch64-unknown-linux-musl` | OCI image | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/oci-image-arm64v8.tar.gz?job=oci-image:aarch64-unknown-linux-musl) |
```bash
$ sudo wget -O /usr/local/bin/matrix-conduit <url>
$ sudo chmod +x /usr/local/bin/matrix-conduit
```
Alternatively, you may compile the binary yourself. First, install any dependencies:
```bash
# Debian
$ sudo apt install libclang-dev build-essential
# RHEL
$ sudo dnf install clang
```
Then, `cd` into the source tree of conduit-next and run:
```bash
$ cargo build --release
```
If you want to cross compile Conduit to another architecture, read the guide below.
<details>
<summary>Cross compilation</summary>
As easiest way to compile conduit for another platform [cross-rs](https://github.com/cross-rs/cross) is recommended, so install it first.
In order to use RockDB as storage backend append `-latomic` to linker flags.
For example, to build a binary for Raspberry Pi Zero W (ARMv6) you need `arm-unknown-linux-gnueabihf` as compilation
target.
```bash
git clone https://gitlab.com/famedly/conduit.git
cd conduit
export RUSTFLAGS='-C link-arg=-lgcc -Clink-arg=-latomic -Clink-arg=-static-libgcc'
cross build --release --no-default-features --features conduit_bin,backend_rocksdb --target=arm-unknown-linux-gnueabihf
```
</details>
## Adding a Conduit user
While Conduit can run as any user it is usually better to use dedicated users for different services. This also allows
you to make sure that the file permissions are correctly set up.
In Debian or RHEL, you can use this command to create a Conduit user:
```bash
sudo adduser --system conduit --group --disabled-login --no-create-home
```
## Forwarding ports in the firewall or the router
Conduit uses the ports 443 and 8448 both of which need to be open in the firewall.
If Conduit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.
## Optional: Avoid port 8448
If Conduit runs behind Cloudflare reverse proxy, which doesn't support port 8448 on free plans, [delegation](https://matrix-org.github.io/synapse/latest/delegate.html) can be set up to have federation traffic routed to port 443:
```apache
# .well-known delegation on Apache
<Files "/.well-known/matrix/server">
ErrorDocument 200 '{"m.server": "your.server.name:443"}'
Header always set Content-Type application/json
Header always set Access-Control-Allow-Origin *
</Files>
```
[SRV DNS record](https://spec.matrix.org/latest/server-server-api/#resolving-server-names) delegation is also [possible](https://www.cloudflare.com/en-gb/learning/dns/dns-records/dns-srv-record/).
## Setting up a systemd service
Now we'll set up a systemd service for Conduit, so it's easy to start/stop Conduit and set it to autostart when your
server reboots. Simply paste the default systemd service you can find below into
`/etc/systemd/system/conduit.service`.
```systemd
[Unit]
Description=Conduit Matrix Server
After=network.target
[Service]
Environment="CONDUIT_CONFIG=/etc/matrix-conduit/conduit.toml"
User=conduit
Group=conduit
RuntimeDirectory=conduit
RuntimeDirectoryMode=0750
Restart=always
ExecStart=/usr/local/bin/matrix-conduit
[Install]
WantedBy=multi-user.target
```
Finally, run
```bash
$ sudo systemctl daemon-reload
```
## Creating the Conduit configuration file
Now we need to create the Conduit's config file in `/etc/conduwuit/conduwuit.toml`. Paste this in **and take a moment
to read it. You need to change at least the server name.**
You can also choose to use a different database backend, but right now only `rocksdb` and `sqlite` are recommended.
See the following example config at [conduwuit-example.toml](conduwuit-example.toml)
## Setting the correct file permissions
As we are using a Conduit specific user we need to allow it to read the config. To do that you can run this command on
Debian or RHEL:
```bash
sudo chown -R root:root /etc/matrix-conduit
sudo chmod 755 /etc/matrix-conduit
```
If you use the default database path you also need to run this:
```bash
sudo mkdir -p /var/lib/matrix-conduit/
sudo chown -R conduit:conduit /var/lib/matrix-conduit/
sudo chmod 700 /var/lib/matrix-conduit/
```
## Setting up the Reverse Proxy
This depends on whether you use Apache, Caddy, Nginx or another web server.
### Apache
Create `/etc/apache2/sites-enabled/050-conduit.conf` and copy-and-paste this:
```apache
# Requires mod_proxy and mod_proxy_http
#
# On Apache instance compiled from source,
# paste into httpd-ssl.conf or httpd.conf
Listen 8448
<VirtualHost *:443 *:8448>
ServerName your.server.name # EDIT THIS
AllowEncodedSlashes NoDecode
# TCP
ProxyPass /_matrix/ http://127.0.0.1:6167/_matrix/ timeout=300 nocanon
ProxyPassReverse /_matrix/ http://127.0.0.1:6167/_matrix/
# UNIX socket
#ProxyPass /_matrix/ unix:/run/conduit/conduit.sock|http://127.0.0.1:6167/_matrix/ nocanon
#ProxyPassReverse /_matrix/ unix:/run/conduit/conduit.sock|http://127.0.0.1:6167/_matrix/
</VirtualHost>
```
**You need to make some edits again.** When you are done, run
```bash
# Debian
$ sudo systemctl reload apache2
# Installed from source
$ sudo apachectl -k graceful
```
### Caddy
Create `/etc/caddy/conf.d/conduit_caddyfile` and enter this (substitute for your server name).
```caddy
your.server.name, your.server.name:8448 {
# TCP
reverse_proxy /_matrix/* 127.0.0.1:6167
# UNIX socket
#reverse_proxy /_matrix/* unix//run/conduit/conduit.sock
}
```
That's it! Just start or enable the service and you're set.
```bash
$ sudo systemctl enable caddy
```
### Nginx
If you use Nginx and not Apache, add the following server section inside the http section of `/etc/nginx/nginx.conf`
```nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
listen 8448 ssl http2;
listen [::]:8448 ssl http2;
server_name your.server.name; # EDIT THIS
merge_slashes off;
# Nginx defaults to only allow 1MB uploads
# Increase this to allow posting large files such as videos
client_max_body_size 20M;
# UNIX socket
#upstream backend {
# server unix:/run/conduit/conduit.sock;
#}
location /_matrix/ {
# TCP
proxy_pass http://127.0.0.1:6167$request_uri;
# UNIX socket
#proxy_pass http://backend;
proxy_set_header Host $http_host;
proxy_buffering off;
proxy_read_timeout 5m;
}
ssl_certificate /etc/letsencrypt/live/your.server.name/fullchain.pem; # EDIT THIS
ssl_certificate_key /etc/letsencrypt/live/your.server.name/privkey.pem; # EDIT THIS
ssl_trusted_certificate /etc/letsencrypt/live/your.server.name/chain.pem; # EDIT THIS
include /etc/letsencrypt/options-ssl-nginx.conf;
}
```
**You need to make some edits again.** When you are done, run
```bash
$ sudo systemctl reload nginx
```
## SSL Certificate
If you chose Caddy as your web proxy SSL certificates are handled automatically and you can skip this step.
The easiest way to get an SSL certificate, if you don't have one already, is to [install](https://certbot.eff.org/instructions) `certbot` and run this:
```bash
# To use ECC for the private key,
# paste into /etc/letsencrypt/cli.ini:
# key-type = ecdsa
# elliptic-curve = secp384r1
$ sudo certbot -d your.server.name
```
[Automated renewal](https://eff-certbot.readthedocs.io/en/stable/using.html#automated-renewals) is usually preconfigured.
If using Cloudflare, configure instead the edge and origin certificates in dashboard. In case youre already running a website on the same Apache server, you can just copy-and-paste the SSL configuration from your main virtual host on port 443 into the above-mentioned vhost.
## You're done!
Now you can start Conduit with:
```bash
$ sudo systemctl start conduit
```
Set it to start automatically when your system boots with:
```bash
$ sudo systemctl enable conduit
```
## How do I know it works?
You can open <https://app.element.io>, enter your homeserver and try to register.
You can also use these commands as a quick health check.
```bash
$ curl https://your.server.name/_matrix/client/versions
# If using port 8448
$ curl https://your.server.name:8448/_matrix/client/versions
```
- To check if your server can talk with other homeservers, you can use the [Matrix Federation Tester](https://federationtester.matrix.org/).
If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.
# What's next?
## Audio/Video calls
For Audio/Video call functionality see the [TURN Guide](TURN.md).
## Appservices
If you want to set up an appservice, take a look at the [Appservice Guide](APPSERVICES.md).
+20 -58
View File
@@ -1,38 +1,44 @@
#### **Note: This list is not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give Conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the Conduwuit Matrix room and ask any pre-usage questions.**
### list of features, bug fixes, etc that conduwuit does that upstream does not: ### list of features, bug fixes, etc that conduwuit does that upstream does not:
- GitLab CI ported to GitHub Actions - GitLab CI ported to GitHub Actions
- Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness - Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
- Add a **lot** of other clippy and rustc lints and a rustfmt.toml file
- Has Renovate and significantly updates all dependencies possible - Has Renovate and significantly updates all dependencies possible
- Uses proper argon2 crate instead of questionable rust-argon2 crate - Uses proper argon2 crate instead of questionable rust-argon2 crate
- Improved and cleaned up logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, etc) - Improved and cleaned up logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, etc)
- Attempts and interest in removing extreme and unnecessary panics/unwraps/expects that can lead to denial of service or such (upstream and upstream contributors want this unusual behaviour for some reason) - Attempts and interest in removing extreme and unnecessary panics/unwraps/expects that can lead to denial of service or such (upstream and upstream contributors want this unusual behaviour for some reason)
- Merged and cleaned up upstream MRs that have been sitting for 6-12 months - Merged and cleaned up upstream MRs that have been sitting for 6-12 months
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much - Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
- Federated presence support and configurable local presence (via upstream MR)
- Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently (via upstream MR) - Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently (via upstream MR)
- Room version 11 support (via upstream MR) - Experimental room version 11 support (via upstream MR)
- Enabled all non-officially-supported room versions as experimental so we can at least attempt to join them
- Configurable guest registration including forbidding guest registrations if no admin user is created yet, respects allow registration setting, and an optional override setting with a default of no guest registrations allowed.
- Explicit startup error/warning if your configuration allows open registration without a token or such like Synapse - Explicit startup error/warning if your configuration allows open registration without a token or such like Synapse
- Improved RocksDB defaults to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage. - Improved RocksDB defaults to use new features that help with performance significantly, uses settings tailored to SSDs, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage.
- Updated Ruma to latest commit where possible, and add some unstable MSCs (some still require an implementation though)
- conduwuit allows MXIDs with `+` in them (thanks to Ruma update)
- Revamped admin room infrastructure and commands (via upstream MR) - Revamped admin room infrastructure and commands (via upstream MR)
- Admin room commands to delete room aliases and unpublish rooms from our room directory (via upstream MR) - Admin room commands to delete room aliases and unpublish rooms from our room directory (via upstream MR)
- Make spaces/hierarchy cache use cache_capacity_modifier instead of hardcoded small value - Make spaces/hierarchy cache use cache_capacity_modifier instead of hardcoded small value
- Make PDU appending, building, etc asynchronous
- Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR) - Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR)
- Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request) - Add *optional* feature flag to enable zstd HTTP body compression
- Add support for querying both Matrix SRV records, the deprecated `_matrix` record and `_matrix-fed` record if necessary - Add support for querying both Matrix SRV records, the deprecated `_matrix` record and `_matrix-fed` record if necessary
- Add config option for device name federation with a privacy-friendly default (disabled) - Add config option for device name federation with a privacy-friendly default (disabled)
- Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy - Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy
- Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy - Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy
- Add support for listening on a UNIX socket for performance and host security with proper default permissions (660) - Add support for listening on a UNIX socket for performance and host security with proper default permissions (660)
- Add missing `destination` key to all `X-Matrix` `Authorization` requests (spec compliance issue) - Add missing `destination` key to all `X-Matrix` `Authorization` requests (spec compliance issue)
- Fix spec compliance issue with servers being able to fetch remote user profiles over federation for users who don't belong to our server (`/_matrix/federation/v1/query/profile`)
- Use aggressive build-time performance optimisations for release builds (1 codegen unit, no debug, fat LTO, etc, and optimise all crates with same) - Use aggressive build-time performance optimisations for release builds (1 codegen unit, no debug, fat LTO, etc, and optimise all crates with same)
- Raise various hardcoded timeouts in codebase that were way too short, making some things like room joins and client bugs error less or none at all than they should - Raise various hardcoded timeouts in codebase that were way too short, making some things like room joins and client bugs error less or none at all than they should
- Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes) (`ForceDeviceListUpdates`) - Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes) (`ForceDeviceListUpdates`)
- Declare various missing Matrix versions and features at `/_matrix/client/versions` - Declare various missing Matrix versions and features at `/_matrix/client/versions`
- Add support for serving server and client well-known files from conduwuit using `well_known_client` and `well_known_server` options - Add support for serving server and client well-known files from conduwuit using `well_known_client` and `well_known_server` options
- Add non-standard sliding sync proxy health check (?) endpoint at `/client/server.json` that some clients such as Element Web query using the `well_known_client` or `well_known_server` config options
- Send a User-Agent on all of our requests (`conduwuit/0.7.0-alpha+conduwuit-0.1.1`) which strangely was not done upstream since forever. Some providers consider no User-Agent suspicious and block said requests. - Send a User-Agent on all of our requests (`conduwuit/0.7.0-alpha+conduwuit-0.1.1`) which strangely was not done upstream since forever. Some providers consider no User-Agent suspicious and block said requests.
- Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic - Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic
- Basic binary commands like `conduwuit --version` work (interested in expanding it more)
- Allow HEAD HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests) - Allow HEAD HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) - Purge unmaintained/irrelevant/broken database backends (heed, sled, persy)
- webp support for images - webp support for images
@@ -40,6 +46,7 @@
- Prevent admin credential commands like reset password and deactivate user from modifying non-local users (https://gitlab.com/famedly/conduit/-/issues/377) - Prevent admin credential commands like reset password and deactivate user from modifying non-local users (https://gitlab.com/famedly/conduit/-/issues/377)
- Fixed spec compliance issue with room version 8 - 11 joins (https://github.com/matrix-org/synapse/issues/16717 / https://github.com/matrix-org/matrix-spec/issues/1708) - Fixed spec compliance issue with room version 8 - 11 joins (https://github.com/matrix-org/synapse/issues/16717 / https://github.com/matrix-org/matrix-spec/issues/1708)
- Add basic cache eviction for true destinations when requests fail if we use a cached destination (e.g. a server has modified their well-known and we're still connecting to the old destination) - Add basic cache eviction for true destinations when requests fail if we use a cached destination (e.g. a server has modified their well-known and we're still connecting to the old destination)
- Only follow 6 redirects total in our default reqwest ClientBuilder
- Generate passwords with 25 characters instead of 15 - Generate passwords with 25 characters instead of 15
- Add missing `reason` field to user ban events (`/ban`) - Add missing `reason` field to user ban events (`/ban`)
- For all [`/report`](https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room. - For all [`/report`](https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
@@ -49,61 +56,16 @@
- Revamp example config, adding a lot of config options available (still some missing) - Revamp example config, adding a lot of config options available (still some missing)
- Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10 - Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
- Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work) - Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work)
- Config option `ip_range_denylist` to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security (note: this is not a guaranteed protection, and you should be using a firewall with zones if you want guaranteed protection as doing this on the application level is prone to bypasses). - Config option `ip_range_denylist` to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security.
- Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`) - Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`)
- Assume well-knowns are broken if they exceed past 10000 characters. - Assume well-knowns are broken if they exceed past 10000 characters.
- Basic validation/checks on user-specified room aliases and custom room ID creations - Basic validation/checks on user-specified room aliases and custom room ID creations
- Warn on unknown config options specified - Warn on unknown config options specified
- Add support for preventing certain room alias names and usernames using regex (via upstream MR) and extended to custom room IDs
- Revamp appservice registration to ruma's `Registration` type which fixes various appservice registration issues, including fixing crashing upon no URL specified (via upstream MR)
- URL preview support (via upstream MR) with various improvements - URL preview support (via upstream MR) with various improvements
- Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing - Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing, and ask systemd for more time to shutdown if needed to prevent systemd's default [`TimeoutStopSec=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=) of 90 seconds from killing conduwuit
- Bumped default max_concurrent_requests to 500
- Add support for the deprecated `user` identifier field for all `/login` requests
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047) - Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047)
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature - Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, as a moderation feature
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
- Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations
- Add admin command to bulk delete media via a codeblock list of MXC URLs.
- Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
- Add `!admin` as a way to call the Conduit admin bot
- Add support for listening on multiple TCP ports
- Add admin command to list all the rooms a local user is joined in
- Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room
- Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
- Startup check if conduwuit running in a container and is listening on 127.0.0.1
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure only by environment variables and no longer need to set `CONDUIT_CONFIG` to an empty string.
- Config option to change Conduit's behaviour of homeserver key fetching (`query_trusted_key_servers_first`). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa.
- Implement database flush and cleanup Conduit operations when using RocksDB
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers may still call
- Commandline argument to specify the path to a config file
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline
- Update rusqlite/sqlite (not that you should be using it)
- Disable update check by default as it's not useful for conduwuit
- Config option to disable incoming remote read receipts if desired
- Extend clear cache admin command to support clearing DNS and TLS name override caches
- Responsive outgoing read receipt EDU support
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS queries, significantly improving federation latency/ping and cache DNS results using hickory-dns / hickory-resolver
- Store the sender user with the MXC URL for all media uploads (`/upload`) (not for thumbnails or media requests which are unauthenticated)
- Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
- Implement RocksDB online backups via admin command
- Implement RocksDB write buffer corking and coalescing in database write-heavy areas
- Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults
- Implement config option to auto join rooms upon registration
- Overall significant database, Client-Server, and federation performance and latency improvements
- Outgoing read receipt and private read receipt support (EDU)
- Outgoing typing indicator support (EDU)
- Outgoing and local presence support (EDU)
- **Opt-in** Sentry.io telemetry and metrics, mainly used for crash reporting
- Add `/_conduwuit/server_version` route to return the version of Conduwuit without relying on the federation API `/_matrix/federation/v1/version`
- Add configurable RocksDB recovery modes to aid in recovering corrupte RocksDB database
- Config option to forbid publishing rooms to the room directory (`lockdown_public_room_directory`) except for admins
- Don't allow `m.call.invite` events to be sent in public rooms (prevents calling the entire room)
- On new public room creations, only allow moderators to send `m.call.invite`, `org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events
- Stop sending `make_join` requests on room joins if 15 servers respond with `M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for us
- Admin debug command to send a federation request/ping to a server's `/_matrix/federation/v1/version` endpoint and measures the latency it took
- Implement building Conduwuit with jemalloc or hardened_malloc light variant, and produce CI builds with jemalloc or hardened_malloc, for performance and/or security
- Significant RocksDB tuning and improvements tailored to maximising Conduwuit performance with RocksDB
- Implement unstable MSC2666 support for querying mutual rooms with a user
- Add admin command to fetch a server's `/.well-known/matrix/support` file
- Send `Cache-Control` response header with immutable and 1 year cache length for all media requests to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
- Forbid the admin room from being made public
- Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
- Implement `include_state` search criteria support for `/search` requests (response now can include room states)
+42 -39
View File
@@ -1,20 +1,10 @@
# conduwuit # conduwuit
[![CI and Artifacts](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml)
<!-- ANCHOR: catchphrase -->
### a well maintained fork of [Conduit](https://conduit.rs/) ### a well maintained fork of [Conduit](https://conduit.rs/)
<!-- ANCHOR_END: catchphrase -->
Visit the [Conduwuit documentation](https://conduwuit.puppyirl.gay/) for more information.
Alternatively you can open [docs/introduction.md](docs/introduction.md) in this repository.
<!-- ANCHOR: body -->
#### What is Matrix? #### What is Matrix?
[Matrix](https://matrix.org) is an open network for secure and decentralized [Matrix](https://matrix.org) is an open network for secure and decentralized
communication. Users from every Matrix homeserver can chat with users from all communication. Users from every Matrix homeserver can chat with users from all
other Matrix servers. You can even use bridges (also called Matrix Appservices) other Matrix servers. You can even use bridges (also called Matrix appservices)
to communicate with users outside of Matrix, like a community on Discord. to communicate with users outside of Matrix, like a community on Discord.
#### What is the goal? #### What is the goal?
@@ -25,29 +15,46 @@ friends or company.
#### Can I try it out? #### Can I try it out?
An official conduwuit server ran by me is available at transfem.dev ([element.transfem.dev](https://element.transfem.dev) / [cinny.transfem.dev](https://cinny.transfem.dev)) There are no public conduwuit homeservers available, however conduwuit is incredibly simple to install. It's just a binary, a config file, and a database path.
#### What is the current status? #### What is the current status?
conduwuit is a fork of Conduit which is in beta, meaning you can join and participate in most conduwuit is a fork of Conduit which is in beta, meaning you can join and participate in most
Matrix rooms, but not all features are supported and you might run into bugs Matrix rooms, but not all features are supported and you might run into bugs
from time to time. from time to time. conduwuit attempts to fix and improve the majority of upstream Conduit bugs
or UX issues that are taking too long to be resolved, or unnecessary Matrix or developer
politics halting simple things from being merged or fixed, and general inactivity.
There are still a few nice to have features missing that some users may notice:
- Outgoing read receipts and typing indicators (receiving works)
#### What's different about your fork than upstream Conduit?
See [DIFFERENCES.md](DIFFERENCES.md)
#### Why does this fork exist? Why don't you contribute back upstream? #### Why does this fork exist? Why don't you contribute back upstream?
I now intend on contributing back as time and mental energy sees fit, but my fork still exists as a way to: I have tried, but:
- avoid unnecessary Matrix and general developer politics - unnecessary Matrix / developer politics
- avoid bikeshedding unnecessary or irrelevant things in upstream MRs - bikeshedding unnecessary or irrelevant things in MRs
- Fast tracked bug fixes, performance improvements, security improvements, and new features - disagreement with how the upstream project is maintained including the codebase
- Have early access to MRs that may not be suitable/acceptable for Conduit (e.g. too niche, too advanced for general users, only being blocked due to pending on contributor actions that we can fix ourselves downstream, pending Matrix spec stuff, etc) - upstream maintainer inactivity
- Support unspecced or WIP features - questionable community members
- Have official support for other OS's like Windows, macOS, and BSD. - lack of MR reviews or issue triaging and no upstream maintainer interest in receiving help
- Have a **stable** testing ground for some MRs or new features and bug fixes - severe bugs, including denial of service and other likely vulnerabilities, not being merged due to things mentioned above
- no interest in adding co-maintainers to help out
And various other reasons that may not be listed here. are what are keeping me from contributing. If the state of the upstream project improves, I'm
<!-- ANCHOR_END: body --> willing to start contributing again. As is, I think if folks want a more polished and well-kept version of Conduit, conduwuit exists for that.
#### How can I deploy my own?
- Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md)
- Nix/NixOS: [nix/README.md](nix/README.md)
If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md).
<!-- ANCHOR: footer -->
#### How can I contribute? #### How can I contribute?
1. Look for an issue you would like to work on and make sure it's not assigned 1. Look for an issue you would like to work on and make sure it's not assigned
@@ -55,7 +62,8 @@ And various other reasons that may not be listed here.
2. Ask someone to assign the issue to you (comment on the issue or chat in 2. Ask someone to assign the issue to you (comment on the issue or chat in
[#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)) [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay))
3. Fork the repo and work on the issue. 3. Fork the repo and work on the issue.
4. Submit a PR (please keep contributions to the GitHub repo, main development is done here, not the GitLab repo which exists just as a mirror. If you are avoiding GitHub, feel free to join our Matrix chat to get your patch in.) 4. Submit a PR (please keep contributions to the GitHub repo, main development is done here,
not the GitLab repo which exists just as a mirror.)
#### Contact #### Contact
@@ -65,23 +73,18 @@ If you run into any question, feel free to
#### Donate #### Donate
- Liberapay: <https://liberapay.com/girlbossceo> Liberapay: <https://liberapay.com/girlbossceo>\
- Ko-fi: <https://ko-fi.com/puppygock> Ko-fi: <https://ko-fi.com/puppygock>\
- GitHub Sponsors: <https://github.com/sponsors/girlbossceo> GitHub Sponsors: <https://github.com/sponsors/girlbossceo>
#### Logo #### Logo
No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3). Banner image is directly from [this cohost post](https://cohost.org/RatBaby/post/1028290-finally-a-flag-for). No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3).
#### Is it conduwuit or Conduwuit?
Both.
#### Mirrors of conduwuit #### Mirrors of conduwuit
- GitHub: <https://github.com/girlbossceo/conduwuit> GitHub: https://github.com/girlbossceo/conduwuit
- GitLab: <https://gitlab.com/girlbossceo/conduwuit> GitLab: https://gitlab.com/girlbossceo/conduwuit
- git.gay: <https://git.gay/june/conduwuit> git.gay: https://git.gay/june/conduwuit
- Codeberg: <https://codeberg.org/girlbossceo/conduwuit> Codeberg: https://codeberg.org/girlbossceo/conduwuit
- sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit> sourcehut: https://git.sr.ht/~girlbossceo/conduwuit
<!-- ANCHOR_END: footer -->
View File
Executable → Regular
+2 -2
View File
@@ -17,7 +17,7 @@ env \
-C "$(git rev-parse --show-toplevel)" \ -C "$(git rev-parse --show-toplevel)" \
docker build \ docker build \
--tag "$OCI_IMAGE" \ --tag "$OCI_IMAGE" \
--file tests/complement/Dockerfile \ --file complement/Dockerfile \
. .
# It's okay (likely, even) that `go test` exits nonzero # It's okay (likely, even) that `go test` exits nonzero
@@ -25,7 +25,7 @@ set +o pipefail
env \ env \
-C "$COMPLEMENT_SRC" \ -C "$COMPLEMENT_SRC" \
COMPLEMENT_BASE_IMAGE="$OCI_IMAGE" \ COMPLEMENT_BASE_IMAGE="$OCI_IMAGE" \
go test -vet=all -timeout 30m -json ./tests | tee "$LOG_FILE" go test -json ./tests | tee "$LOG_FILE"
set -o pipefail set -o pipefail
# Post-process the results into an easy-to-compare format # Post-process the results into an easy-to-compare format
+30 -21
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -eo pipefail set -euo pipefail
# The first argument must be the desired installable # The first argument must be the desired installable
INSTALLABLE="$1" INSTALLABLE="$1"
@@ -8,34 +8,43 @@ INSTALLABLE="$1"
# Build the installable and forward any other arguments too # Build the installable and forward any other arguments too
nix build -L "$@" nix build -L "$@"
if [ ! -z "$ATTIC_TOKEN" ]; then if [ ! -z ${ATTIC_TOKEN+x} ]; then
nix run --inputs-from . attic -- \
login \ nix run --inputs-from . attic -- login \
conduit \ conduit \
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduit}" \ https://attic.kennel.juneis.dog/conduit \
"$ATTIC_TOKEN" "$ATTIC_TOKEN"
# Push the target installable and its build dependencies push_args=(
nix run --inputs-from . attic -- \ # Attic and its build dependencies
push \ "$(nix path-info --inputs-from . attic)"
conduit \ "$(nix path-info --inputs-from . attic --derivation)"
"$(nix path-info "$INSTALLABLE" --derivation)" \
"$(nix path-info "$INSTALLABLE")"
# The target installable and its build dependencies
"$(nix path-info "$INSTALLABLE" --derivation)"
"$(nix path-info "$INSTALLABLE")"
)
nix run --inputs-from . attic -- push conduit "${push_args[@]}"
# push to "conduwuit" too # push to "conduwuit" too
nix run --inputs-from . attic -- \ nix run --inputs-from . attic -- login \
login \ conduwuit \
conduwuit \ https://attic.kennel.juneis.dog/conduwuit \
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduwuit}" \
"$ATTIC_TOKEN" "$ATTIC_TOKEN"
# Push the target installable and its build dependencies push_args=(
nix run --inputs-from . attic -- \ # Attic and its build dependencies
push \ "$(nix path-info --inputs-from . attic)"
conduwuit \ "$(nix path-info --inputs-from . attic --derivation)"
"$(nix path-info "$INSTALLABLE" --derivation)" \
# The target installable and its build dependencies
"$(nix path-info "$INSTALLABLE" --derivation)"
"$(nix path-info "$INSTALLABLE")" "$(nix path-info "$INSTALLABLE")"
)
nix run --inputs-from . attic -- push conduwuit "${push_args[@]}"
else else
echo "\$ATTIC_TOKEN is unset, skipping uploading to the binary cache" echo "\$ATTIC_TOKEN is unset, skipping uploading to the binary cache"
fi fi
-18
View File
@@ -1,18 +0,0 @@
[book]
title = "conduwuit"
description = "conduwuit, which is a fork of Conduit, is a simple, fast and reliable chat server for the Matrix protocol"
language = "en"
multilingual = false
src = "docs"
[build]
build-dir = "public"
create-missing = true
[output.html]
git-repository-url = "https://github.com/girlbossceo/conduwuit"
edit-url-template = "https://github.com/girlbossceo/conduwuit/edit/main/{path}"
git-repository-icon = "fa-github-square"
[output.html.search]
limit-results = 15
-1
View File
@@ -1 +0,0 @@
too-many-lines-threshold = 700
+46
View File
@@ -0,0 +1,46 @@
FROM rust:1.75.0
WORKDIR /workdir
RUN apt-get update && apt-get install -y --no-install-recommends \
libclang-dev
COPY Cargo.toml Cargo.toml
COPY Cargo.lock Cargo.lock
COPY src src
RUN cargo build --release \
&& mv target/release/conduit conduit \
&& rm -rf target
# Install caddy
RUN apt-get update \
&& apt-get install -y \
debian-keyring \
debian-archive-keyring \
apt-transport-https \
curl \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/gpg.key' \
| gpg --dearmor -o /usr/share/keyrings/caddy-testing-archive-keyring.gpg \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/debian.deb.txt' \
| tee /etc/apt/sources.list.d/caddy-testing.list \
&& apt-get update \
&& apt-get install -y caddy
COPY conduit-example.toml conduit.toml
COPY complement/caddy.json caddy.json
ENV SERVER_NAME=localhost
ENV CONDUIT_CONFIG=/workdir/conduit.toml
RUN sed -i "s/port = 6167/port = 8008/g" conduit.toml
RUN echo "log = \"warn,_=off,sled=off\"" >> conduit.toml
RUN sed -i "s/address = \"127.0.0.1\"/address = \"0.0.0.0\"/g" conduit.toml
EXPOSE 8008 8448
CMD uname -a && \
sed -i "s/#server_name = \"your.server.name\"/server_name = \"${SERVER_NAME}\"/g" conduit.toml && \
sed -i "s/your.server.name/${SERVER_NAME}/g" caddy.json && \
caddy start --config caddy.json > /dev/null && \
/workdir/conduit
+12
View File
@@ -0,0 +1,12 @@
# Complement
## What's that?
Have a look at [its repository](https://github.com/matrix-org/complement).
## How do I use it with Conduit?
The script at [`../bin/complement`](../bin/complement) has automation for this.
It takes a few command line arguments, you can read the script to find out what
those are.
+72
View File
@@ -0,0 +1,72 @@
{
"logging": {
"logs": {
"default": {
"level": "WARN"
}
}
},
"apps": {
"http": {
"https_port": 8448,
"servers": {
"srv0": {
"listen": [":8448"],
"routes": [{
"match": [{
"host": ["your.server.name"]
}],
"handle": [{
"handler": "subroute",
"routes": [{
"handle": [{
"handler": "reverse_proxy",
"upstreams": [{
"dial": "127.0.0.1:8008"
}]
}]
}]
}],
"terminal": true
}],
"tls_connection_policies": [{
"match": {
"sni": ["your.server.name"]
}
}]
}
}
},
"pki": {
"certificate_authorities": {
"local": {
"name": "Complement CA",
"root": {
"certificate": "/complement/ca/ca.crt",
"private_key": "/complement/ca/ca.key"
},
"intermediate": {
"certificate": "/complement/ca/ca.crt",
"private_key": "/complement/ca/ca.key"
}
}
}
},
"tls": {
"automation": {
"policies": [{
"subjects": ["your.server.name"],
"issuers": [{
"module": "internal"
}],
"on_demand": true
}, {
"issuers": [{
"module": "internal",
"ca": "local"
}]
}]
}
}
}
}
+44 -429
View File
@@ -2,8 +2,6 @@
# This is the official example config for conduwuit. # This is the official example config for conduwuit.
# If you use it for your server, you will need to adjust it to your own needs. # If you use it for your server, you will need to adjust it to your own needs.
# At the very least, change the server_name field! # At the very least, change the server_name field!
#
# This documentation can also be found at https://conduwuit.puppyirl.gay/configuration.html
# ============================================================================= # =============================================================================
[global] [global]
@@ -24,39 +22,18 @@
# YOU NEED TO EDIT THIS # YOU NEED TO EDIT THIS
#server_name = "your.server.name" #server_name = "your.server.name"
# Servers listed here will be used to gather public keys of other servers (notary trusted key servers). # Servers listed here will be used to gather public keys of other servers.
# # Generally, copying this exactly should be enough. (Currently, conduwuit doesn't
# The default behaviour for conduwuit is to attempt to query trusted key servers before querying the individual servers. # support batched key requests, so this list should only contain Synapse
# This is done for performance reasons, but if you would like to query individual servers before the notary servers # servers.) Defaults to `matrix.org`
# configured below, set to
#
# (Currently, conduwuit doesn't support batched key requests, so this list should only contain Synapse servers)
# Defaults to `matrix.org`
# trusted_servers = ["matrix.org"] # trusted_servers = ["matrix.org"]
# Sentry.io crash/panic reporting, performance monitoring/metrics, etc.
# Conduwuit's Sentry reporting endpoint is o4506996327251968.ingest.us.sentry.io
#
# Defaults to false
#sentry = false
# Report your Conduwuit server_name in Sentry.io crash reports and metrics
#
# Defaults to false
#sentry_send_server_name = false
# Performance monitoring/tracing sample rate for Sentry.io
#
# Note that too high values may impact performance, and can be disabled by setting it to 0.0
#
# Defaults to 0.15
#sentry_traces_sample_rate = 0.15
### Database configuration ### Database configuration
# This is the only directory where conduwuit will save its data, including media # This is the only directory where conduwuit will save its data, including media
database_path = "/var/lib/matrix-conduit/" database_path = "/var/lib/conduwuit/"
# Database backend: Only rocksdb and sqlite are supported. Please note that sqlite # Database backend: Only rocksdb and sqlite are supported. Please note that sqlite
# will perform significantly worse than rocksdb as it is not intended to be used the # will perform significantly worse than rocksdb as it is not intended to be used the
@@ -64,13 +41,13 @@ database_path = "/var/lib/matrix-conduit/"
database_backend = "rocksdb" database_backend = "rocksdb"
### Network ### Network
# The port(s) conduwuit will be running on. You need to set up a reverse proxy such as # The port conduwuit will be running on. You need to set up a reverse proxy such as
# Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be # Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be
# forwarded to the conduwuit instance running on this port # forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this. # Docker users: Don't change this, you'll need to map an external port to this.
# To listen on multiple ports, specify a vector e.g. [8080, 8448]
port = 6167 port = 6167
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be # default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
@@ -103,31 +80,15 @@ max_request_size = 20_000_000 # in bytes
#unix_socket_perms = 660 #unix_socket_perms = 660
# Set this to true for conduwuit to compress HTTP response bodies using zstd. # Set this to true for conduwuit to compress HTTP response bodies using zstd.
# This option does nothing if conduwuit was not built with `zstd_compression` feature. # Please be aware that enabling HTTP compression may weaken or even defeat TLS.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this. # Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this. # See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
zstd_compression = false zstd_compression = false
# Set this to true for conduwuit to compress HTTP response bodies using gzip.
# This option does nothing if conduwuit was not built with `gzip_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
gzip_compression = false
# Set this to true for conduwuit to compress HTTP response bodies using brotli.
# This option does nothing if conduwuit was not built with `brotli_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
brotli_compression = false
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to. # Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to.
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security. # Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
# #
# To disable, set this to be an empty vector (`[]`). # To disable, set this to be an empty vector (`[]`).
# Please be aware that this is *not* a guarantee. You should be using a firewall with zones as doing this on the application layer may have bypasses.
# #
# Currently this does not account for proxies in use like Synapse does. # Currently this does not account for proxies in use like Synapse does.
ip_range_denylist = [ ip_range_denylist = [
@@ -153,25 +114,18 @@ ip_range_denylist = [
] ]
### Moderation / Privacy / Security ### Moderation / Privacy / Security
# Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically. # Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically.
# Defaults to false # For private homeservers, this is best at false.
allow_guest_registration = false allow_guest_registration = false
# Set to true to log guest registrations in the admin room.
# Defaults to false as it may be noisy or unnecessary.
log_guest_registrations = false
# Set to true to allow guest registrations/users to auto join any rooms specified in `auto_join_rooms`
# Defaults to false
allow_guests_auto_join_rooms = false
# Vector list of servers that conduwuit will refuse to download remote media from. # Vector list of servers that conduwuit will refuse to download remote media from.
# No default. # No default.
# prevent_media_downloads_from = ["example.com", "example.local"] # prevent_media_downloads_from = ["example.com", "example.local"]
# Enables registration. If set to false, no users can register on this # Enables open registration. If set to false, no users can register on this
# server. # server.
# If set to true without a token configured, users can register with no form of 2nd- # If set to true without a token configured, users can register with no form of 2nd-
# step only if you set # step only if you set
@@ -197,32 +151,6 @@ registration_token = "change this token for something specific to your server"
# defaults to true # defaults to true
# allow_room_creation = true # allow_room_creation = true
# controls whether non-admin local users are forbidden from sending room invites (local and remote),
# and if non-admin users can receive remote room invites. admins are always allowed to send and receive all room invites.
# defaults to false
# block_non_admin_invites = false
# List of forbidden username patterns/strings. Values in this list are matched as *contains*.
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
# have a forbidden username.
# No default.
# forbidden_usernames = []
# List of forbidden room aliases and room IDs as patterns/strings. Values in this list are matched as *contains*.
# This is checked upon room alias creation, custom room ID creation if used, and startup as warnings if any room aliases
# in your database have a forbidden room alias/ID.
# No default.
# forbidden_alias_names = []
# List of forbidden server names that we will block all client room joins, incoming federated room directory requests, incoming federated invites for, and incoming federated joins. This check is applied on the room ID, room alias, sender server name, and sender user's server name.
# Basically "global" ACLs. For our user (client) checks, admin users are allowed.
# No default.
# forbidden_remote_server_names = []
# List of forbidden server names that we will block all outgoing federated room directory requests for. Useful for preventing our users from wandering into bad servers or spaces.
# No default.
# forbidden_remote_room_directory_server_names = []
# Set this to true to allow your server's public room directory to be federated. # 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 # Set this to false to protect against /publicRooms spiders, but will forbid external users
# from viewing your server's public room directory. If federation is disabled entirely # from viewing your server's public room directory. If federation is disabled entirely
@@ -233,12 +161,6 @@ allow_public_room_directory_over_federation = false
# authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders. # authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders.
allow_public_room_directory_without_auth = false allow_public_room_directory_without_auth = false
# Set this to true to lock down your server's public room directory and only allow admins to publish rooms to the room directory.
# Unpublishing is still allowed by all users with this enabled.
#
# Defaults to false
lockdown_public_room_directory = false
# Set this to true to allow federating device display names / allow external users to see your device display name. # Set this to true to allow federating device display names / allow external users to see your device display name.
# If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled. # If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled.
allow_device_name_federation = false allow_device_name_federation = false
@@ -249,7 +171,7 @@ allow_device_name_federation = false
url_preview_domain_contains_allowlist = [] url_preview_domain_contains_allowlist = []
# Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none. # Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com" # Note: This is an *explicit* match, not a ccontains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so. # Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_explicit_allowlist = [] url_preview_domain_explicit_allowlist = []
@@ -258,97 +180,45 @@ url_preview_domain_explicit_allowlist = []
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so. # Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_url_contains_allowlist = [] url_preview_url_contains_allowlist = []
# Vector list of explicit domains not allowed to send requests to for URL previews. Defaults to none. # Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 1MB (1_000_000 bytes)
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com" url_preview_max_spider_size = 1_000_000
# The denylist is checked first before allowlist. Setting this to "*" will not do anything.
url_preview_domain_explicit_denylist = []
# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 384KB (384_000 bytes)
url_preview_max_spider_size = 384_000
# Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false. # Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false.
# Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched. # Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched.
# Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain. # Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain.
url_preview_check_root_domain = false url_preview_check_root_domain = false
# Config option to allow or disallow incoming federation requests that obtain the profiles
# of our local users from `/_matrix/federation/v1/query/profile`
#
# This is inherently false if `allow_federation` is disabled
#
# Defaults to true
allow_profile_lookup_federation_requests = true
### Misc ### Misc
# max log level for conduwuit. allows debug, info, warn, or error # max log level for conduwuit. allows debug, info, warn, or error
# see also: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
# **Caveat**:
# For release builds, the tracing crate is configured to only implement levels higher than error to avoid unnecessary overhead in the compiled binary from trace macros.
# For debug builds, this restriction is not applied.
#
# Defaults to "warn"
#log = "warn" #log = "warn"
# controls whether encrypted rooms and events are allowed (default true) # controls whether encrypted rooms and events are allowed (default true)
#allow_encryption = false #allow_encryption = false
# if enabled, conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable` # conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable`
# for any new announcements made. Despite the name, this is not an update check # for any new announcements made. Despite the name, this is not an update check
# endpoint, it is simply an announcement check endpoint. # endpoint, it is simply an announcement check endpoint. I don't plan on using
# Defaults to false. # this so feel free to disable it.
#allow_check_for_updates = false allow_check_for_updates = true
# Enables adding the lightning bolt emoji (⚡️) to all newly registered users'
# initial display names.
enable_lightning_bolt = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#well_known_server = "matrix.example.com:443"
#well_known_client = "https://matrix.example.com"
# Note that whatever you put will show up in the well-known JSON values.
# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit. # Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 3 - 5, and 11. # conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 1 - 5, and 11.
# Defaults to true. # Defaults to true.
#allow_unstable_room_versions = true #allow_unstable_room_versions = true
# Option to control adding arbitrary text to the end of the user's displayname upon registration with a space before the text.
# This was the lightning bolt emoji option, just replaced with support for adding your own custom text or emojis.
# To disable, set this to "" (an empty string)
# Defaults to "🏳️‍⚧️" (trans pride flag)
#new_user_displayname_suffix = "🏳️‍⚧️"
# Option to control whether conduwuit will query your list of trusted notary key servers (`trusted_servers`) for
# remote homeserver signing keys it doesn't know *first*, or query the individual servers first before falling back to the trusted
# key servers.
#
# The former/default behaviour makes federated/remote rooms joins generally faster because we're querying a single (or list of) server
# that we know works, is reasonably fast, and is reliable for just about all the homeserver signing keys in the room. Querying individual
# servers may take longer depending on the general infrastructure of everyone in there, how many dead servers there are, etc.
#
# However, this does create an increased reliance on one single or multiple large entities as `trusted_servers` should generally
# contain long-term and large servers who know a very large number of homeservers.
#
# If you don't know what any of this means, leave this and `trusted_servers` alone to their defaults.
#
# Defaults to true as this is the fastest option for federation.
#query_trusted_key_servers_first = true
# List/vector of room **IDs** that conduwuit will make newly registered users join.
# The room IDs specified must be rooms that you have joined at least once on the server, and must be public.
#
# No default.
#auto_join_rooms = []
# Retry failed and incomplete messages to remote servers immediately upon startup. This is called bursting.
# If this is disabled, said messages may not be delivered until more messages are queued for that server.
# Do not change this option unless server resources are extremely limited or the scale of the server's
# deployment is huge. Do not disable this unless you know what you are doing.
#startup_netburst = true
# Limit the startup netburst to the most recent (default: 50) messages queued for each remote server. All older
# messages are dropped and not reattempted. The `startup_netburst` option must be enabled for this value to have
# any effect. Do not change this value unless you know what you are doing. Set this value to -1 to reattempt
# every message without trimming the queues; this may consume significant disk. Set this value to 0 to drop all
# messages without any attempt at redelivery.
#startup_netburst_keep = 50
### Generic database options
# Set this to any float value to multiply conduwuit's in-memory LRU caches with. # Set this to any float value to multiply conduwuit's in-memory LRU caches with.
# May be useful if you have significant memory to spare to increase performance. # May be useful if you have significant memory to spare to increase performance.
# Defaults to 1.0. # Defaults to 1.0.
@@ -356,35 +226,19 @@ allow_profile_lookup_federation_requests = true
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches. # Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
# May be useful if you have significant memory to spare to increase performance. # May be useful if you have significant memory to spare to increase performance.
# Defaults to 256.0 # Defaults to 300.0
#db_cache_capacity_mb = 256.0 #db_cache_capacity_mb = 300.0
# Interval in seconds when conduwuit will run database cleanup operations.
#
# For SQLite: this will flush the WAL by executing `PRAGMA wal_checkpoint(RESTART)` (https://www.sqlite.org/pragma.html#pragma_wal_checkpoint)
# For RocksDB: this will run `flush_opt` to flush database memtables to SST files on disk (https://docs.rs/rocksdb/latest/rocksdb/struct.DBCommon.html#method.flush_opt)
# These operations always run on shutdown.
#
# Defaults to 30 minutes (1800 seconds) to avoid IO amplification from too frequent cleanups
#cleanup_second_interval = 1800
### RocksDB options ### RocksDB options
# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage) # Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
#
# It is worth noting that by default, conduwuit will use RocksDB with Direct IO enabled. *Generally* speaking this improves performance as it bypasses buffered I/O (system page cache).
# However there is a potential chance that Direct IO may cause issues with database operations if your setup is uncommon. This has been observed with FUSE filesystems, and possibly ZFS filesystem.
# RocksDB generally deals/corrects these issues but it cannot account for all setups.
# If you experience any weird RocksDB issues, try enabling this option as it turns off Direct IO and feel free to report in the conduwuit Matrix room if this option fixes your DB issues.
# See https://github.com/facebook/rocksdb/wiki/Direct-IO for more information.
#
# Defaults to false
#rocksdb_optimize_for_spinning_disks = false #rocksdb_optimize_for_spinning_disks = false
# RocksDB log level. This is not the same as conduwuit's log level. This is the log level for the RocksDB engine/library # RocksDB log level. This is not the same as conduwuit's log level. This is the log level for RocksDB itself
# which show up in your database folder/path as `LOG` files. Defaults to error. conduwuit will typically log RocksDB errors as normal. # which show up in your database folder/path as `LOG` files. Defaults to warn. conduwuit will typically log RocksDB errors.
#rocksdb_log_level = "error" #rocksdb_log_level = "warn"
# Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB. # Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB.
#rocksdb_max_log_file_size = 4194304 #rocksdb_max_log_file_size = 4194304
@@ -392,271 +246,32 @@ allow_profile_lookup_federation_requests = true
# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0. # Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0 #rocksdb_log_time_to_roll = 0
# Amount of threads that RocksDB will use for parallelism on database operatons such as cleanup, sync, flush, compaction, etc. Set to 0 to use all your physical cores.
#
# Defaults to your CPU physical core count (not logical threads).
#rocksdb_parallelism_threads = 0
# Maximum number of LOG files RocksDB will keep. This must *not* be set to 0. It must be at least 1.
# Defaults to 3 as these are not very useful.
#rocksdb_max_log_files = 3
# Type of RocksDB database compression to use.
# Available options are "zstd", "zlib", "bz2" and "lz4"
# It is best to use ZSTD as an overall good balance between speed/performance, storage, IO amplification, and CPU usage.
# For more performance but less compression (more storage used) and less CPU usage, use LZ4.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# Defaults to "zstd"
#rocksdb_compression_algo = "zstd"
# Level of compression the specified compression algorithm for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
#rocksdb_compression_level = 32767
# Level of compression the specified compression algorithm for the bottommost level/data for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
# Since this is the bottommost level (generally old and least used data), it may be desirable to have a very
# high compression level here as it's lesss likely for this data to be used. Research your chosen compression algorithm.
#
#rocksdb_bottommost_compression_level = 32767
# Whether to enable RocksDB "bottommost_compression".
# At the expense of more CPU usage, this will further compress the database to reduce more storage.
# It is recommended to use ZSTD compression with this for best compression results.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# Defaults to false as this uses more CPU when compressing.
#rocksdb_bottommost_compression = false
# Database recovery mode (for RocksDB WAL corruption)
#
# Use this option when the server reports corruption and refuses to start. Set mode 2 (PointInTime)
# to cleanly recover from this corruption. The server will continue from the last good state,
# several seconds or minutes prior to the crash. Clients may have to run "clear-cache & reload" to
# account for the rollback. Upon success, you may reset the mode back to default and restart again.
# Please note in some cases the corruption error may not be cleared for at least 30 minutes of
# operation in PointInTime mode.
#
# As a very last ditch effort, if PointInTime does not fix or resolve anything, you can try mode
# 3 (SkipAnyCorruptedRecord) but this will leave the server in a potentially inconsistent state.
#
# The default mode 1 (TolerateCorruptedTailRecords) will automatically drop the last entry in the
# database if corrupted during shutdown, but nothing more. It is extraordinarily unlikely this will
# desynchronize clients. To disable any form of silent rollback set mode 0 (AbsoluteConsistency).
#
# The options are:
# 0 = AbsoluteConsistency
# 1 = TolerateCorruptedTailRecords (default)
# 2 = PointInTime (use me if trying to recover)
# 3 = SkipAnyCorruptedRecord (you now voided your Conduwuit warranty)
#
# See https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes for more information
#
# Defaults to 1 (TolerateCorruptedTailRecords)
#rocksdb_recovery_mode = 1
# Controls whether memory buffers are written to storage at the fixed interval set by `cleanup_period_interval`
# even when they are not full. Setting this will increase load on the storage backplane and is never advised
# under normal circumstances.
#rocksdb_periodic_cleanup = false
### Domain Name Resolution and Caching ### Presence
# Maximum entries stored in DNS memory-cache. The size of an entry may vary so please take care if # Config option to control local (your server only) presence updates/requests. Defaults to false.
# raising this value excessively. Only decrease this when using an external DNS cache. Please note
# that systemd does *not* count as an external cache, even when configured to do so.
#dns_cache_entries = 12288
# Minimum time-to-live in seconds for entries in the DNS cache. The default may appear high to most
# administrators; this is by design. Only decrease this if you are using an external DNS cache.
#dns_min_ttl = 10800
# Minimum time-to-live in seconds for NXDOMAIN entries in the DNS cache. This value is critical for
# the server to federate efficiently. NXDOMAIN's are assumed to not be returning to the federation
# and aggressively cached rather than constantly rechecked.
#dns_min_ttl_nxdomain = 86400
# The number of seconds to wait for a reply to a DNS query. Please note that recursive queries can
# take up to several seconds for some domains, so this value should not be too low.
#dns_timeout = 10
# Number of retries after a timeout.
#dns_attempts = 10
# Fallback to TCP on DNS errors. Set this to false if unsupported by nameserver.
#dns_tcp_fallback = true
# Enable to query all nameservers until the domain is found. Referred to as "trust_negative_responses" in hickory_resolver.
# This can avoid useless DNS queries if the first nameserver responds with NXDOMAIN or an empty NOERROR response.
#
# The default is to query one nameserver and stop (false).
#query_all_nameservers = true
### Request Timeouts, Connection Timeouts, and Connection Pooling
## Request Timeouts are HTTP response timeouts
## Connection Timeouts are TCP connection timeouts
##
## Connection Pooling Timeouts are timeouts for keeping an open idle connection alive.
## Connection pooling and keepalive is very useful for federation or other places where for performance reasons,
## we want to keep connections open that we will re-use frequently due to TCP and TLS 1.3 overhead/expensiveness.
##
## Generally these defaults are the best, but if you find a reason to need to change these they are here.
# Default/base connection timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 10 seconds
#request_conn_timeout = 10
# Default/base request timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 35 seconds
#request_timeout = 35
# Default/base max idle connections per host
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 1 as generally the same open connection can be re-used
#request_idle_per_host = 1
# Default/base idle connection pool timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 5 seconds
#request_idle_timeout = 5
# Federation well-known resolution connection timeout
#
# Defaults to 6 seconds
#well_known_conn_timeout = 6
# Federation HTTP well-known resolution request timeout
#
# Defaults to 10 seconds
#well_known_timeout = 10
# Federation client/server request timeout
# You most definitely want this to be high to account for extremely large room joins, slow homeservers, your own resources etc.
#
# Defaults to 300 seconds
#federation_timeout = 300
# Federation client/sender max idle connections per host
#
# Defaults to 1 as generally the same open connection can be re-used
#federation_idle_per_host = 1
# Federation client/sender idle connection pool timeout
#
# Defaults to 25 seconds
#federation_idle_timeout = 25
# Appservice URL request connection timeout
#
# Defaults to 120 seconds
#appservice_timeout = 120
# Appservice URL idle connection pool timeout
#
# Defaults to 300 seconds
#appservice_idle_timeout = 300
# Notification gateway pusher idle connection pool timeout
#
# Defaults to 15 seconds
#pusher_idle_timeout = 15
### Presence / Typing Indicators / Read Receipts
# Config option to control local (your server only) presence updates/requests. Defaults to true.
# Note that presence on conduwuit is very fast unlike Synapse's. # Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, this MUST be enabled. # If using outgoing presence, this MUST be enabled.
# #allow_local_presence = false
#allow_local_presence = true
# Config option to control incoming federated presence updates/requests. Defaults to true. # Config option to control incoming federated presence updates/requests. Defaults to false.
# This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true. # This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's. # Note that presence on conduwuit is very fast unlike Synapse's.
# #allow_incoming_presence = false
#allow_incoming_presence = true
# Config option to control outgoing presence updates/requests. Defaults to true. # Config option to control outgoing presence updates/requests. Defaults to false.
# This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true. # This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's. # Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, you MUST enable `allow_local_presence` as well. # If using outgoing presence, you MUST enable `allow_local_presence` as well.
# #
#allow_outgoing_presence = true # Warning: Outgoing federated presence is not spec compliant due to relying on PDUs and EDUs combined.
# Outgoing presence will not be very reliable due to this and any issues with federated outgoing presence are very likely attributed to this issue.
# Incoming presence and local presence are unaffected.
#allow_outgoing_presence = false
# Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes. # Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes.
#presence_idle_timeout_s = 300 #presence_idle_timeout_s = 300
# Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes. # Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes.
#presence_offline_timeout_s = 1800 #presence_offline_timeout_s = 1800
# Config option to control whether we should receive remote incoming read receipts.
# Defaults to true.
#allow_incoming_read_receipts = true
# Config option to control whether we should send read receipts to remote servers.
# Defaults to true.
#allow_outgoing_read_receipts = true
# Config option to control outgoing typing updates to federation. Defaults to true.
#allow_outgoing_typing = true
# Config option to control incoming typing updates from federation. Defaults to true.
#allow_incoming_typing = true
# Config option to control maximum time federation user can indicate typing.
#typing_federation_timeout_s = 30
# Config option to control minimum time local client can indicate typing. This does not override
# a client's request to stop typing. It only enforces a minimum value in case of no stop request.
#typing_client_timeout_min_s = 15
# Config option to control maximum time local client can indicate typing.
#typing_client_timeout_max_s = 45
# Other options not in [global]:
#
#
# Enables running conduwuit with direct TLS support
# It is strongly recommended you use a reverse proxy instead. This is primarily relevant for test suites like complement that require a private CA setup.
# [global.tls]
# certs = "/path/to/my/certificate.crt"
# key = "/path/to/my/private_key.key"
#
# Whether to listen and allow for HTTP and HTTPS connections (insecure!)
# This config option is only available if conduwuit was built with `axum_dual_protocol` feature (not default feature)
# Defaults to false
#dual_protocol = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#
#[global.well_known]
#server = "matrix.example.com:443"
#client = "https://matrix.example.com"
#
# A single contact and/or support page for /.well-known/matrix/support
# All options here are strings. Currently only supports 1 single contact.
# No default.
#
#support_page = ""
#support_role = ""
#support_email = ""
#support_mxid = ""
+1 -1
View File
@@ -5,7 +5,7 @@ Installation
------------ ------------
Information about downloading, building and deploying the Debian package, see Information about downloading, building and deploying the Debian package, see
the "Installing Conduit" section in the Deploying docs. the "Installing Conduit" section in [DEPLOY.md](../DEPLOY.md).
All following sections until "Setting up the Reverse Proxy" be ignored because All following sections until "Setting up the Reverse Proxy" be ignored because
this is handled automatically by the packaging. this is handled automatically by the packaging.
+1 -4
View File
@@ -1,5 +1,5 @@
[Unit] [Unit]
Description=conduwuit Matrix homeserver Description=Conduit Matrix homeserver
After=network-online.target After=network-online.target
[Service] [Service]
@@ -50,9 +50,6 @@ ExecStart=/usr/sbin/matrix-conduit
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
TimeoutStopSec=4m
TimeoutStartSec=4m
StartLimitInterval=1m StartLimitInterval=1m
StartLimitBurst=5 StartLimitBurst=5
+295 -3
View File
@@ -3,17 +3,18 @@ set -e
. /usr/share/debconf/confmodule . /usr/share/debconf/confmodule
CONDUIT_CONFIG_PATH=/etc/matrix-conduit
CONDUIT_CONFIG_FILE="${CONDUIT_CONFIG_PATH}/conduit.toml"
CONDUIT_DATABASE_PATH=/var/lib/matrix-conduit/ CONDUIT_DATABASE_PATH=/var/lib/matrix-conduit/
case "$1" in case "$1" in
configure) configure)
# Create the `_matrix-conduit` user if it does not exist yet. # Create the `_matrix-conduit` user if it does not exist yet.
if ! getent passwd _matrix-conduit > /dev/null ; then if ! getent passwd _matrix-conduit > /dev/null ; then
echo 'Adding system user for the Conduwuit Matrix homeserver' 1>&2 echo 'Adding system user for the Conduit Matrix homeserver' 1>&2
adduser --system --group --quiet \ adduser --system --group --quiet \
--home "$CONDUIT_DATABASE_PATH" \ --home "$CONDUIT_DATABASE_PATH" \
--disabled-login \ --disabled-login \
--shell "/usr/sbin/nologin" \
--force-badname \ --force-badname \
_matrix-conduit _matrix-conduit
fi fi
@@ -21,8 +22,299 @@ case "$1" in
# Create the database path if it does not exist yet and fix up ownership # Create the database path if it does not exist yet and fix up ownership
# and permissions. # and permissions.
mkdir -p "$CONDUIT_DATABASE_PATH" mkdir -p "$CONDUIT_DATABASE_PATH"
chown _matrix-conduit:_matrix-conduit -R "$CONDUIT_DATABASE_PATH" chown _matrix-conduit "$CONDUIT_DATABASE_PATH"
chmod 700 "$CONDUIT_DATABASE_PATH" chmod 700 "$CONDUIT_DATABASE_PATH"
if [ ! -e "$CONDUIT_CONFIG_FILE" ]; then
# Write the debconf values in the config.
db_get matrix-conduit/hostname
CONDUIT_SERVER_NAME="$RET"
db_get matrix-conduit/address
CONDUIT_ADDRESS="$RET"
db_get matrix-conduit/port
CONDUIT_PORT="$RET"
mkdir -p "$CONDUIT_CONFIG_PATH"
cat > "$CONDUIT_CONFIG_FILE" << EOF
# =============================================================================
# This is the official example config for conduwuit.
# If you use it for your server, you will need to adjust it to your own needs.
# At the very least, change the server_name field!
# =============================================================================
[global]
# The server_name is the pretty name of this server. It is used as a suffix for user
# and room ids. Examples: matrix.org, conduit.rs
# The Conduit server needs all /_matrix/ requests to be reachable at
# https://your.server.name/ on port 443 (client-server) and 8448 (federation).
# If that's not possible for you, you can create /.well-known files to redirect
# requests (delegation). See
# https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient
# and
# https://spec.matrix.org/v1.9/server-server-api/#getwell-knownmatrixserver
# for more information
# YOU NEED TO EDIT THIS
server_name = "${CONDUIT_SERVER_NAME}"
# Servers listed here will be used to gather public keys of other servers.
# Generally, copying this exactly should be enough. (Currently, conduwuit doesn't
# support batched key requests, so this list should only contain Synapse
# servers.) Defaults to `matrix.org`
# trusted_servers = ["matrix.org"]
### Database configuration
# This is the only directory where conduwuit will save its data, including media
database_path = "${CONDUIT_DATABASE_PATH}"
# Database backend: Only rocksdb and sqlite are supported. Please note that sqlite
# will perform significantly worse than rocksdb as it is not intended to be used the
# way it is by conduwuit. sqlite only exists for historical reasons.
database_backend = "rocksdb"
### Network
# The port conduwuit will be running on. You need to set up a reverse proxy such as
# Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be
# forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this.
port = ${CONDUIT_PORT}
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
# localhost (127.0.0.1 / ::1). If you are using Docker or a container NAT networking setup, you
# likely need this to be 0.0.0.0.
address = "${CONDUIT_ADDRESS}"
# How many requests conduwuit sends to other servers at the same time concurrently. Default is 500
# Note that because conduwuit is very fast unlike other homeserver implementations, setting this too
# high could inadvertently result in ratelimits kicking in, or overloading lower-end homeservers out there.
#
# A valid use-case for enabling this is if you have a significant amount of overall federation activity
# such as many rooms joined/tracked, and many servers in the true destination cache caused by that. Upon
# rebooting conduwuit, depending on how fast your resources are, client and incoming federation requests
# may timeout or be "stalled" for a period of time due to hitting the max concurrent requests limit from
# refreshing federation/destination caches and such.
#
# If you have a lot of active users on your homeserver, you will definitely need to raise this.
#
# No this will not speed up room joins.
#max_concurrent_requests = 500
# Max request size for file uploads
max_request_size = 20_000_000 # in bytes
# Uncomment unix_socket_path to listen on a UNIX socket at the specified path.
# If listening on a UNIX socket, you must remove/comment the 'address' key if defined and add your
# reverse proxy to the 'conduwuit' group, unless world RW permissions are specified with unix_socket_perms (666 minimum).
#unix_socket_path = "/run/conduwuit/conduwuit.sock"
#unix_socket_perms = 660
# Set this to true for conduwuit to compress HTTP response bodies using zstd.
# Please be aware that enabling HTTP compression may weaken or even defeat TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
zstd_compression = false
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to.
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
#
# To disable, set this to be an empty vector (`[]`).
#
# Currently this does not account for proxies in use like Synapse does.
ip_range_denylist = [
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"100.64.0.0/10",
"192.0.0.0/24",
"169.254.0.0/16",
"192.88.99.0/24",
"198.18.0.0/15",
"192.0.2.0/24",
"198.51.100.0/24",
"203.0.113.0/24",
"224.0.0.0/4",
"::1/128",
"fe80::/10",
"fc00::/7",
"2001:db8::/32",
"ff00::/8",
"fec0::/10",
]
### Moderation / Privacy / Security
# Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically.
# For private homeservers, this is best at false.
allow_guest_registration = false
# Vector list of servers that conduwuit will refuse to download remote media from.
# No default.
# prevent_media_downloads_from = ["example.com", "example.local"]
# Enables open registration. If set to false, no users can register on this
# server.
# If set to true without a token configured, users can register with no form of 2nd-
# step only if you set
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` to
# true in your config. If you would like
# registration only via token reg, please configure the `registration_token` key.
allow_registration = false
# Please note that an open registration homeserver with no second-step verification
# is highly prone to abuse and potential defederation by homeservers, including
# matrix.org.
# A static registration token that new users will have to provide when creating
# an account. If unset and `allow_registration` is true, registration is open
# without any condition. YOU NEED TO EDIT THIS.
registration_token = "change this token for something specific to your server"
# controls whether federation is allowed or not
# defaults to true
# allow_federation = true
# controls whether users are allowed to create rooms.
# appservices and admins are always allowed to create rooms
# defaults to true
# allow_room_creation = true
# 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 directory. If federation is disabled entirely
# (`allow_federation`), this is inherently false.
allow_public_room_directory_over_federation = false
# Set this to true to allow your server's public room directory to be queried without client
# authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders.
allow_public_room_directory_without_auth = false
# Set this to true to allow federating device display names / allow external users to see your device display name.
# If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled.
allow_device_name_federation = false
# Vector list of domains allowed to send requests to for URL previews. Defaults to none.
# Note: this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com" and "http://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_contains_allowlist = []
# Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a ccontains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_explicit_allowlist = []
# Vector list of URLs allowed to send requests to for URL previews. Defaults to none.
# Note that this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com/", "https://google.com/url?q=https://mymaliciousdomainexample.com", and "https://mymaliciousdomainexample.com/hi/google.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_url_contains_allowlist = []
# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 1MB (1_000_000 bytes)
url_preview_max_spider_size = 1_000_000
# Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false.
# Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched.
# Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain.
url_preview_check_root_domain = false
### Misc
# max log level for conduwuit. allows debug, info, warn, or error
#log = "warn"
# controls whether encrypted rooms and events are allowed (default true)
#allow_encryption = false
# conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable`
# for any new announcements made. Despite the name, this is not an update check
# endpoint, it is simply an announcement check endpoint. I don't plan on using
# this so feel free to disable it.
allow_check_for_updates = true
# Enables adding the lightning bolt emoji (⚡️) to all newly registered users'
# initial display names.
enable_lightning_bolt = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#well_known_server = "matrix.example.com:443"
#well_known_client = "https://matrix.example.com"
# Note that whatever you put will show up in the well-known JSON values.
# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 1 - 5, and 11.
# Defaults to true.
#allow_unstable_room_versions = true
# Set this to any float value to multiply conduwuit's in-memory LRU caches with.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 1.0.
#conduit_cache_capacity_modifier = 1.0
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 900.0
#db_cache_capacity_mb = 900.0
### RocksDB options
# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
#rocksdb_optimize_for_spinning_disks = false
# RocksDB log level. This is not the same as conduwuit's log level. This is the log level for RocksDB itself
# which show up in your database folder/path as `LOG` files. Defaults to warn. conduwuit will typically log RocksDB errors.
#rocksdb_log_level = "warn"
# Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB.
#rocksdb_max_log_file_size = 4194304
# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0
### Presence
# Config option to control local (your server only) presence updates/requests. Defaults to false.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, this MUST be enabled.
#allow_local_presence = false
# Config option to control incoming federated presence updates/requests. Defaults to false.
# This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
#allow_incoming_presence = false
# Config option to control outgoing presence updates/requests. Defaults to false.
# This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, you MUST enable `allow_local_presence` as well.
#
# Warning: Outgoing federated presence is not spec compliant due to relying on PDUs and EDUs combined.
# Outgoing presence will not be very reliable due to this and any issues with federated outgoing presence are very likely attributed to this issue.
# Incoming presence and local presence are unaffected.
#allow_outgoing_presence = false
# Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes.
#presence_idle_timeout_s = 300
# Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes.
#presence_offline_timeout_s = 1800
EOF
fi
;; ;;
esac esac
@@ -1,4 +1,6 @@
# Conduwuit for Docker # Deploy using Docker
> **Note:** To run and use Conduit you should probably use it with a Domain or Subdomain behind a reverse proxy (like Nginx, Traefik, Apache, ...) with a Lets Encrypt certificate.
## Docker ## Docker
@@ -7,7 +9,7 @@ To run conduwuit with Docker you can either build the image yourself or pull it
### Use a registry ### Use a registry
OCI images for conduwuit are available in the registries listed below. OCI images for conduwuit are available in the registries listed below. We recommend using the image tagged as `latest` from GitLab's own registry.
| Registry | Image | Size | Notes | | Registry | Image | Size | Notes |
| --------------- | --------------------------------------------------------------- | ----------------------------- | ---------------------- | | --------------- | --------------------------------------------------------------- | ----------------------------- | ---------------------- |
@@ -31,7 +33,7 @@ to pull it to your machine.
### Build using a Dockerfile ### Build using a dockerfile
The Dockerfile provided by Conduit has two stages, each of which creates an image. The Dockerfile provided by Conduit has two stages, each of which creates an image.
@@ -68,7 +70,7 @@ docker run -d -p 8448:6167 \
or you can use [docker-compose](#docker-compose). or you can use [docker-compose](#docker-compose).
The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../configuration.md). The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../conduit-example.toml).
You can pass in different env vars to change config values on the fly. You can even configure Conduit completely by using env vars, but for that you need You can pass in different env vars to change config values on the fly. You can even configure Conduit completely by using env vars, but for that you need
to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file. to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
@@ -87,7 +89,7 @@ When picking the traefik-related compose file, rename it so it matches `docker-c
rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want
for your server. for your server.
Additional info about deploying Conduit can be found [here](generic.md). Additional info about deploying Conduit can be found [here](../DEPLOY.md).
### Build ### Build
@@ -129,7 +131,7 @@ So...step by step:
1. Copy [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or 1. Copy [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or
[`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and [`docker-compose.override.yml`](docker-compose.override.yml) from the repository and remove `.for-traefik` (or `.with-traefik`) from the filename. [`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and [`docker-compose.override.yml`](docker-compose.override.yml) from the repository and remove `.for-traefik` (or `.with-traefik`) from the filename.
2. Open both files and modify/adjust them to your needs. Meaning, change the `CONDUIT_SERVER_NAME` and the volume host mappings according to your needs. 2. Open both files and modify/adjust them to your needs. Meaning, change the `CONDUIT_SERVER_NAME` and the volume host mappings according to your needs.
3. Create the `conduit.toml` config file, an example can be found [here](../configuration.md), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars. 3. Create the `conduit.toml` config file, an example can be found [here](../conduit-example.toml), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars.
4. Uncomment the `element-web` service if you want to host your own Element Web Client and create a `element_config.json`. 4. Uncomment the `element-web` service if you want to host your own Element Web Client and create a `element_config.json`.
5. Create the files needed by the `well-known` service. 5. Create the files needed by the `well-known` service.
@@ -1,5 +1,5 @@
# Conduit - Behind Traefik Reverse Proxy # Conduit - Behind Traefik Reverse Proxy
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -18,13 +18,12 @@ services:
# GIT_REF: origin/master # GIT_REF: origin/master
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- db:/var/lib/matrix-conduit - db:/var/lib/matrix-conduit/
#- ./conduwuit.toml:/etc/conduit.toml
networks: networks:
- proxy - proxy
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: your.server.name # EDIT THIS
CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit/
CONDUIT_DATABASE_BACKEND: rocksdb CONDUIT_DATABASE_BACKEND: rocksdb
CONDUIT_PORT: 6167 CONDUIT_PORT: 6167
CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
@@ -35,8 +34,7 @@ services:
#CONDUIT_MAX_CONCURRENT_REQUESTS: 100 #CONDUIT_MAX_CONCURRENT_REQUESTS: 100
#CONDUIT_LOG: warn,state_res=warn #CONDUIT_LOG: warn,state_res=warn
CONDUIT_ADDRESS: 0.0.0.0 CONDUIT_ADDRESS: 0.0.0.0
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above CONDUIT_CONFIG: '' # Ignore this
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container # We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here # to serve those two as static files. If you want to use a different way, delete or comment the below service, here
@@ -1,5 +1,5 @@
# Conduit - Traefik Reverse Proxy Labels # Conduit - Traefik Reverse Proxy Labels
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -1,5 +1,5 @@
# Conduit - Behind Traefik Reverse Proxy # Conduit - Behind Traefik Reverse Proxy
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -19,17 +19,19 @@ services:
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- db:/srv/conduit/.local/share/conduit - db:/srv/conduit/.local/share/conduit
#- ./conduwuit.toml:/etc/conduit.toml ### Uncomment if you want to use conduit.toml to configure Conduit
### Note: Set env vars will override conduit.toml values
# - ./conduit.toml:/srv/conduit/conduit.toml
networks: networks:
- proxy - proxy
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]' CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION : 'true' CONDUIT_ALLOW_REGISTRATION : 'true'
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above
### Uncomment and change values as desired ### Uncomment and change values as desired
# CONDUIT_ADDRESS: 0.0.0.0 # CONDUIT_ADDRESS: 0.0.0.0
# CONDUIT_PORT: 6167 # CONDUIT_PORT: 6167
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if you want to configure purely by env vars, set this to an empty string ''
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging # Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
# CONDUIT_LOG: info # default is: "warn,state_res=warn" # CONDUIT_LOG: info # default is: "warn,state_res=warn"
# CONDUIT_ALLOW_JAEGER: 'false' # CONDUIT_ALLOW_JAEGER: 'false'
@@ -39,7 +41,6 @@ services:
# CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit # CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit
# CONDUIT_WORKERS: 10 # CONDUIT_WORKERS: 10
# CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB # CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container # We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here # to serve those two as static files. If you want to use a different way, delete or comment the below service, here
@@ -1,5 +1,5 @@
# Conduit # Conduit
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -20,11 +20,10 @@ services:
ports: ports:
- 8448:6167 - 8448:6167
volumes: volumes:
- db:/var/lib/matrix-conduit - db:/var/lib/matrix-conduit/
#- ./conduwuit.toml:/etc/conduit.toml
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: your.server.name # EDIT THIS
CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit/
CONDUIT_DATABASE_BACKEND: rocksdb CONDUIT_DATABASE_BACKEND: rocksdb
CONDUIT_PORT: 6167 CONDUIT_PORT: 6167
CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
@@ -35,8 +34,7 @@ services:
#CONDUIT_MAX_CONCURRENT_REQUESTS: 400 #CONDUIT_MAX_CONCURRENT_REQUESTS: 400
#CONDUIT_LOG: warn,state_res=warn #CONDUIT_LOG: warn,state_res=warn
CONDUIT_ADDRESS: 0.0.0.0 CONDUIT_ADDRESS: 0.0.0.0
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above CONDUIT_CONFIG: '' # Ignore this
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# #
### Uncomment if you want to use your own Element-Web App. ### Uncomment if you want to use your own Element-Web App.
### Note: You need to provide a config.json for Element and you also need a second ### Note: You need to provide a config.json for Element and you also need a second
-13
View File
@@ -1,13 +0,0 @@
# Summary
- [Introduction](introduction.md)
- [Differences from upstream Conduit](differences.md)
- [Example configuration](configuration.md)
- [Deploying](deploying.md)
- [Generic](deploying/generic.md)
- [Debian](deploying/debian.md)
- [Docker](deploying/docker.md)
- [NixOS](deploying/nixos.md)
- [TURN](turn.md)
- [Appservices](appservices.md)
-5
View File
@@ -1,5 +0,0 @@
# Example configuration
``` toml
{{#include ../conduwuit-example.toml}}
```
-3
View File
@@ -1,3 +0,0 @@
# Deploying
This chapter describes various ways to deploy Conduwuit.
-1
View File
@@ -1 +0,0 @@
{{#include ../../debian/README.md}}
-165
View File
@@ -1,165 +0,0 @@
# Generic deployment documentation
### Please note that this documentation is not fully representative of conduwuit at the moment. Assume majority of it is outdated.
> ## Getting help
>
> If you run into any problems while setting up conduwuit, ask us
> in `#conduwuit:puppygock.gay` or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
## Installing conduwuit
You may simply download the binary that fits your machine. Run `uname -m` to see what you need.
Prebuilt binaries can be downloaded from the latest successful CI workflow on the main branch here: https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml?query=branch%3Amain+actor%3Agirlbossceo+is%3Asuccess+event%3Apush
Alternatively, you may compile the binary yourself. First, install any dependencies:
```bash
# Debian
$ sudo apt install libclang-dev build-essential
# RHEL
$ sudo dnf install clang
```
Then, `cd` into the source tree of conduit-next and run:
```bash
$ cargo build --release
```
## Adding a Conduit user
While Conduit can run as any user it is usually better to use dedicated users for different services. This also allows
you to make sure that the file permissions are correctly set up.
In Debian or RHEL, you can use this command to create a Conduit user:
```bash
sudo adduser --system conduit --group --disabled-login --no-create-home
```
## Forwarding ports in the firewall or the router
Conduit uses the ports 443 and 8448 both of which need to be open in the firewall.
If Conduit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.
## Setting up a systemd service
Now we'll set up a systemd service for Conduit, so it's easy to start/stop Conduit and set it to autostart when your
server reboots. Simply paste the default systemd service you can find below into
`/etc/systemd/system/conduit.service`.
```systemd
[Unit]
Description=Conduwuit Matrix Server
After=network.target
[Service]
Environment="CONDUIT_CONFIG=/etc/matrix-conduit/conduit.toml"
User=conduit
Group=conduit
RuntimeDirectory=conduit
RuntimeDirectoryMode=0750
Restart=always
ExecStart=/usr/local/bin/matrix-conduit
[Install]
WantedBy=multi-user.target
```
Finally, run
```bash
$ sudo systemctl daemon-reload
```
## Creating the Conduit configuration file
Now we need to create the Conduit's config file in `/etc/conduwuit/conduwuit.toml`. Paste this in **and take a moment
to read it. You need to change at least the server name.**
RocksDB (`rocksdb`) is the only supported database backend. SQLite only exists for historical reasons and is not recommended. Any performance issues, storage issues, database issues, etc will not be assisted if using SQLite and you will be asked to migrate to RocksDB first.
See the following example config at [conduwuit-example.toml](../configuration.md)
## Setting the correct file permissions
As we are using a Conduit specific user we need to allow it to read the config. To do that you can run this command on
Debian or RHEL:
```bash
sudo chown -R root:root /etc/matrix-conduit
sudo chmod 755 /etc/matrix-conduit
```
If you use the default database path you also need to run this:
```bash
sudo mkdir -p /var/lib/matrix-conduit/
sudo chown -R conduit:conduit /var/lib/matrix-conduit/
sudo chmod 700 /var/lib/matrix-conduit/
```
## Setting up the Reverse Proxy
Refer to the documentation or various guides online of your chosen reverse proxy software. A Caddy example will be provided as this is the recommended reverse proxy for new users and is very trivial.
### Caddy
Create `/etc/caddy/conf.d/conduwuit_caddyfile` and enter this (substitute for your server name).
```caddy
your.server.name, your.server.name:8448 {
# TCP
reverse_proxy 127.0.0.1:6167
# UNIX socket
#reverse_proxy unix//run/conduit/conduit.sock
}
```
That's it! Just start or enable the service and you're set.
```bash
$ sudo systemctl enable caddy
```
## You're done!
Now you can start Conduit with:
```bash
$ sudo systemctl start conduit
```
Set it to start automatically when your system boots with:
```bash
$ sudo systemctl enable conduit
```
## How do I know it works?
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your homeserver and try to register.
You can also use these commands as a quick health check.
```bash
$ curl https://your.server.name/_conduwuit/server_version
# If using port 8448
$ curl https://your.server.name:8448/_conduwuit/server_version
```
- To check if your server can talk with other homeservers, you can use the [Matrix Federation Tester](https://federationtester.matrix.org/).
If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.
# What's next?
## Audio/Video calls
For Audio/Video call functionality see the [TURN Guide](../turn.md).
## Appservices
If you want to set up an appservice, take a look at the [Appservice Guide](../appservices.md).
-30
View File
@@ -1,30 +0,0 @@
# Conduwuit for NixOS
Conduwuit can be acquired by Nix from various places:
* The `flake.nix` at the root of the repo
* The `default.nix` at the root of the repo
* From Conduwuit's binary cache
A binary cache for conduwuit that the CI/CD publishes to is available at the
following places (both are the same just different names):
```
https://attic.kennel.juneis.dog/conduit
conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
https://attic.kennel.juneis.dog/conduwuit
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
```
If specifying a URL in your flake, please use the GitHub remote: `github:girlbossceo/conduwuit`
The `flake.nix` and `default.nix` do not (currently) provide a NixOS module, so
(for now) [`services.matrix-conduit`][module] from Nixpkgs should be used to
configure Conduit.
If you want to run the latest code, you should get Conduwuit from the `flake.nix`
or `default.nix` and set [`services.matrix-conduit.package`][package]
appropriately.
[module]: https://search.nixos.org/options?channel=unstable&query=services.matrix-conduit
[package]: https://search.nixos.org/options?channel=unstable&query=services.matrix-conduit.package
-17
View File
@@ -1,17 +0,0 @@
# Conduwuit
{{#include ../README.md:catchphrase}}
{{#include ../README.md:body}}
#### What's different about your fork than upstream Conduit?
See [differences.md](differences.md)
#### How can I deploy my own?
- [Deployment options](deploying.md)
If you want to connect an Appservice to Conduwuit, take a look at the [appservices documentation](appservices.md).
{{#include ../README.md:footer}}
+6 -28
View File
@@ -40,26 +40,6 @@ name = "cargo-clippy"
group = "versions" group = "versions"
script = "cargo clippy -- --version" script = "cargo clippy -- --version"
[[task]]
name = "cargo-audit"
group = "versions"
script = "cargo audit --version"
[[task]]
name = "cargo-deb"
group = "versions"
script = "cargo deb --version"
[[task]]
name = "lychee"
group = "versions"
script = "lychee --version"
[[task]]
name = "cargo-audit"
group = "security"
script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
[[task]] [[task]]
name = "cargo-fmt" name = "cargo-fmt"
group = "lints" group = "lints"
@@ -71,7 +51,6 @@ group = "lints"
script = """ script = """
RUSTDOCFLAGS="-D warnings" cargo doc \ RUSTDOCFLAGS="-D warnings" cargo doc \
--workspace \ --workspace \
--all-features \
--no-deps \ --no-deps \
--document-private-items \ --document-private-items \
--color always --color always
@@ -80,12 +59,7 @@ RUSTDOCFLAGS="-D warnings" cargo doc \
[[task]] [[task]]
name = "cargo-clippy" name = "cargo-clippy"
group = "lints" group = "lints"
script = "cargo clippy --workspace --all-targets --all-features --color=always -- -D warnings" script = "cargo clippy --workspace --all-targets --color=always -- -D warnings"
[[task]]
name = "lychee"
group = "lints"
script = "lychee --offline docs"
[[task]] [[task]]
name = "cargo" name = "cargo"
@@ -94,8 +68,12 @@ script = """
cargo test \ cargo test \
--workspace \ --workspace \
--all-targets \ --all-targets \
--all-features \
--color=always \ --color=always \
-- \ -- \
--color=always --color=always
""" """
[[task]]
name = "cargo-audit"
group = "security"
script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
Generated
+16 -16
View File
@@ -60,8 +60,8 @@
}, },
"original": { "original": {
"owner": "ipetkov", "owner": "ipetkov",
"ref": "master",
"repo": "crane", "repo": "crane",
"rev": "2c653e4478476a52c6aa3ac0495e4dea7449ea0e",
"type": "github" "type": "github"
} }
}, },
@@ -73,11 +73,11 @@
"rust-analyzer-src": "rust-analyzer-src" "rust-analyzer-src": "rust-analyzer-src"
}, },
"locked": { "locked": {
"lastModified": 1711606966, "lastModified": 1707891749,
"narHash": "sha256-nTaO7ZDL4D02dVC5ktqnXNiNuODBUHyE4qEcFjAUCQY=", "narHash": "sha256-SeikNYElHgv8uVMbiA9/pU3Cce7ssIsiM8CnEiwd1Nc=",
"owner": "nix-community", "owner": "nix-community",
"repo": "fenix", "repo": "fenix",
"rev": "aa45c3e901ea42d6633af083c0c555efaf948b17", "rev": "3115aab064ef38cccd792c45429af8df43d6d277",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -138,11 +138,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1710146030, "lastModified": 1705309234,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -153,11 +153,11 @@
}, },
"nix-filter": { "nix-filter": {
"locked": { "locked": {
"lastModified": 1710156097, "lastModified": 1705332318,
"narHash": "sha256-1Wvk8UP7PXdf8bCCaEoMnOT1qe5/Duqgj+rL8sRQsSM=", "narHash": "sha256-kcw1yFeJe9N4PjQji9ZeX47jg0p9A0DuU4djKvg1a7I=",
"owner": "numtide", "owner": "numtide",
"repo": "nix-filter", "repo": "nix-filter",
"rev": "3342559a24e85fc164b295c3444e8a139924675b", "rev": "3449dc925982ad46246cfc36469baf66e1b64f17",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -200,11 +200,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1711523803, "lastModified": 1707689078,
"narHash": "sha256-UKcYiHWHQynzj6CN/vTcix4yd1eCu1uFdsuarupdCQQ=", "narHash": "sha256-UUGmRa84ZJHpGZ1WZEBEUOzaPOWG8LZ0yPg1pdDF/yM=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "2726f127c15a4cc9810843b96cad73c7eb39e443", "rev": "f9d39fb9aff0efee4a3d5f4a6d7c17701d38a1d8",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -228,11 +228,11 @@
"rust-analyzer-src": { "rust-analyzer-src": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1711562745, "lastModified": 1707849817,
"narHash": "sha256-s/YOyBM0vumhkqCFi8CnV5imFlC5JJrGia8CmEXyQkM=", "narHash": "sha256-If6T0MDErp3/z7DBlpG4bV46IPP+7BWSlgTI88cmbw0=",
"owner": "rust-lang", "owner": "rust-lang",
"repo": "rust-analyzer", "repo": "rust-analyzer",
"rev": "ad51a17c627b4ca57f83f0dc1f3bb5f3f17e6d0b", "rev": "a02a219773629686bd8ff123ca1aa995fa50d976",
"type": "github" "type": "github"
}, },
"original": { "original": {
+72 -170
View File
@@ -13,12 +13,7 @@
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
crane = { crane = {
# Pin latest crane that's not affected by the following bugs: url = "github:ipetkov/crane?ref=master";
#
# * <https://github.com/ipetkov/crane/issues/527#issuecomment-1978079140>
# * <https://github.com/toml-rs/toml/issues/691>
# * <https://github.com/toml-rs/toml/issues/267>
url = "github:ipetkov/crane?rev=2c653e4478476a52c6aa3ac0495e4dea7449ea0e";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
attic.url = "github:zhaofengli/attic?ref=main"; attic.url = "github:zhaofengli/attic?ref=main";
@@ -36,21 +31,16 @@
}: flake-utils.lib.eachDefaultSystem (system: }: flake-utils.lib.eachDefaultSystem (system:
let let
pkgsHost = nixpkgs.legacyPackages.${system}; pkgsHost = nixpkgs.legacyPackages.${system};
allocator = null;
rocksdb' = pkgs: rocksdb' = pkgs: pkgs.rocksdb.overrideAttrs (old:
let {
version = "9.0.0"; src = pkgs.fetchFromGitHub {
in owner = "facebook";
(pkgs.rocksdb.overrideAttrs (old: { repo = "rocksdb";
inherit version; rev = "v8.10.0";
src = pkgs.fetchFromGitHub { hash = "sha256-KGsYDBc1fz/90YYNGwlZ0LUKXYsP1zyhP29TnRQwgjQ=";
owner = "girlbossceo"; };
repo = "rocksdb"; });
rev = "449768a833b79c267c584b5ab1d50e73db6faf9d";
hash = "sha256-MjmGfAlZ5WC2+hFH6nEUprqBjO8xiTQh2HJIqQ5mIg8=";
};
}));
# Nix-accessible `Cargo.toml` # Nix-accessible `Cargo.toml`
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml); cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
@@ -70,11 +60,10 @@
# bindgen needs the build platform's libclang. Apparently due to # bindgen needs the build platform's libclang. Apparently due to
# "splicing weirdness", pkgs.rustPlatform.bindgenHook on its own doesn't # "splicing weirdness", pkgs.rustPlatform.bindgenHook on its own doesn't
# quite do the right thing here. # quite do the right thing here.
pkgs.pkgsBuildHost.rustPlatform.bindgenHook pkgs.buildPackages.rustPlatform.bindgenHook
]; ];
env = pkgs: { env = pkgs: {
CONDUIT_VERSION_EXTRA = self.shortRev or self.dirtyShortRev;
ROCKSDB_INCLUDE_DIR = "${rocksdb' pkgs}/include"; ROCKSDB_INCLUDE_DIR = "${rocksdb' pkgs}/include";
ROCKSDB_LIB_DIR = "${rocksdb' pkgs}/lib"; ROCKSDB_LIB_DIR = "${rocksdb' pkgs}/lib";
} }
@@ -83,38 +72,38 @@
} }
// { // {
CARGO_BUILD_RUSTFLAGS = let inherit (pkgs) lib stdenv; in CARGO_BUILD_RUSTFLAGS = let inherit (pkgs) lib stdenv; in
lib.concatStringsSep " " ([ ] lib.concatStringsSep " " ([]
++ lib.optionals ++ lib.optionals
# This disables PIE for static builds, which isn't great in terms # This disables PIE for static builds, which isn't great in terms
# of security. Unfortunately, my hand is forced because nixpkgs' # of security. Unfortunately, my hand is forced because nixpkgs'
# `libstdc++.a` is built without `-fPIE`, which precludes us from # `libstdc++.a` is built without `-fPIE`, which precludes us from
# leaving PIE enabled. # leaving PIE enabled.
stdenv.hostPlatform.isStatic stdenv.hostPlatform.isStatic
[ "-C" "relocation-model=static" ] ["-C" "relocation-model=static"]
++ lib.optionals ++ lib.optionals
(stdenv.buildPlatform.config != stdenv.hostPlatform.config) (stdenv.buildPlatform.config != stdenv.hostPlatform.config)
[ "-l" "c" ] ["-l" "c"]
++ lib.optionals ++ lib.optionals
# This check has to match the one [here][0]. We only need to set # This check has to match the one [here][0]. We only need to set
# these flags when using a different linker. Don't ask me why, # these flags when using a different linker. Don't ask me why,
# though, because I don't know. All I know is it breaks otherwise. # though, because I don't know. All I know is it breaks otherwise.
# #
# [0]: https://github.com/NixOS/nixpkgs/blob/5cdb38bb16c6d0a38779db14fcc766bc1b2394d6/pkgs/build-support/rust/lib/default.nix#L37-L40 # [0]: https://github.com/NixOS/nixpkgs/blob/612f97239e2cc474c13c9dafa0df378058c5ad8d/pkgs/build-support/rust/lib/default.nix#L36-L39
( (
# Nixpkgs doesn't check for x86_64 here but we do, because I # Nixpkgs doesn't check for x86_64 here but we do, because I
# observed a failure building statically for x86_64 without # observed a failure building statically for x86_64 without
# including it here. Linkers are weird. # including it here. Linkers are weird.
(stdenv.hostPlatform.isAarch64 || stdenv.hostPlatform.isx86_64) (stdenv.hostPlatform.isAarch64 || stdenv.hostPlatform.isx86_64)
&& stdenv.hostPlatform.isStatic && stdenv.hostPlatform.isStatic
&& !stdenv.isDarwin && !stdenv.isDarwin
&& !stdenv.cc.bintools.isLLVM && !stdenv.cc.bintools.isLLVM
) )
[ [
"-l" "-l"
"stdc++" "stdc++"
"-L" "-L"
"${stdenv.cc.cc.lib}/${stdenv.hostPlatform.config}/lib" "${stdenv.cc.cc.lib}/${stdenv.hostPlatform.config}/lib"
] ]
); );
} }
@@ -123,7 +112,7 @@
# even covers the case of build scripts that need native code compiled and # even covers the case of build scripts that need native code compiled and
# run on the build platform (I think). # run on the build platform (I think).
# #
# [0]: https://github.com/NixOS/nixpkgs/blob/5cdb38bb16c6d0a38779db14fcc766bc1b2394d6/pkgs/build-support/rust/lib/default.nix#L57-L80 # [0]: https://github.com/NixOS/nixpkgs/blob/612f97239e2cc474c13c9dafa0df378058c5ad8d/pkgs/build-support/rust/lib/default.nix#L64-L78
// ( // (
let let
inherit (pkgs.rust.lib) envVars; inherit (pkgs.rust.lib) envVars;
@@ -142,32 +131,31 @@
envVars.linkerForTarget; envVars.linkerForTarget;
} }
) )
// ( // (
let let
inherit (pkgs.stdenv.hostPlatform.rust) cargoEnvVarTarget rustcTarget; inherit (pkgs.stdenv.hostPlatform.rust) cargoEnvVarTarget rustcTarget;
in in
{ {
"CC_${cargoEnvVarTarget}" = envVars.ccForHost; "CC_${cargoEnvVarTarget}" = envVars.ccForHost;
"CXX_${cargoEnvVarTarget}" = envVars.cxxForHost; "CXX_${cargoEnvVarTarget}" = envVars.cxxForHost;
"CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForHost; "CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForHost;
CARGO_BUILD_TARGET = rustcTarget; CARGO_BUILD_TARGET = rustcTarget;
} }
) )
// ( // (
let let
inherit (pkgs.stdenv.buildPlatform.rust) cargoEnvVarTarget; inherit (pkgs.stdenv.buildPlatform.rust) cargoEnvVarTarget;
in in
{ {
"CC_${cargoEnvVarTarget}" = envVars.ccForBuild; "CC_${cargoEnvVarTarget}" = envVars.ccForBuild;
"CXX_${cargoEnvVarTarget}" = envVars.cxxForBuild; "CXX_${cargoEnvVarTarget}" = envVars.cxxForBuild;
"CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForBuild; "CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForBuild;
HOST_CC = "${pkgs.pkgsBuildHost.stdenv.cc}/bin/cc"; HOST_CC = "${pkgs.buildPackages.stdenv.cc}/bin/cc";
HOST_CXX = "${pkgs.pkgsBuildHost.stdenv.cc}/bin/c++"; HOST_CXX = "${pkgs.buildPackages.stdenv.cc}/bin/c++";
} }
) ));
);
mkPackage = pkgs: allocator: builder pkgs { package = pkgs: builder pkgs {
src = nix-filter { src = nix-filter {
root = ./.; root = ./.;
include = [ include = [
@@ -177,13 +165,6 @@
]; ];
}; };
buildFeatures = [ ]
++ (if allocator == "jemalloc" then [ "jemalloc" ] else [ ])
++ (if allocator == "hmalloc" then [ "hardened_malloc" ] else [ ])
;
rocksdb' = (if allocator == "jemalloc" then (pkgs.rocksdb.override { enableJemalloc = true; }) else (rocksdb' pkgs));
# This is redundant with CI # This is redundant with CI
doCheck = false; doCheck = false;
@@ -193,13 +174,11 @@
meta.mainProgram = cargoToml.package.name; meta.mainProgram = cargoToml.package.name;
}; };
mkOciImage = pkgs: package: allocator: mkOciImage = pkgs: package:
pkgs.dockerTools.buildLayeredImage { pkgs.dockerTools.buildImage {
name = package.pname; name = package.pname;
tag = "main"; tag = "main";
# Debian makes builds reproducible through using the HEAD commit's date copyToRoot = [
created = "@${toString self.lastModified}";
contents = [
pkgs.dockerTools.caCertificates pkgs.dockerTools.caCertificates
]; ];
config = { config = {
@@ -217,41 +196,8 @@
in in
{ {
packages = { packages = {
default = mkPackage pkgsHost null; default = package pkgsHost;
jemalloc = mkPackage pkgsHost "jemalloc"; oci-image = mkOciImage pkgsHost self.packages.${system}.default;
hmalloc = mkPackage pkgsHost "hmalloc";
oci-image = mkOciImage pkgsHost self.packages.${system}.default null;
oci-image-jemalloc = mkOciImage pkgsHost self.packages.${system}.default "jemalloc";
oci-image-hmalloc = mkOciImage pkgsHost self.packages.${system}.default "hmalloc";
book =
let
package = self.packages.${system}.default;
in
pkgsHost.stdenv.mkDerivation {
pname = "${package.pname}-book";
version = package.version;
src = nix-filter {
root = ./.;
include = [
"book.toml"
"conduwuit-example.toml"
"README.md"
"debian/README.md"
"docs"
];
};
nativeBuildInputs = (with pkgsHost; [
mdbook
]);
buildPhase = ''
mdbook build
mv public $out
'';
};
} }
// //
builtins.listToAttrs builtins.listToAttrs
@@ -272,19 +218,7 @@
# An output for a statically-linked binary # An output for a statically-linked binary
{ {
name = binaryName; name = binaryName;
value = mkPackage pkgsCrossStatic null; value = package pkgsCrossStatic;
}
# An output for a statically-linked binary with jemalloc
{
name = "${binaryName}-jemalloc";
value = mkPackage pkgsCrossStatic "jemalloc";
}
# An output for a statically-linked binary with hardened_malloc
{
name = "${binaryName}-hmalloc";
value = mkPackage pkgsCrossStatic "hmalloc";
} }
# An output for an OCI image based on that binary # An output for an OCI image based on that binary
@@ -292,36 +226,13 @@
name = "oci-image-${crossSystem}"; name = "oci-image-${crossSystem}";
value = mkOciImage value = mkOciImage
pkgsCrossStatic pkgsCrossStatic
self.packages.${system}.${binaryName} self.packages.${system}.${binaryName};
null;
}
# An output for an OCI image based on that binary with jemalloc
{
name = "oci-image-${crossSystem}-jemalloc";
value = mkOciImage
pkgsCrossStatic
self.packages.${system}.${binaryName}
"jemalloc";
}
# An output for an OCI image based on that binary with hardened_malloc
{
name = "oci-image-${crossSystem}-hmalloc";
value = mkOciImage
pkgsCrossStatic
self.packages.${system}.${binaryName}
"hmalloc";
} }
] ]
) )
[ [
"x86_64-unknown-linux-musl" "x86_64-unknown-linux-musl"
"x86_64-unknown-linux-musl-jemalloc"
"x86_64-unknown-linux-musl-hmalloc"
"aarch64-unknown-linux-musl" "aarch64-unknown-linux-musl"
"aarch64-unknown-linux-musl-jemalloc"
"aarch64-unknown-linux-musl-hmalloc"
] ]
) )
); );
@@ -346,21 +257,12 @@
] ++ (with pkgsHost; [ ] ++ (with pkgsHost; [
engage engage
# Needed for producing Debian packages
cargo-deb
# Needed for Complement # Needed for Complement
go go
olm olm
# Needed for our script for Complement # Needed for our script for Complement
jq jq
# Needed for finding broken markdown links
lychee
# Useful for editing the book locally
mdbook
]); ]);
}; };
}); });
+198
View File
@@ -0,0 +1,198 @@
# Conduit for Nix/NixOS
This guide assumes you have a recent version of Nix (^2.4) installed.
Since Conduit ships as a Nix flake, you'll first need to [enable
flakes][enable_flakes].
You can now use the usual Nix commands to interact with Conduit's flake. For
example, `nix run gitlab:famedly/conduit` will run Conduit (though you'll need
to provide configuration and such manually as usual).
If your NixOS configuration is defined as a flake, you can depend on this flake
to provide a more up-to-date version than provided by `nixpkgs`. In your flake,
add the following to your `inputs`:
```nix
conduit = {
url = "gitlab:famedly/conduit";
# Assuming you have an input for nixpkgs called `nixpkgs`. If you experience
# build failures while using this, try commenting/deleting this line. This
# will probably also require you to always build from source.
inputs.nixpkgs.follows = "nixpkgs";
};
```
Next, make sure you're passing your flake inputs to the `specialArgs` argument
of `nixpkgs.lib.nixosSystem` [as explained here][specialargs]. This guide will
assume you've named the group `flake-inputs`.
Now you can configure Conduit and a reverse proxy for it. Add the following to
a new Nix file and include it in your configuration:
```nix
{ config
, pkgs
, flake-inputs
, ...
}:
let
# You'll need to edit these values
# The hostname that will appear in your user and room IDs
server_name = "example.com";
# The hostname that Conduit actually runs on
#
# This can be the same as `server_name` if you want. This is only necessary
# when Conduit is running on a different machine than the one hosting your
# root domain. This configuration also assumes this is all running on a single
# machine, some tweaks will need to be made if this is not the case.
matrix_hostname = "matrix.${server_name}";
# An admin email for TLS certificate notifications
admin_email = "admin@${server_name}";
# These ones you can leave alone
# Build a dervation that stores the content of `${server_name}/.well-known/matrix/server`
well_known_server = pkgs.writeText "well-known-matrix-server" ''
{
"m.server": "${matrix_hostname}"
}
'';
# Build a dervation that stores the content of `${server_name}/.well-known/matrix/client`
well_known_client = pkgs.writeText "well-known-matrix-client" ''
{
"m.homeserver": {
"base_url": "https://${matrix_hostname}"
}
}
'';
in
{
# Configure Conduit itself
services.matrix-conduit = {
enable = true;
# This causes NixOS to use the flake defined in this repository instead of
# the build of Conduit built into nixpkgs.
package = flake-inputs.conduit.packages.${pkgs.system}.default;
settings.global = {
inherit server_name;
};
};
# Configure automated TLS acquisition/renewal
security.acme = {
acceptTerms = true;
defaults = {
email = admin_email;
};
};
# ACME data must be readable by the NGINX user
users.users.nginx.extraGroups = [
"acme"
];
# Configure NGINX as a reverse proxy
services.nginx = {
enable = true;
recommendedProxySettings = true;
virtualHosts = {
"${matrix_hostname}" = {
forceSSL = true;
enableACME = true;
listen = [
{
addr = "0.0.0.0";
port = 443;
ssl = true;
}
{
addr = "[::]";
port = 443;
ssl = true;
} {
addr = "0.0.0.0";
port = 8448;
ssl = true;
}
{
addr = "[::]";
port = 8448;
ssl = true;
}
];
locations."/_matrix/" = {
proxyPass = "http://backend_conduit$request_uri";
proxyWebsockets = true;
extraConfig = ''
proxy_set_header Host $host;
proxy_buffering off;
'';
};
extraConfig = ''
merge_slashes off;
'';
};
"${server_name}" = {
forceSSL = true;
enableACME = true;
locations."=/.well-known/matrix/server" = {
# Use the contents of the derivation built previously
alias = "${well_known_server}";
extraConfig = ''
# Set the header since by default NGINX thinks it's just bytes
default_type application/json;
'';
};
locations."=/.well-known/matrix/client" = {
# Use the contents of the derivation built previously
alias = "${well_known_client}";
extraConfig = ''
# Set the header since by default NGINX thinks it's just bytes
default_type application/json;
# https://matrix.org/docs/spec/client_server/r0.4.0#web-browser-clients
add_header Access-Control-Allow-Origin "*";
'';
};
};
};
upstreams = {
"backend_conduit" = {
servers = {
"[::1]:${toString config.services.matrix-conduit.settings.global.port}" = { };
};
};
};
};
# Open firewall ports for HTTP, HTTPS, and Matrix federation
networking.firewall.allowedTCPPorts = [ 80 443 8448 ];
networking.firewall.allowedUDPPorts = [ 80 443 8448 ];
}
```
Now you can rebuild your system configuration and you should be good to go!
[enable_flakes]: https://nixos.wiki/wiki/Flakes#Enable_flakes
[specialargs]: https://nixos.wiki/wiki/Flakes#Using_nix_flakes_with_NixOS
-1
View File
@@ -3,7 +3,6 @@
# Other files that need upkeep when this changes: # Other files that need upkeep when this changes:
# #
# * `.gitlab-ci.yml` # * `.gitlab-ci.yml`
# * `.github/workflows/ci.yml`
# * `Cargo.toml` # * `Cargo.toml`
# * `flake.nix` # * `flake.nix`
# #
+2 -28
View File
@@ -1,28 +1,2 @@
edition = "2021" unstable_features = true
imports_granularity="Crate"
condense_wildcard_suffixes = true
format_code_in_doc_comments = true
format_macro_bodies = true
format_macro_matchers = true
format_strings = true
hex_literal_case = "Upper"
max_width = 120
tab_spaces = 4
array_width = 80
comment_width = 80
wrap_comments = true
fn_params_layout = "Compressed"
fn_call_width = 80
fn_single_line = true
hard_tabs = true
match_block_trailing_comma = true
imports_granularity = "Crate"
normalize_comments = false
reorder_impl_items = true
reorder_imports = true
group_imports = "StdExternalCrate"
newline_style = "Unix"
use_field_init_shorthand = true
use_small_heuristics = "Off"
use_try_shorthand = true
chain_width = 60
+114
View File
@@ -0,0 +1,114 @@
use crate::{services, utils, Error, Result};
use bytes::BytesMut;
use ruma::api::{
appservice::Registration, IncomingResponse, MatrixVersion, OutgoingRequest, SendAccessToken,
};
use std::{fmt::Debug, mem, time::Duration};
use tracing::warn;
/// Sends a request to an appservice
///
/// Only returns None if there is no url specified in the appservice registration file
pub(crate) async fn send_request<T: OutgoingRequest>(
registration: Registration,
request: T,
) -> Option<Result<T::IncomingResponse>>
where
T: Debug,
{
if let Some(destination) = registration.url {
let hs_token = registration.hs_token.as_str();
let mut http_request = request
.try_into_http_request::<BytesMut>(
&destination,
SendAccessToken::IfRequired(hs_token),
&[MatrixVersion::V1_0],
)
.map_err(|e| {
warn!("Failed to find destination {}: {}", destination, e);
Error::BadServerResponse("Invalid destination")
})
.unwrap()
.map(|body| body.freeze());
let mut parts = http_request.uri().clone().into_parts();
let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned();
let symbol = if old_path_and_query.contains('?') {
"&"
} else {
"?"
};
parts.path_and_query = Some(
(old_path_and_query + symbol + "access_token=" + hs_token)
.parse()
.unwrap(),
);
*http_request.uri_mut() = parts.try_into().expect("our manipulation is always valid");
let mut reqwest_request = reqwest::Request::try_from(http_request)
.expect("all http requests are valid reqwest requests");
*reqwest_request.timeout_mut() = Some(Duration::from_secs(120));
let url = reqwest_request.url().clone();
let mut response = match services()
.globals
.default_client()
.execute(reqwest_request)
.await
{
Ok(r) => r,
Err(e) => {
warn!(
"Could not send request to appservice {} at {}: {}",
registration.id, destination, e
);
return Some(Err(e.into()));
}
};
// reqwest::Response -> http::Response conversion
let status = response.status();
let mut http_response_builder = http::Response::builder()
.status(status)
.version(response.version());
mem::swap(
response.headers_mut(),
http_response_builder
.headers_mut()
.expect("http::response::Builder is usable"),
);
let body = response.bytes().await.unwrap_or_else(|e| {
warn!("server error: {}", e);
Vec::new().into()
}); // TODO: handle timeout
if !status.is_success() {
warn!(
"Appservice returned bad response {} {}\n{}\n{:?}",
destination,
status,
url,
utils::string_from_bytes(&body)
);
}
let response = T::IncomingResponse::try_from_http_response(
http_response_builder
.body(body)
.expect("reqwest body is valid http body"),
);
Some(response.map_err(|_| {
warn!(
"Appservice returned invalid response bytes {}\n{}",
destination, url
);
Error::BadServerResponse("Server returned bad response.")
}))
} else {
None
}
}
+400 -462
View File
@@ -1,25 +1,21 @@
use register::RegistrationKind;
use ruma::{
api::client::{
account::{
change_password, deactivate, get_3pids, get_username_availability,
register::{self, LoginType},
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, whoami,
ThirdPartyIdRemovalStatus,
},
error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo},
},
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
push, UserId,
};
use tracing::{error, info, warn};
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH}; use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use crate::{ use crate::{api::client_server, services, utils, Error, Result, Ruma};
api::client_server::{self, join_room_by_id_helper}, use ruma::{
service, services, utils, Error, Result, Ruma, api::client::{
account::{
change_password, deactivate, get_3pids, get_username_availability, register,
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn,
whoami, ThirdPartyIdRemovalStatus,
},
error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo},
},
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
push, UserId,
}; };
use tracing::{info, warn};
use register::RegistrationKind;
const RANDOM_USER_ID_LENGTH: usize = 10; const RANDOM_USER_ID_LENGTH: usize = 10;
@@ -32,361 +28,303 @@ const RANDOM_USER_ID_LENGTH: usize = 10;
/// - The server name of the user id matches this server /// - The server name of the user id matches this server
/// - No user or appservice on this server already claimed this username /// - No user or appservice on this server already claimed this username
/// ///
/// Note: This will not reserve the username, so the username might become /// Note: This will not reserve the username, so the username might become invalid when trying to register
/// invalid when trying to register
pub async fn get_register_available_route( pub async fn get_register_available_route(
body: Ruma<get_username_availability::v3::Request>, body: Ruma<get_username_availability::v3::Request>,
) -> Result<get_username_availability::v3::Response> { ) -> Result<get_username_availability::v3::Response> {
// Validate user id // Validate user id
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services().globals.server_name()) let user_id = UserId::parse_with_server_name(
.ok() body.username.to_lowercase(),
.filter(|user_id| !user_id.is_historical() && user_id.server_name() == services().globals.server_name()) services().globals.server_name(),
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; )
.ok()
.filter(|user_id| {
!user_id.is_historical() && user_id.server_name() == services().globals.server_name()
})
.ok_or(Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid.",
))?;
// Check if username is creative enough // Check if username is creative enough
if services().users.exists(&user_id)? { if services().users.exists(&user_id)? {
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken.")); return Err(Error::BadRequest(
} ErrorKind::UserInUse,
"Desired user ID is already taken.",
));
}
if services() if services()
.globals .globals
.forbidden_usernames() .forbidden_usernames()
.is_match(user_id.localpart()) .is_match(user_id.localpart())
{ {
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden.")); return Err(Error::BadRequest(
} ErrorKind::Unknown,
"Username is forbidden.",
));
}
// TODO add check for appservice namespaces // TODO add check for appservice namespaces
// If no if check is true we have an username that's available to be used. // If no if check is true we have an username that's available to be used.
Ok(get_username_availability::v3::Response { Ok(get_username_availability::v3::Response { available: true })
available: true,
})
} }
/// # `POST /_matrix/client/v3/register` /// # `POST /_matrix/client/v3/register`
/// ///
/// Register an account on this homeserver. /// Register an account on this homeserver.
/// ///
/// You can use [`GET /// You can use [`GET /_matrix/client/v3/register/available`](fn.get_register_available_route.html)
/// /_matrix/client/v3/register/available`](fn.get_register_available_route. /// to check if the user id is valid and available.
/// html) to check if the user id is valid and available.
/// ///
/// - Only works if registration is enabled /// - Only works if registration is enabled
/// - If type is guest: ignores all parameters except /// - If type is guest: ignores all parameters except initial_device_display_name
/// initial_device_display_name
/// - If sender is not appservice: Requires UIAA (but we only use a dummy stage) /// - If sender is not appservice: Requires UIAA (but we only use a dummy stage)
/// - If type is not guest and no username is given: Always fails after UIAA /// - If type is not guest and no username is given: Always fails after UIAA check
/// check
/// - Creates a new account and populates it with default account data /// - Creates a new account and populates it with default account data
/// - If `inhibit_login` is false: Creates a device and returns device id and /// - If `inhibit_login` is false: Creates a device and returns device id and access_token
/// access_token
#[allow(clippy::doc_markdown)]
pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> { pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> {
if !services().globals.allow_registration() && body.appservice_info.is_none() { if !services().globals.allow_registration() && !body.from_appservice {
info!( info!("Registration disabled and request not from known appservice, rejecting registration attempt for username {:?}", body.username);
"Registration disabled and request not from known appservice, rejecting registration attempt for username \ return Err(Error::BadRequest(
{:?}", ErrorKind::Forbidden,
body.username "Registration has been disabled.",
); ));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Registration has been disabled.")); }
}
let is_guest = body.kind == RegistrationKind::Guest; let is_guest = body.kind == RegistrationKind::Guest;
if is_guest if is_guest
&& (!services().globals.allow_guest_registration() && (!services().globals.allow_guest_registration()
|| (services().globals.allow_registration() && services().globals.config.registration_token.is_some())) || (services().globals.allow_registration()
{ && services().globals.config.registration_token.is_some()))
info!( {
"Guest registration disabled / registration enabled with token configured, rejecting guest registration, \ info!("Guest registration disabled / registration enabled with token configured, rejecting guest registration, initial device name: {:?}", body.initial_device_display_name);
initial device name: {:?}", return Err(Error::BadRequest(
body.initial_device_display_name ErrorKind::GuestAccessForbidden,
); "Guest registration is disabled.",
return Err(Error::BadRequest( ));
ErrorKind::GuestAccessForbidden, }
"Guest registration is disabled.",
));
}
// forbid guests from registering if there is not a real admin user yet. give // forbid guests from registering if there is not a real admin user yet. give generic user error.
// generic user error. if is_guest && services().users.count()? < 2 {
if is_guest && services().users.count()? < 2 { warn!("Guest account attempted to register before a real admin user has been registered, rejecting registration. Guest's initial device name: {:?}", body.initial_device_display_name);
warn!( return Err(Error::BadRequest(
"Guest account attempted to register before a real admin user has been registered, rejecting \ ErrorKind::Forbidden,
registration. Guest's initial device name: {:?}", "Registration temporarily disabled.",
body.initial_device_display_name ));
); }
return Err(Error::BadRequest(ErrorKind::forbidden(), "Registration temporarily disabled."));
}
let user_id = match (&body.username, is_guest) { let user_id = match (&body.username, is_guest) {
(Some(username), false) => { (Some(username), false) => {
let proposed_user_id = let proposed_user_id = UserId::parse_with_server_name(
UserId::parse_with_server_name(username.to_lowercase(), services().globals.server_name()) username.to_lowercase(),
.ok() services().globals.server_name(),
.filter(|user_id| { )
!user_id.is_historical() && user_id.server_name() == services().globals.server_name() .ok()
}) .filter(|user_id| {
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; !user_id.is_historical()
&& user_id.server_name() == services().globals.server_name()
})
.ok_or(Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid.",
))?;
if services().users.exists(&proposed_user_id)? { if services().users.exists(&proposed_user_id)? {
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken.")); return Err(Error::BadRequest(
} ErrorKind::UserInUse,
"Desired user ID is already taken.",
));
}
if services() if services()
.globals .globals
.forbidden_usernames() .forbidden_usernames()
.is_match(proposed_user_id.localpart()) .is_match(proposed_user_id.localpart())
{ {
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden.")); return Err(Error::BadRequest(
} ErrorKind::Unknown,
"Username is forbidden.",
));
}
proposed_user_id proposed_user_id
}, }
_ => loop { _ => loop {
let proposed_user_id = UserId::parse_with_server_name( let proposed_user_id = UserId::parse_with_server_name(
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(), utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
services().globals.server_name(), services().globals.server_name(),
) )
.unwrap(); .unwrap();
if !services().users.exists(&proposed_user_id)? { if !services().users.exists(&proposed_user_id)? {
break proposed_user_id; break proposed_user_id;
} }
}, },
}; };
if body.body.login_type == Some(LoginType::ApplicationService) { // UIAA
if let Some(ref info) = body.appservice_info { let mut uiaainfo;
if !info.is_user_match(&user_id) { let skip_auth;
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace.")); if services().globals.config.registration_token.is_some() {
} // Registration token required
} else { uiaainfo = UiaaInfo {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token.")); flows: vec![AuthFlow {
} stages: vec![AuthType::RegistrationToken],
} else if services().appservice.is_exclusive_user_id(&user_id).await { }],
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice.")); completed: Vec::new(),
} params: Default::default(),
session: None,
auth_error: None,
};
skip_auth = body.from_appservice;
} else {
// No registration token necessary, but clients must still go through the flow
uiaainfo = UiaaInfo {
flows: vec![AuthFlow {
stages: vec![AuthType::Dummy],
}],
completed: Vec::new(),
params: Default::default(),
session: None,
auth_error: None,
};
skip_auth = body.from_appservice || is_guest;
}
// UIAA if !skip_auth {
let mut uiaainfo; if let Some(auth) = &body.auth {
let skip_auth; let (worked, uiaainfo) = services().uiaa.try_auth(
if services().globals.config.registration_token.is_some() { &UserId::parse_with_server_name("", services().globals.server_name())
// Registration token required .expect("we know this is valid"),
uiaainfo = UiaaInfo { "".into(),
flows: vec![AuthFlow { auth,
stages: vec![AuthType::RegistrationToken], &uiaainfo,
}], )?;
completed: Vec::new(), if !worked {
params: Box::default(), return Err(Error::Uiaa(uiaainfo));
session: None, }
auth_error: None, // Success!
}; } else if let Some(json) = body.json_body {
skip_auth = body.appservice_info.is_some(); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
} else { services().uiaa.create(
// No registration token necessary, but clients must still go through the flow &UserId::parse_with_server_name("", services().globals.server_name())
uiaainfo = UiaaInfo { .expect("we know this is valid"),
flows: vec![AuthFlow { "".into(),
stages: vec![AuthType::Dummy], &uiaainfo,
}], &json,
completed: Vec::new(), )?;
params: Box::default(), return Err(Error::Uiaa(uiaainfo));
session: None, } else {
auth_error: None, return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}; }
skip_auth = body.appservice_info.is_some() || is_guest; }
}
if !skip_auth { let password = if is_guest {
if let Some(auth) = &body.auth { None
let (worked, uiaainfo) = services().uiaa.try_auth( } else {
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"), body.password.as_deref()
"".into(), };
auth,
&uiaainfo,
)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"),
"".into(),
&uiaainfo,
&json,
)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
}
let password = if is_guest { // Create user
None services().users.create(&user_id, password)?;
} else {
body.password.as_deref()
};
// Create user // Default to pretty displayname
services().users.create(&user_id, password)?; let mut displayname = user_id.localpart().to_owned();
// Default to pretty displayname // If enabled append lightning bolt to display name (default true)
let mut displayname = user_id.localpart().to_owned(); if services().globals.enable_lightning_bolt() {
displayname.push_str(" ⚡️");
}
// If `new_user_displayname_suffix` is set, registration will push whatever services()
// content is set to the user's display name with a space before it .users
if !services().globals.new_user_displayname_suffix().is_empty() { .set_displayname(&user_id, Some(displayname.clone()))
displayname.push_str(&(" ".to_owned() + services().globals.new_user_displayname_suffix())); .await?;
}
services() // Initial account data
.users services().account_data.update(
.set_displayname(&user_id, Some(displayname.clone())) None,
.await?; &user_id,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent {
global: push::Ruleset::server_default(&user_id),
},
})
.expect("to json always works"),
)?;
// Initial account data // Inhibit login does not work for guests
services().account_data.update( if !is_guest && body.inhibit_login {
None, return Ok(register::v3::Response {
&user_id, access_token: None,
GlobalAccountDataEventType::PushRules.to_string().into(), user_id,
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent { device_id: None,
content: ruma::events::push_rules::PushRulesEventContent { refresh_token: None,
global: push::Ruleset::server_default(&user_id), expires_in: None,
}, });
}) }
.expect("to json always works"),
)?;
// Inhibit login does not work for guests // Generate new device id if the user didn't specify one
if !is_guest && body.inhibit_login { let device_id = if is_guest {
return Ok(register::v3::Response { None
access_token: None, } else {
user_id, body.device_id.clone()
device_id: None, }
refresh_token: None, .unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
expires_in: None,
});
}
// Generate new device id if the user didn't specify one // Generate new token for the device
let device_id = if is_guest { let token = utils::random_string(TOKEN_LENGTH);
None
} else {
body.device_id.clone()
}
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
// Generate new token for the device // Create device for this account
let token = utils::random_string(TOKEN_LENGTH); services().users.create_device(
&user_id,
&device_id,
&token,
body.initial_device_display_name.clone(),
)?;
// Create device for this account info!("New user \"{}\" registered on this server.", user_id);
services()
.users
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
info!("New user \"{}\" registered on this server.", user_id); // log in conduit admin channel if a non-guest user registered
if !body.from_appservice && !is_guest {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server."
)));
}
// log in conduit admin channel if a non-guest user registered // log in conduit admin channel if a guest registered
if body.appservice_info.is_none() && !is_guest { if !body.from_appservice && is_guest {
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server." "Guest user \"{user_id}\" with device display name `{:?}` registered on this server.",
))); body.initial_device_display_name
} )));
}
// log in conduit admin channel if a guest registered // If this is the first real user, grant them admin privileges except for guest users
if body.appservice_info.is_none() && is_guest && services().globals.log_guest_registrations() { // Note: the server user, @conduit:servername, is generated first
if let Some(device_display_name) = &body.initial_device_display_name { if services().users.count()? == 2 && !is_guest {
if body services()
.initial_device_display_name .admin
.as_ref() .make_user_admin(&user_id, displayname)
.is_some_and(|device_display_name| !device_display_name.is_empty()) .await?;
{
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
server."
)));
} else {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
)));
}
} else {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
)));
}
}
// If this is the first real user, grant them admin privileges except for guest warn!("Granting {} admin privileges as the first user", user_id);
// users Note: the server user, @conduit:servername, is generated first }
if !is_guest {
if let Some(admin_room) = service::admin::Service::get_admin_room()? {
if services()
.rooms
.state_cache
.room_joined_count(&admin_room)?
== Some(1)
{
services()
.admin
.make_user_admin(&user_id, displayname)
.await?;
warn!("Granting {} admin privileges as the first user", user_id); Ok(register::v3::Response {
} access_token: Some(token),
} user_id,
} device_id: Some(device_id),
refresh_token: None,
if body.appservice_info.is_none() expires_in: None,
&& !services().globals.config.auto_join_rooms.is_empty() })
&& (services().globals.allow_guests_auto_join_rooms() || !is_guest)
{
for room in &services().globals.config.auto_join_rooms {
if !services()
.rooms
.state_cache
.server_in_room(services().globals.server_name(), room)?
{
warn!("Skipping room {room} to automatically join as we have never joined before.");
continue;
}
if let Some(room_id_server_name) = room.server_name() {
if let Err(e) = join_room_by_id_helper(
Some(&user_id),
room,
Some("Automatically joining this room upon registration".to_owned()),
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
None,
)
.await
{
// don't return this error so we don't fail registrations
error!("Failed to automatically join room {room} for user {user_id}: {e}");
} else {
info!("Automatically joined room {room} for user {user_id}");
};
}
}
}
Ok(register::v3::Response {
access_token: Some(token),
user_id,
device_id: Some(device_id),
refresh_token: None,
expires_in: None,
})
} }
/// # `POST /_matrix/client/r0/account/password` /// # `POST /_matrix/client/r0/account/password`
@@ -395,89 +333,89 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
/// ///
/// - Requires UIAA to verify user password /// - Requires UIAA to verify user password
/// - Changes the password of the sender user /// - Changes the password of the sender user
/// - The password hash is calculated using argon2 with 32 character salt, the /// - The password hash is calculated using argon2 with 32 character salt, the plain password is
/// plain password is
/// not saved /// not saved
/// ///
/// If logout_devices is true it does the following for each device except the /// If logout_devices is true it does the following for each device except the sender device:
/// sender device:
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn change_password_route(body: Ruma<change_password::v3::Request>) -> Result<change_password::v3::Response> { pub async fn change_password_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<change_password::v3::Request>,
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); ) -> Result<change_password::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
let mut uiaainfo = UiaaInfo { let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow { flows: vec![AuthFlow {
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services() let (worked, uiaainfo) =
.uiaa services()
.try_auth(sender_user, sender_device, auth, &uiaainfo)?; .uiaa
if !worked { .try_auth(sender_user, sender_device, auth, &uiaainfo)?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); } else if let Some(json) = body.json_body {
services() uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.uiaa services()
.create(sender_user, sender_device, &uiaainfo, &json)?; .uiaa
return Err(Error::Uiaa(uiaainfo)); .create(sender_user, sender_device, &uiaainfo, &json)?;
} else { return Err(Error::Uiaa(uiaainfo));
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); } else {
} return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
services() services()
.users .users
.set_password(sender_user, Some(&body.new_password))?; .set_password(sender_user, Some(&body.new_password))?;
if body.logout_devices { if body.logout_devices {
// Logout all devices except the current one // Logout all devices except the current one
for id in services() for id in services()
.users .users
.all_device_ids(sender_user) .all_device_ids(sender_user)
.filter_map(Result::ok) .filter_map(|id| id.ok())
.filter(|id| id != sender_device) .filter(|id| id != sender_device)
{ {
services().users.remove_device(sender_user, &id)?; services().users.remove_device(sender_user, &id)?;
} }
} }
info!("User {} changed their password.", sender_user); info!("User {} changed their password.", sender_user);
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} changed their password." "User {sender_user} changed their password."
))); )));
Ok(change_password::v3::Response {}) Ok(change_password::v3::Response {})
} }
/// # `GET _matrix/client/r0/account/whoami` /// # `GET _matrix/client/r0/account/whoami`
/// ///
/// Get `user_id` of the sender user. /// Get user_id of the sender user.
/// ///
/// Note: Also works for Application Services /// Note: Also works for Application Services
pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> { pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device_id = body.sender_device.clone(); let device_id = body.sender_device.as_ref().cloned();
Ok(whoami::v3::Response { Ok(whoami::v3::Response {
user_id: sender_user.clone(), user_id: sender_user.clone(),
device_id, device_id,
is_guest: services().users.is_deactivated(sender_user)? && body.appservice_info.is_none(), is_guest: services().users.is_deactivated(sender_user)? && !body.from_appservice,
}) })
} }
/// # `POST /_matrix/client/r0/account/deactivate` /// # `POST /_matrix/client/r0/account/deactivate`
@@ -486,59 +424,61 @@ pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3:
/// ///
/// - Leaves all rooms and rejects all invitations /// - Leaves all rooms and rejects all invitations
/// - Invalidates all access tokens /// - Invalidates all access tokens
/// - Deletes all device metadata (device id, device display name, last seen ip, /// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets all to-device events /// - Forgets all to-device events
/// - Triggers device list updates /// - Triggers device list updates
/// - Removes ability to log in again /// - Removes ability to log in again
pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<deactivate::v3::Response> { pub async fn deactivate_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<deactivate::v3::Request>,
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); ) -> Result<deactivate::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
let mut uiaainfo = UiaaInfo { let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow { flows: vec![AuthFlow {
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services() let (worked, uiaainfo) =
.uiaa services()
.try_auth(sender_user, sender_device, auth, &uiaainfo)?; .uiaa
if !worked { .try_auth(sender_user, sender_device, auth, &uiaainfo)?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); } else if let Some(json) = body.json_body {
services() uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.uiaa services()
.create(sender_user, sender_device, &uiaainfo, &json)?; .uiaa
return Err(Error::Uiaa(uiaainfo)); .create(sender_user, sender_device, &uiaainfo, &json)?;
} else { return Err(Error::Uiaa(uiaainfo));
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); } else {
} return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
// Make the user leave all rooms before deactivation // Make the user leave all rooms before deactivation
client_server::leave_all_rooms(sender_user).await?; client_server::leave_all_rooms(sender_user).await?;
// Remove devices and mark account as deactivated // Remove devices and mark account as deactivated
services().users.deactivate_account(sender_user)?; services().users.deactivate_account(sender_user)?;
info!("User {} deactivated their account.", sender_user); info!("User {} deactivated their account.", sender_user);
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} deactivated their account." "User {sender_user} deactivated their account."
))); )));
Ok(deactivate::v3::Response { Ok(deactivate::v3::Response {
id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport, id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport,
}) })
} }
/// # `GET _matrix/client/v3/account/3pid` /// # `GET _matrix/client/v3/account/3pid`
@@ -546,40 +486,38 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
/// Get a list of third party identifiers associated with this account. /// Get a list of third party identifiers associated with this account.
/// ///
/// - Currently always returns empty list /// - Currently always returns empty list
pub async fn third_party_route(body: Ruma<get_3pids::v3::Request>) -> Result<get_3pids::v3::Response> { pub async fn third_party_route(
let _sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_3pids::v3::Request>,
) -> Result<get_3pids::v3::Response> {
let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(get_3pids::v3::Response::new(Vec::new())) Ok(get_3pids::v3::Response::new(Vec::new()))
} }
/// # `POST /_matrix/client/v3/account/3pid/email/requestToken` /// # `POST /_matrix/client/v3/account/3pid/email/requestToken`
/// ///
/// "This API should be used to request validation tokens when adding an email /// "This API should be used to request validation tokens when adding an email address to an account"
/// address to an account"
/// ///
/// - 403 signals that The homeserver does not allow the third party identifier /// - 403 signals that The homeserver does not allow the third party identifier as a contact option.
/// as a contact option.
pub async fn request_3pid_management_token_via_email_route( pub async fn request_3pid_management_token_via_email_route(
_body: Ruma<request_3pid_management_token_via_email::v3::Request>, _body: Ruma<request_3pid_management_token_via_email::v3::Request>,
) -> Result<request_3pid_management_token_via_email::v3::Response> { ) -> Result<request_3pid_management_token_via_email::v3::Response> {
Err(Error::BadRequest( Err(Error::BadRequest(
ErrorKind::ThreepidDenied, ErrorKind::ThreepidDenied,
"Third party identifier is not allowed", "Third party identifier is not allowed",
)) ))
} }
/// # `POST /_matrix/client/v3/account/3pid/msisdn/requestToken` /// # `POST /_matrix/client/v3/account/3pid/msisdn/requestToken`
/// ///
/// "This API should be used to request validation tokens when adding an phone /// "This API should be used to request validation tokens when adding an phone number to an account"
/// number to an account"
/// ///
/// - 403 signals that The homeserver does not allow the third party identifier /// - 403 signals that The homeserver does not allow the third party identifier as a contact option.
/// as a contact option.
pub async fn request_3pid_management_token_via_msisdn_route( pub async fn request_3pid_management_token_via_msisdn_route(
_body: Ruma<request_3pid_management_token_via_msisdn::v3::Request>, _body: Ruma<request_3pid_management_token_via_msisdn::v3::Request>,
) -> Result<request_3pid_management_token_via_msisdn::v3::Response> { ) -> Result<request_3pid_management_token_via_msisdn::v3::Response> {
Err(Error::BadRequest( Err(Error::BadRequest(
ErrorKind::ThreepidDenied, ErrorKind::ThreepidDenied,
"Third party identifier is not allowed", "Third party identifier is not allowed",
)) ))
} }
+205 -192
View File
@@ -1,68 +1,64 @@
use rand::seq::SliceRandom;
use ruma::{
api::{
appservice,
client::{
alias::{create_alias, delete_alias, get_alias},
error::ErrorKind,
},
federation,
},
OwnedRoomAliasId, OwnedServerName,
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use rand::seq::SliceRandom;
use regex::Regex;
use ruma::{
api::{
appservice,
client::{
alias::{create_alias, delete_alias, get_alias},
error::ErrorKind,
},
federation,
},
OwnedRoomAliasId, OwnedServerName,
};
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}` /// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
/// ///
/// Creates a new room alias on this server. /// Creates a new room alias on this server.
pub async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result<create_alias::v3::Response> { pub async fn create_alias_route(
if body.room_alias.server_name() != services().globals.server_name() { body: Ruma<create_alias::v3::Request>,
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); ) -> Result<create_alias::v3::Response> {
} if body.room_alias.server_name() != services().globals.server_name() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
}
if services() if services()
.globals .globals
.forbidden_alias_names() .forbidden_room_names()
.is_match(body.room_alias.alias()) .is_match(body.room_alias.alias())
{ {
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias is forbidden.")); return Err(Error::BadRequest(
} ErrorKind::Unknown,
"Room alias is forbidden.",
));
}
if let Some(ref info) = body.appservice_info { if services()
if !info.aliases.is_match(body.room_alias.as_str()) { .rooms
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace.")); .alias
} .resolve_local_alias(&body.room_alias)?
} else if services() .is_some()
.appservice {
.is_exclusive_alias(&body.room_alias) return Err(Error::Conflict("Alias already exists."));
.await }
{
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice."));
}
if services() if services()
.rooms .rooms
.alias .alias
.resolve_local_alias(&body.room_alias)? .set_alias(&body.room_alias, &body.room_id)
.is_some() .is_err()
{ {
return Err(Error::Conflict("Alias already exists.")); return Err(Error::BadRequest(
} ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
));
};
if services() Ok(create_alias::v3::Response::new())
.rooms
.alias
.set_alias(&body.room_alias, &body.room_id)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
));
};
Ok(create_alias::v3::Response::new())
} }
/// # `DELETE /_matrix/client/v3/directory/room/{roomAlias}` /// # `DELETE /_matrix/client/v3/directory/room/{roomAlias}`
@@ -71,166 +67,183 @@ pub async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result
/// ///
/// - TODO: additional access control checks /// - TODO: additional access control checks
/// - TODO: Update canonical alias event /// - TODO: Update canonical alias event
pub async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result<delete_alias::v3::Response> { pub async fn delete_alias_route(
if body.room_alias.server_name() != services().globals.server_name() { body: Ruma<delete_alias::v3::Request>,
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); ) -> Result<delete_alias::v3::Response> {
} if body.room_alias.server_name() != services().globals.server_name() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
}
if services() if services()
.rooms .rooms
.alias .alias
.resolve_local_alias(&body.room_alias)? .resolve_local_alias(&body.room_alias)?
.is_none() .is_none()
{ {
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist.")); return Err(Error::BadRequest(
} ErrorKind::NotFound,
"Alias does not exist.",
));
}
if let Some(ref info) = body.appservice_info { if services()
if !info.aliases.is_match(body.room_alias.as_str()) { .rooms
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace.")); .alias
} .remove_alias(&body.room_alias)
} else if services() .is_err()
.appservice {
.is_exclusive_alias(&body.room_alias) return Err(Error::BadRequest(
.await ErrorKind::InvalidParam,
{ "Invalid room alias. Alias must be in the form of '#localpart:server_name'",
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice.")); ));
} };
if services() // TODO: update alt_aliases?
.rooms
.alias
.remove_alias(&body.room_alias)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
));
};
// TODO: update alt_aliases? Ok(delete_alias::v3::Response::new())
Ok(delete_alias::v3::Response::new())
} }
/// # `GET /_matrix/client/v3/directory/room/{roomAlias}` /// # `GET /_matrix/client/v3/directory/room/{roomAlias}`
/// ///
/// Resolve an alias locally or over federation. /// Resolve an alias locally or over federation.
pub async fn get_alias_route(body: Ruma<get_alias::v3::Request>) -> Result<get_alias::v3::Response> { pub async fn get_alias_route(
get_alias_helper(body.body.room_alias).await body: Ruma<get_alias::v3::Request>,
) -> Result<get_alias::v3::Response> {
get_alias_helper(body.body.room_alias).await
} }
pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get_alias::v3::Response> { pub(crate) async fn get_alias_helper(
if room_alias.server_name() != services().globals.server_name() { room_alias: OwnedRoomAliasId,
let response = services() ) -> Result<get_alias::v3::Response> {
.sending if room_alias.server_name() != services().globals.server_name() {
.send_federation_request( let response = services()
room_alias.server_name(), .sending
federation::query::get_room_information::v1::Request { .send_federation_request(
room_alias: room_alias.clone(), room_alias.server_name(),
}, federation::query::get_room_information::v1::Request {
) room_alias: room_alias.to_owned(),
.await?; },
)
.await?;
let room_id = response.room_id; let room_id = response.room_id;
let mut servers = response.servers; let mut servers = response.servers;
// since the room alias server_name responded, insert it into the list // find active servers in room state cache to suggest
servers.push(room_alias.server_name().into()); for extra_servers in services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(|r| r.ok())
{
servers.push(extra_servers);
}
// find active servers in room state cache to suggest // insert our server as the very first choice if in list
servers.extend( if let Some(server_index) = servers
services() .clone()
.rooms .into_iter()
.state_cache .position(|server| server == services().globals.server_name())
.room_servers(&room_id) {
.filter_map(Result::ok), servers.remove(server_index);
); servers.insert(0, services().globals.server_name().to_owned());
}
servers.sort_unstable(); servers.sort_unstable();
servers.dedup(); servers.dedup();
// shuffle list of servers randomly after sort and dedupe // shuffle list of servers randomly after sort and dedupe
servers.shuffle(&mut rand::thread_rng()); servers.shuffle(&mut rand::thread_rng());
// prefer the very first server to be ourselves if available, else prefer the return Ok(get_alias::v3::Response::new(room_id, servers));
// room alias server first }
if let Some(server_index) = servers
.iter()
.position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
} else if let Some(alias_server_index) = servers
.iter()
.position(|server| server == room_alias.server_name())
{
servers.remove(alias_server_index);
servers.insert(0, room_alias.server_name().into());
}
return Ok(get_alias::v3::Response::new(room_id, servers)); let mut room_id = None;
} match services().rooms.alias.resolve_local_alias(&room_alias)? {
Some(r) => room_id = Some(r),
None => {
for (_id, registration) in services().appservice.all()? {
let aliases = registration
.namespaces
.aliases
.iter()
.filter_map(|alias| Regex::new(alias.regex.as_str()).ok())
.collect::<Vec<_>>();
let mut room_id = None; if aliases
match services().rooms.alias.resolve_local_alias(&room_alias)? { .iter()
Some(r) => room_id = Some(r), .any(|aliases| aliases.is_match(room_alias.as_str()))
None => { && if let Some(opt_result) = services()
for appservice in services().appservice.read().await.values() { .sending
if appservice.aliases.is_match(room_alias.as_str()) .send_appservice_request(
&& matches!( registration,
services() appservice::query::query_room_alias::v1::Request {
.sending room_alias: room_alias.clone(),
.send_appservice_request( },
appservice.registration.clone(), )
appservice::query::query_room_alias::v1::Request { .await
room_alias: room_alias.clone(), {
}, opt_result.is_ok()
) } else {
.await, false
Ok(Some(_opt_result)) }
) { {
room_id = Some( room_id = Some(
services() services()
.rooms .rooms
.alias .alias
.resolve_local_alias(&room_alias)? .resolve_local_alias(&room_alias)?
.ok_or_else(|| Error::bad_config("Room does not exist."))?, .ok_or_else(|| {
); Error::bad_config("Appservice lied to us. Room does not exist.")
break; })?,
} );
} break;
}, }
}; }
}
};
let Some(room_id) = room_id else { let room_id = match room_id {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found.")); Some(room_id) => room_id,
}; None => {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Room with alias not found.",
))
}
};
// find active servers in room state cache to suggest let mut servers: Vec<OwnedServerName> = Vec::new();
let mut servers: Vec<OwnedServerName> = services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(Result::ok)
.collect();
servers.sort_unstable(); // find active servers in room state cache to suggest
servers.dedup(); for extra_servers in services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(|r| r.ok())
{
servers.push(extra_servers);
}
// shuffle list of servers randomly after sort and dedupe // insert our server as the very first choice if in list
servers.shuffle(&mut rand::thread_rng()); if let Some(server_index) = servers
.clone()
.into_iter()
.position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
// insert our server as the very first choice if in list servers.sort_unstable();
if let Some(server_index) = servers servers.dedup();
.iter()
.position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
Ok(get_alias::v3::Response::new(room_id, servers)) // shuffle list of servers randomly after sort and dedupe
servers.shuffle(&mut rand::thread_rng());
Ok(get_alias::v3::Response::new(room_id, servers))
} }
+232 -218
View File
@@ -1,348 +1,362 @@
use ruma::api::client::{
backup::{
add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session, create_backup_version,
delete_backup_keys, delete_backup_keys_for_room, delete_backup_keys_for_session, delete_backup_version,
get_backup_info, get_backup_keys, get_backup_keys_for_room, get_backup_keys_for_session,
get_latest_backup_info, update_backup_version,
},
error::ErrorKind,
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{
backup::{
add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session,
create_backup_version, delete_backup_keys, delete_backup_keys_for_room,
delete_backup_keys_for_session, delete_backup_version, get_backup_info, get_backup_keys,
get_backup_keys_for_room, get_backup_keys_for_session, get_latest_backup_info,
update_backup_version,
},
error::ErrorKind,
};
/// # `POST /_matrix/client/r0/room_keys/version` /// # `POST /_matrix/client/r0/room_keys/version`
/// ///
/// Creates a new backup. /// Creates a new backup.
pub async fn create_backup_version_route( pub async fn create_backup_version_route(
body: Ruma<create_backup_version::v3::Request>, body: Ruma<create_backup_version::v3::Request>,
) -> Result<create_backup_version::v3::Response> { ) -> Result<create_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let version = services() let version = services()
.key_backups .key_backups
.create_backup(sender_user, &body.algorithm)?; .create_backup(sender_user, &body.algorithm)?;
Ok(create_backup_version::v3::Response { Ok(create_backup_version::v3::Response { version })
version,
})
} }
/// # `PUT /_matrix/client/r0/room_keys/version/{version}` /// # `PUT /_matrix/client/r0/room_keys/version/{version}`
/// ///
/// Update information about an existing backup. Only `auth_data` can be /// Update information about an existing backup. Only `auth_data` can be modified.
/// modified.
pub async fn update_backup_version_route( pub async fn update_backup_version_route(
body: Ruma<update_backup_version::v3::Request>, body: Ruma<update_backup_version::v3::Request>,
) -> Result<update_backup_version::v3::Response> { ) -> Result<update_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.key_backups .key_backups
.update_backup(sender_user, &body.version, &body.algorithm)?; .update_backup(sender_user, &body.version, &body.algorithm)?;
Ok(update_backup_version::v3::Response {}) Ok(update_backup_version::v3::Response {})
} }
/// # `GET /_matrix/client/r0/room_keys/version` /// # `GET /_matrix/client/r0/room_keys/version`
/// ///
/// Get information about the latest backup version. /// Get information about the latest backup version.
pub async fn get_latest_backup_info_route( pub async fn get_latest_backup_info_route(
body: Ruma<get_latest_backup_info::v3::Request>, body: Ruma<get_latest_backup_info::v3::Request>,
) -> Result<get_latest_backup_info::v3::Response> { ) -> Result<get_latest_backup_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let (version, algorithm) = services() let (version, algorithm) = services()
.key_backups .key_backups
.get_latest_backup(sender_user)? .get_latest_backup(sender_user)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Key backup does not exist.",
))?;
Ok(get_latest_backup_info::v3::Response { Ok(get_latest_backup_info::v3::Response {
algorithm, algorithm,
count: (services().key_backups.count_keys(sender_user, &version)? as u32).into(), count: (services().key_backups.count_keys(sender_user, &version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &version)?, etag: services().key_backups.get_etag(sender_user, &version)?,
version, version,
}) })
} }
/// # `GET /_matrix/client/r0/room_keys/version` /// # `GET /_matrix/client/r0/room_keys/version`
/// ///
/// Get information about an existing backup. /// Get information about an existing backup.
pub async fn get_backup_info_route(body: Ruma<get_backup_info::v3::Request>) -> Result<get_backup_info::v3::Response> { pub async fn get_backup_info_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_backup_info::v3::Request>,
let algorithm = services() ) -> Result<get_backup_info::v3::Response> {
.key_backups let sender_user = body.sender_user.as_ref().expect("user is authenticated");
.get_backup(sender_user, &body.version)? let algorithm = services()
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?; .key_backups
.get_backup(sender_user, &body.version)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Key backup does not exist.",
))?;
Ok(get_backup_info::v3::Response { Ok(get_backup_info::v3::Response {
algorithm, algorithm,
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
version: body.version.clone(), version: body.version.to_owned(),
}) })
} }
/// # `DELETE /_matrix/client/r0/room_keys/version/{version}` /// # `DELETE /_matrix/client/r0/room_keys/version/{version}`
/// ///
/// Delete an existing key backup. /// Delete an existing key backup.
/// ///
/// - Deletes both information about the backup, as well as all key data related /// - Deletes both information about the backup, as well as all key data related to the backup
/// to the backup
pub async fn delete_backup_version_route( pub async fn delete_backup_version_route(
body: Ruma<delete_backup_version::v3::Request>, body: Ruma<delete_backup_version::v3::Request>,
) -> Result<delete_backup_version::v3::Response> { ) -> Result<delete_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.key_backups .key_backups
.delete_backup(sender_user, &body.version)?; .delete_backup(sender_user, &body.version)?;
Ok(delete_backup_version::v3::Response {}) Ok(delete_backup_version::v3::Response {})
} }
/// # `PUT /_matrix/client/r0/room_keys/keys` /// # `PUT /_matrix/client/r0/room_keys/keys`
/// ///
/// Add the received backup keys to the database. /// Add the received backup keys to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) -> Result<add_backup_keys::v3::Response> { pub async fn add_backup_keys_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<add_backup_keys::v3::Request>,
) -> Result<add_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) if Some(&body.version)
!= services() != services()
.key_backups .key_backups
.get_latest_backup_version(sender_user)? .get_latest_backup_version(sender_user)?
.as_ref() .as_ref()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
)); ));
} }
for (room_id, room) in &body.rooms { for (room_id, room) in &body.rooms {
for (session_id, key_data) in &room.sessions { for (session_id, key_data) in &room.sessions {
services() services().key_backups.add_key(
.key_backups sender_user,
.add_key(sender_user, &body.version, room_id, session_id, key_data)?; &body.version,
} room_id,
} session_id,
key_data,
)?
}
}
Ok(add_backup_keys::v3::Response { Ok(add_backup_keys::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}` /// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}`
/// ///
/// Add the received backup keys to the database. /// Add the received backup keys to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_room_route( pub async fn add_backup_keys_for_room_route(
body: Ruma<add_backup_keys_for_room::v3::Request>, body: Ruma<add_backup_keys_for_room::v3::Request>,
) -> Result<add_backup_keys_for_room::v3::Response> { ) -> Result<add_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) if Some(&body.version)
!= services() != services()
.key_backups .key_backups
.get_latest_backup_version(sender_user)? .get_latest_backup_version(sender_user)?
.as_ref() .as_ref()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
)); ));
} }
for (session_id, key_data) in &body.sessions { for (session_id, key_data) in &body.sessions {
services() services().key_backups.add_key(
.key_backups sender_user,
.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?; &body.version,
} &body.room_id,
session_id,
key_data,
)?
}
Ok(add_backup_keys_for_room::v3::Response { Ok(add_backup_keys_for_room::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
/// ///
/// Add the received backup key to the database. /// Add the received backup key to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_session_route( pub async fn add_backup_keys_for_session_route(
body: Ruma<add_backup_keys_for_session::v3::Request>, body: Ruma<add_backup_keys_for_session::v3::Request>,
) -> Result<add_backup_keys_for_session::v3::Response> { ) -> Result<add_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) if Some(&body.version)
!= services() != services()
.key_backups .key_backups
.get_latest_backup_version(sender_user)? .get_latest_backup_version(sender_user)?
.as_ref() .as_ref()
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
)); ));
} }
services() services().key_backups.add_key(
.key_backups sender_user,
.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?; &body.version,
&body.room_id,
&body.session_id,
&body.session_data,
)?;
Ok(add_backup_keys_for_session::v3::Response { Ok(add_backup_keys_for_session::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
/// # `GET /_matrix/client/r0/room_keys/keys` /// # `GET /_matrix/client/r0/room_keys/keys`
/// ///
/// Retrieves all keys from the backup. /// Retrieves all keys from the backup.
pub async fn get_backup_keys_route(body: Ruma<get_backup_keys::v3::Request>) -> Result<get_backup_keys::v3::Response> { pub async fn get_backup_keys_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_backup_keys::v3::Request>,
) -> Result<get_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let rooms = services().key_backups.get_all(sender_user, &body.version)?; let rooms = services().key_backups.get_all(sender_user, &body.version)?;
Ok(get_backup_keys::v3::Response { Ok(get_backup_keys::v3::Response { rooms })
rooms,
})
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}` /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}`
/// ///
/// Retrieves all keys from the backup for a given room. /// Retrieves all keys from the backup for a given room.
pub async fn get_backup_keys_for_room_route( pub async fn get_backup_keys_for_room_route(
body: Ruma<get_backup_keys_for_room::v3::Request>, body: Ruma<get_backup_keys_for_room::v3::Request>,
) -> Result<get_backup_keys_for_room::v3::Response> { ) -> Result<get_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sessions = services() let sessions = services()
.key_backups .key_backups
.get_room(sender_user, &body.version, &body.room_id)?; .get_room(sender_user, &body.version, &body.room_id)?;
Ok(get_backup_keys_for_room::v3::Response { Ok(get_backup_keys_for_room::v3::Response { sessions })
sessions,
})
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
/// ///
/// Retrieves a key from the backup. /// Retrieves a key from the backup.
pub async fn get_backup_keys_for_session_route( pub async fn get_backup_keys_for_session_route(
body: Ruma<get_backup_keys_for_session::v3::Request>, body: Ruma<get_backup_keys_for_session::v3::Request>,
) -> Result<get_backup_keys_for_session::v3::Response> { ) -> Result<get_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let key_data = services() let key_data = services()
.key_backups .key_backups
.get_session(sender_user, &body.version, &body.room_id, &body.session_id)? .get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"Backup key not found for this user's session.", "Backup key not found for this user's session.",
))?; ))?;
Ok(get_backup_keys_for_session::v3::Response { Ok(get_backup_keys_for_session::v3::Response { key_data })
key_data,
})
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys` /// # `DELETE /_matrix/client/r0/room_keys/keys`
/// ///
/// Delete the keys from the backup. /// Delete the keys from the backup.
pub async fn delete_backup_keys_route( pub async fn delete_backup_keys_route(
body: Ruma<delete_backup_keys::v3::Request>, body: Ruma<delete_backup_keys::v3::Request>,
) -> Result<delete_backup_keys::v3::Response> { ) -> Result<delete_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.key_backups .key_backups
.delete_all_keys(sender_user, &body.version)?; .delete_all_keys(sender_user, &body.version)?;
Ok(delete_backup_keys::v3::Response { Ok(delete_backup_keys::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}` /// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`
/// ///
/// Delete the keys from the backup for a given room. /// Delete the keys from the backup for a given room.
pub async fn delete_backup_keys_for_room_route( pub async fn delete_backup_keys_for_room_route(
body: Ruma<delete_backup_keys_for_room::v3::Request>, body: Ruma<delete_backup_keys_for_room::v3::Request>,
) -> Result<delete_backup_keys_for_room::v3::Response> { ) -> Result<delete_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.key_backups .key_backups
.delete_room_keys(sender_user, &body.version, &body.room_id)?; .delete_room_keys(sender_user, &body.version, &body.room_id)?;
Ok(delete_backup_keys_for_room::v3::Response { Ok(delete_backup_keys_for_room::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
/// ///
/// Delete a key from the backup. /// Delete a key from the backup.
pub async fn delete_backup_keys_for_session_route( pub async fn delete_backup_keys_for_session_route(
body: Ruma<delete_backup_keys_for_session::v3::Request>, body: Ruma<delete_backup_keys_for_session::v3::Request>,
) -> Result<delete_backup_keys_for_session::v3::Response> { ) -> Result<delete_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services().key_backups.delete_room_key(
.key_backups sender_user,
.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?; &body.version,
&body.room_id,
&body.session_id,
)?;
Ok(delete_backup_keys_for_session::v3::Response { Ok(delete_backup_keys_for_session::v3::Response {
count: (services() count: (services()
.key_backups .key_backups
.count_keys(sender_user, &body.version)? as u32) .count_keys(sender_user, &body.version)? as u32)
.into(), .into(),
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
}) })
} }
+20 -43
View File
@@ -1,51 +1,28 @@
use crate::{services, Result, Ruma};
use ruma::api::client::discovery::get_capabilities::{
self, Capabilities, RoomVersionStability, RoomVersionsCapability,
};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma::api::client::discovery::get_capabilities::{ /// # `GET /_matrix/client/r0/capabilities`
self, Capabilities, ChangePasswordCapability, RoomVersionStability, RoomVersionsCapability, SetAvatarUrlCapability,
SetDisplayNameCapability, ThirdPartyIdChangesCapability,
};
use crate::{services, Result, Ruma};
/// # `GET /_matrix/client/v3/capabilities`
/// ///
/// Get information on the supported feature set and other relevent capabilities /// Get information on the supported feature set and other relevent capabilities of this server.
/// of this server.
pub async fn get_capabilities_route( pub async fn get_capabilities_route(
_body: Ruma<get_capabilities::v3::Request>, _body: Ruma<get_capabilities::v3::Request>,
) -> Result<get_capabilities::v3::Response> { ) -> Result<get_capabilities::v3::Response> {
let mut available = BTreeMap::new(); let mut available = BTreeMap::new();
for room_version in &services().globals.unstable_room_versions { for room_version in &services().globals.unstable_room_versions {
available.insert(room_version.clone(), RoomVersionStability::Unstable); available.insert(room_version.clone(), RoomVersionStability::Unstable);
} }
for room_version in &services().globals.stable_room_versions { for room_version in &services().globals.stable_room_versions {
available.insert(room_version.clone(), RoomVersionStability::Stable); available.insert(room_version.clone(), RoomVersionStability::Stable);
} }
let mut capabilities = Capabilities::new(); let mut capabilities = Capabilities::new();
capabilities.room_versions = RoomVersionsCapability { capabilities.room_versions = RoomVersionsCapability {
default: services().globals.default_room_version(), default: services().globals.default_room_version(),
available, available,
}; };
capabilities.change_password = ChangePasswordCapability { Ok(get_capabilities::v3::Response { capabilities })
enabled: true,
};
capabilities.set_avatar_url = SetAvatarUrlCapability {
enabled: true,
};
capabilities.set_displayname = SetDisplayNameCapability {
enabled: true,
};
// conduit does not implement 3PID stuff
capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability {
enabled: false,
};
Ok(get_capabilities::v3::Response {
capabilities,
})
} }
+62 -64
View File
@@ -1,118 +1,116 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{ api::client::{
config::{get_global_account_data, get_room_account_data, set_global_account_data, set_room_account_data}, config::{
error::ErrorKind, get_global_account_data, get_room_account_data, set_global_account_data,
}, set_room_account_data,
events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent}, },
serde::Raw, error::ErrorKind,
},
events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent},
serde::Raw,
}; };
use serde::Deserialize; use serde::Deserialize;
use serde_json::{json, value::RawValue as RawJsonValue}; use serde_json::{json, value::RawValue as RawJsonValue};
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}` /// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
/// ///
/// Sets some account data for the sender user. /// Sets some account data for the sender user.
pub async fn set_global_account_data_route( pub async fn set_global_account_data_route(
body: Ruma<set_global_account_data::v3::Request>, body: Ruma<set_global_account_data::v3::Request>,
) -> Result<set_global_account_data::v3::Response> { ) -> Result<set_global_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let data: serde_json::Value = serde_json::from_str(body.data.json().get()) let data: serde_json::Value = serde_json::from_str(body.data.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?; .map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
let event_type = body.event_type.to_string(); let event_type = body.event_type.to_string();
services().account_data.update( services().account_data.update(
None, None,
sender_user, sender_user,
event_type.clone().into(), event_type.clone().into(),
&json!({ &json!({
"type": event_type, "type": event_type,
"content": data, "content": data,
}), }),
)?; )?;
Ok(set_global_account_data::v3::Response {}) Ok(set_global_account_data::v3::Response {})
} }
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}` /// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
/// ///
/// Sets some room account data for the sender user. /// Sets some room account data for the sender user.
pub async fn set_room_account_data_route( pub async fn set_room_account_data_route(
body: Ruma<set_room_account_data::v3::Request>, body: Ruma<set_room_account_data::v3::Request>,
) -> Result<set_room_account_data::v3::Response> { ) -> Result<set_room_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let data: serde_json::Value = serde_json::from_str(body.data.json().get()) let data: serde_json::Value = serde_json::from_str(body.data.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?; .map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Data is invalid."))?;
let event_type = body.event_type.to_string(); let event_type = body.event_type.to_string();
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
event_type.clone().into(), event_type.clone().into(),
&json!({ &json!({
"type": event_type, "type": event_type,
"content": data, "content": data,
}), }),
)?; )?;
Ok(set_room_account_data::v3::Response {}) Ok(set_room_account_data::v3::Response {})
} }
/// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}` /// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}`
/// ///
/// Gets some account data for the sender user. /// Gets some account data for the sender user.
pub async fn get_global_account_data_route( pub async fn get_global_account_data_route(
body: Ruma<get_global_account_data::v3::Request>, body: Ruma<get_global_account_data::v3::Request>,
) -> Result<get_global_account_data::v3::Response> { ) -> Result<get_global_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event: Box<RawJsonValue> = services() let event: Box<RawJsonValue> = services()
.account_data .account_data
.get(None, sender_user, body.event_type.to_string().into())? .get(None, sender_user, body.event_type.to_string().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
Ok(get_global_account_data::v3::Response { Ok(get_global_account_data::v3::Response { account_data })
account_data,
})
} }
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}` /// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
/// ///
/// Gets some room account data for the sender user. /// Gets some room account data for the sender user.
pub async fn get_room_account_data_route( pub async fn get_room_account_data_route(
body: Ruma<get_room_account_data::v3::Request>, body: Ruma<get_room_account_data::v3::Request>,
) -> Result<get_room_account_data::v3::Response> { ) -> Result<get_room_account_data::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event: Box<RawJsonValue> = services() let event: Box<RawJsonValue> = services()
.account_data .account_data
.get(Some(&body.room_id), sender_user, body.event_type.clone())? .get(Some(&body.room_id), sender_user, body.event_type.clone())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
Ok(get_room_account_data::v3::Response { Ok(get_room_account_data::v3::Response { account_data })
account_data,
})
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractRoomEventContent { struct ExtractRoomEventContent {
content: Raw<AnyRoomAccountDataEventContent>, content: Raw<AnyRoomAccountDataEventContent>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct ExtractGlobalEventContent { struct ExtractGlobalEventContent {
content: Raw<AnyGlobalAccountDataEventContent>, content: Raw<AnyGlobalAccountDataEventContent>,
} }
+177 -169
View File
@@ -1,201 +1,209 @@
use std::collections::HashSet;
use ruma::{
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
events::StateEventType,
};
use tracing::error;
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::{
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
events::StateEventType,
};
use std::collections::HashSet;
use tracing::error;
/// # `GET /_matrix/client/r0/rooms/{roomId}/context` /// # `GET /_matrix/client/r0/rooms/{roomId}/context`
/// ///
/// Allows loading room history around an event. /// Allows loading room history around an event.
/// ///
/// - Only works if the user is joined (TODO: always allow, but only show events /// - Only works if the user is joined (TODO: always allow, but only show events if the user was
/// if the user was
/// joined, depending on history_visibility) /// joined, depending on history_visibility)
pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<get_context::v3::Response> { pub async fn get_context_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_context::v3::Request>,
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); ) -> Result<get_context::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
let (lazy_load_enabled, lazy_load_send_redundant) = match &body.filter.lazy_load_options { let (lazy_load_enabled, lazy_load_send_redundant) = match &body.filter.lazy_load_options {
LazyLoadOptions::Enabled { LazyLoadOptions::Enabled {
include_redundant_members, include_redundant_members,
} => (true, *include_redundant_members), } => (true, *include_redundant_members),
LazyLoadOptions::Disabled => (false, false), _ => (false, false),
}; };
let mut lazy_loaded = HashSet::new(); let mut lazy_loaded = HashSet::new();
let base_token = services() let base_token = services()
.rooms .rooms
.timeline .timeline
.get_pdu_count(&body.event_id)? .get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event id not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Base event id not found.",
))?;
let base_event = services() let base_event =
.rooms services()
.timeline .rooms
.get_pdu(&body.event_id)? .timeline
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event not found."))?; .get_pdu(&body.event_id)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Base event not found.",
))?;
let room_id = base_event.room_id.clone(); let room_id = base_event.room_id.clone();
if !services() if !services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_event(sender_user, &room_id, &body.event_id)? .user_can_see_event(sender_user, &room_id, &body.event_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::forbidden(), ErrorKind::Forbidden,
"You don't have permission to view this event.", "You don't have permission to view this event.",
)); ));
} }
if !services().rooms.lazy_loading.lazy_load_was_sent_before( if !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user, sender_user,
sender_device, sender_device,
&room_id, &room_id,
&base_event.sender, &base_event.sender,
)? || lazy_load_send_redundant )? || lazy_load_send_redundant
{ {
lazy_loaded.insert(base_event.sender.as_str().to_owned()); lazy_loaded.insert(base_event.sender.as_str().to_owned());
} }
// Use limit with maximum 100 // Use limit with maximum 100
let limit = u64::from(body.limit).min(100) as usize; let limit = u64::from(body.limit).min(100) as usize;
let base_event = base_event.to_room_event(); let base_event = base_event.to_room_event();
let events_before: Vec<_> = services() let events_before: Vec<_> = services()
.rooms .rooms
.timeline .timeline
.pdus_until(sender_user, &room_id, base_token)? .pdus_until(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(Result::ok) // Remove buggy events .filter_map(|r| r.ok()) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_event(sender_user, &room_id, &pdu.event_id) .user_can_see_event(sender_user, &room_id, &pdu.event_id)
.unwrap_or(false) .unwrap_or(false)
}) })
.collect(); .collect();
for (_, event) in &events_before { for (_, event) in &events_before {
if !services().rooms.lazy_loading.lazy_load_was_sent_before( if !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user, sender_user,
sender_device, sender_device,
&room_id, &room_id,
&event.sender, &event.sender,
)? || lazy_load_send_redundant )? || lazy_load_send_redundant
{ {
lazy_loaded.insert(event.sender.as_str().to_owned()); lazy_loaded.insert(event.sender.as_str().to_owned());
} }
} }
let start_token = events_before let start_token = events_before
.last() .last()
.map_or_else(|| base_token.stringify(), |(count, _)| count.stringify()); .map(|(count, _)| count.stringify())
.unwrap_or_else(|| base_token.stringify());
let events_before: Vec<_> = events_before let events_before: Vec<_> = events_before
.into_iter() .into_iter()
.map(|(_, pdu)| pdu.to_room_event()) .map(|(_, pdu)| pdu.to_room_event())
.collect(); .collect();
let events_after: Vec<_> = services() let events_after: Vec<_> = services()
.rooms .rooms
.timeline .timeline
.pdus_after(sender_user, &room_id, base_token)? .pdus_after(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(Result::ok) // Remove buggy events .filter_map(|r| r.ok()) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_event(sender_user, &room_id, &pdu.event_id) .user_can_see_event(sender_user, &room_id, &pdu.event_id)
.unwrap_or(false) .unwrap_or(false)
}) })
.collect(); .collect();
for (_, event) in &events_after { for (_, event) in &events_after {
if !services().rooms.lazy_loading.lazy_load_was_sent_before( if !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user, sender_user,
sender_device, sender_device,
&room_id, &room_id,
&event.sender, &event.sender,
)? || lazy_load_send_redundant )? || lazy_load_send_redundant
{ {
lazy_loaded.insert(event.sender.as_str().to_owned()); lazy_loaded.insert(event.sender.as_str().to_owned());
} }
} }
let shortstatehash = services() let shortstatehash = match services().rooms.state_accessor.pdu_shortstatehash(
.rooms events_after
.state_accessor .last()
.pdu_shortstatehash( .map_or(&*body.event_id, |(_, e)| &*e.event_id),
events_after )? {
.last() Some(s) => s,
.map_or(&*body.event_id, |(_, e)| &*e.event_id), None => services()
)? .rooms
.map_or( .state
services() .get_room_shortstatehash(&room_id)?
.rooms .expect("All rooms have state"),
.state };
.get_room_shortstatehash(&room_id)?
.expect("All rooms have state"),
|hash| hash,
);
let state_ids = services() let state_ids = services()
.rooms .rooms
.state_accessor .state_accessor
.state_full_ids(shortstatehash) .state_full_ids(shortstatehash)
.await?; .await?;
let end_token = events_after let end_token = events_after
.last() .last()
.map_or_else(|| base_token.stringify(), |(count, _)| count.stringify()); .map(|(count, _)| count.stringify())
.unwrap_or_else(|| base_token.stringify());
let events_after: Vec<_> = events_after let events_after: Vec<_> = events_after
.into_iter() .into_iter()
.map(|(_, pdu)| pdu.to_room_event()) .map(|(_, pdu)| pdu.to_room_event())
.collect(); .collect();
let mut state = Vec::new(); let mut state = Vec::new();
for (shortstatekey, id) in state_ids { for (shortstatekey, id) in state_ids {
let (event_type, state_key) = services() let (event_type, state_key) = services()
.rooms .rooms
.short .short
.get_statekey_from_short(shortstatekey)?; .get_statekey_from_short(shortstatekey)?;
if event_type != StateEventType::RoomMember { if event_type != StateEventType::RoomMember {
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else { let pdu = match services().rooms.timeline.get_pdu(&id)? {
error!("Pdu in state not found: {}", id); Some(pdu) => pdu,
continue; None => {
}; error!("Pdu in state not found: {}", id);
continue;
}
};
state.push(pdu.to_state_event());
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
let pdu = match services().rooms.timeline.get_pdu(&id)? {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id);
continue;
}
};
state.push(pdu.to_state_event());
}
}
state.push(pdu.to_state_event()); let resp = get_context::v3::Response {
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) { start: Some(start_token),
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else { end: Some(end_token),
error!("Pdu in state not found: {}", id); events_before,
continue; event: Some(base_event),
}; events_after,
state,
};
state.push(pdu.to_state_event()); Ok(resp)
}
}
let resp = get_context::v3::Response {
start: Some(start_token),
end: Some(end_token),
events_before,
event: Some(base_event),
events_after,
state,
};
Ok(resp)
} }
+112 -106
View File
@@ -1,63 +1,65 @@
use crate::{services, utils, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
device::{self, delete_device, delete_devices, get_device, get_devices, update_device}, device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
error::ErrorKind, error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
}; };
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{services, utils, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/devices` /// # `GET /_matrix/client/r0/devices`
/// ///
/// Get metadata on all devices of the sender user. /// Get metadata on all devices of the sender user.
pub async fn get_devices_route(body: Ruma<get_devices::v3::Request>) -> Result<get_devices::v3::Response> { pub async fn get_devices_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_devices::v3::Request>,
) -> Result<get_devices::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let devices: Vec<device::Device> = services() let devices: Vec<device::Device> = services()
.users .users
.all_devices_metadata(sender_user) .all_devices_metadata(sender_user)
.filter_map(Result::ok) // Filter out buggy devices .filter_map(|r| r.ok()) // Filter out buggy devices
.collect(); .collect();
Ok(get_devices::v3::Response { Ok(get_devices::v3::Response { devices })
devices,
})
} }
/// # `GET /_matrix/client/r0/devices/{deviceId}` /// # `GET /_matrix/client/r0/devices/{deviceId}`
/// ///
/// Get metadata on a single device of the sender user. /// Get metadata on a single device of the sender user.
pub async fn get_device_route(body: Ruma<get_device::v3::Request>) -> Result<get_device::v3::Response> { pub async fn get_device_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_device::v3::Request>,
) -> Result<get_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device = services() let device = services()
.users .users
.get_device_metadata(sender_user, &body.body.device_id)? .get_device_metadata(sender_user, &body.body.device_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
Ok(get_device::v3::Response { Ok(get_device::v3::Response { device })
device,
})
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}` /// # `PUT /_matrix/client/r0/devices/{deviceId}`
/// ///
/// Updates the metadata on a given device of the sender user. /// Updates the metadata on a given device of the sender user.
pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Result<update_device::v3::Response> { pub async fn update_device_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<update_device::v3::Request>,
) -> Result<update_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut device = services() let mut device = services()
.users .users
.get_device_metadata(sender_user, &body.device_id)? .get_device_metadata(sender_user, &body.device_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
device.display_name.clone_from(&body.display_name); device.display_name = body.display_name.clone();
services() services()
.users .users
.update_device_metadata(sender_user, &body.device_id, &device)?; .update_device_metadata(sender_user, &body.device_id, &device)?;
Ok(update_device::v3::Response {}) Ok(update_device::v3::Response {})
} }
/// # `DELETE /_matrix/client/r0/devices/{deviceId}` /// # `DELETE /_matrix/client/r0/devices/{deviceId}`
@@ -66,48 +68,50 @@ pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Resu
/// ///
/// - Requires UIAA to verify user password /// - Requires UIAA to verify user password
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Result<delete_device::v3::Response> { pub async fn delete_device_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<delete_device::v3::Request>,
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); ) -> Result<delete_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
// UIAA // UIAA
let mut uiaainfo = UiaaInfo { let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow { flows: vec![AuthFlow {
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services() let (worked, uiaainfo) =
.uiaa services()
.try_auth(sender_user, sender_device, auth, &uiaainfo)?; .uiaa
if !worked { .try_auth(sender_user, sender_device, auth, &uiaainfo)?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); } else if let Some(json) = body.json_body {
services() uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.uiaa services()
.create(sender_user, sender_device, &uiaainfo, &json)?; .uiaa
return Err(Error::Uiaa(uiaainfo)); .create(sender_user, sender_device, &uiaainfo, &json)?;
} else { return Err(Error::Uiaa(uiaainfo));
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); } else {
} return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
services() services()
.users .users
.remove_device(sender_user, &body.device_id)?; .remove_device(sender_user, &body.device_id)?;
Ok(delete_device::v3::Response {}) Ok(delete_device::v3::Response {})
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}` /// # `PUT /_matrix/client/r0/devices/{deviceId}`
@@ -118,46 +122,48 @@ pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Resu
/// ///
/// For each device: /// For each device:
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_devices_route(body: Ruma<delete_devices::v3::Request>) -> Result<delete_devices::v3::Response> { pub async fn delete_devices_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<delete_devices::v3::Request>,
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); ) -> Result<delete_devices::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
// UIAA // UIAA
let mut uiaainfo = UiaaInfo { let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow { flows: vec![AuthFlow {
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services() let (worked, uiaainfo) =
.uiaa services()
.try_auth(sender_user, sender_device, auth, &uiaainfo)?; .uiaa
if !worked { .try_auth(sender_user, sender_device, auth, &uiaainfo)?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); } else if let Some(json) = body.json_body {
services() uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.uiaa services()
.create(sender_user, sender_device, &uiaainfo, &json)?; .uiaa
return Err(Error::Uiaa(uiaainfo)); .create(sender_user, sender_device, &uiaainfo, &json)?;
} else { return Err(Error::Uiaa(uiaainfo));
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); } else {
} return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
for device_id in &body.devices { for device_id in &body.devices {
services().users.remove_device(sender_user, device_id)?; services().users.remove_device(sender_user, device_id)?
} }
Ok(delete_devices::v3::Response {}) Ok(delete_devices::v3::Response {})
} }
+321 -327
View File
@@ -1,66 +1,57 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
directory::{get_public_rooms, get_public_rooms_filtered, get_room_visibility, set_room_visibility}, directory::{
error::ErrorKind, get_public_rooms, get_public_rooms_filtered, get_room_visibility,
room, set_room_visibility,
}, },
federation, error::ErrorKind,
}, room,
directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork}, },
events::{ federation,
room::{ },
avatar::RoomAvatarEventContent, directory::{Filter, PublicRoomJoinRule, PublicRoomsChunk, RoomNetwork},
canonical_alias::RoomCanonicalAliasEventContent, events::{
create::RoomCreateEventContent, room::{
guest_access::{GuestAccess, RoomGuestAccessEventContent}, avatar::RoomAvatarEventContent,
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, canonical_alias::RoomCanonicalAliasEventContent,
join_rules::{JoinRule, RoomJoinRulesEventContent}, create::RoomCreateEventContent,
topic::RoomTopicEventContent, guest_access::{GuestAccess, RoomGuestAccessEventContent},
}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
StateEventType, join_rules::{JoinRule, RoomJoinRulesEventContent},
}, topic::RoomTopicEventContent,
ServerName, UInt, },
StateEventType,
},
ServerName, UInt,
}; };
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use crate::{services, Error, Result, Ruma};
/// # `POST /_matrix/client/v3/publicRooms` /// # `POST /_matrix/client/v3/publicRooms`
/// ///
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
/// ///
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_filtered_route( pub async fn get_public_rooms_filtered_route(
body: Ruma<get_public_rooms_filtered::v3::Request>, body: Ruma<get_public_rooms_filtered::v3::Request>,
) -> Result<get_public_rooms_filtered::v3::Response> { ) -> Result<get_public_rooms_filtered::v3::Response> {
if let Some(server) = &body.server { if !services()
if services() .globals
.globals .config
.forbidden_remote_room_directory_server_names() .allow_public_room_directory_without_auth
.contains(server) {
{ let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
return Err(Error::BadRequest( }
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let response = get_public_rooms_filtered_helper( get_public_rooms_filtered_helper(
body.server.as_deref(), body.server.as_deref(),
body.limit, body.limit,
body.since.as_deref(), body.since.as_deref(),
&body.filter, &body.filter,
&body.room_network, &body.room_network,
) )
.await .await
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
})?;
Ok(response)
} }
/// # `GET /_matrix/client/v3/publicRooms` /// # `GET /_matrix/client/v3/publicRooms`
@@ -69,40 +60,31 @@ pub async fn get_public_rooms_filtered_route(
/// ///
/// - Rooms are ordered by the number of joined members /// - Rooms are ordered by the number of joined members
pub async fn get_public_rooms_route( pub async fn get_public_rooms_route(
body: Ruma<get_public_rooms::v3::Request>, body: Ruma<get_public_rooms::v3::Request>,
) -> Result<get_public_rooms::v3::Response> { ) -> Result<get_public_rooms::v3::Response> {
if let Some(server) = &body.server { if !services()
if services() .globals
.globals .config
.forbidden_remote_room_directory_server_names() .allow_public_room_directory_without_auth
.contains(server) {
{ let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
return Err(Error::BadRequest( }
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let response = get_public_rooms_filtered_helper( let response = get_public_rooms_filtered_helper(
body.server.as_deref(), body.server.as_deref(),
body.limit, body.limit,
body.since.as_deref(), body.since.as_deref(),
&Filter::default(), &Filter::default(),
&RoomNetwork::Matrix, &RoomNetwork::Matrix,
) )
.await .await?;
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
})?;
Ok(get_public_rooms::v3::Response { Ok(get_public_rooms::v3::Response {
chunk: response.chunk, chunk: response.chunk,
prev_batch: response.prev_batch, prev_batch: response.prev_batch,
next_batch: response.next_batch, next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate, total_room_count_estimate: response.total_room_count_estimate,
}) })
} }
/// # `PUT /_matrix/client/r0/directory/list/room/{roomId}` /// # `PUT /_matrix/client/r0/directory/list/room/{roomId}`
@@ -111,282 +93,294 @@ pub async fn get_public_rooms_route(
/// ///
/// - TODO: Access control checks /// - TODO: Access control checks
pub async fn set_room_visibility_route( pub async fn set_room_visibility_route(
body: Ruma<set_room_visibility::v3::Request>, body: Ruma<set_room_visibility::v3::Request>,
) -> Result<set_room_visibility::v3::Response> { ) -> Result<set_room_visibility::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.metadata.exists(&body.room_id)? { if !services().rooms.metadata.exists(&body.room_id)? {
// Return 404 if the room doesn't exist // Return 404 if the room doesn't exist
return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found")); return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
} }
match &body.visibility { match &body.visibility {
room::Visibility::Public => { room::Visibility::Public => {
if services().globals.config.lockdown_public_room_directory && !services().users.is_admin(sender_user)? { services().rooms.directory.set_public(&body.room_id)?;
info!( info!("{} made {} public", sender_user, body.room_id);
"Non-admin user {sender_user} tried to publish {0} to the room directory while \ }
\"lockdown_public_room_directory\" is enabled", room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
body.room_id _ => {
); return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room visibility type is not supported.",
));
}
}
return Err(Error::BadRequest( Ok(set_room_visibility::v3::Response {})
ErrorKind::forbidden(),
"Publishing rooms to the room directory is not allowed",
));
}
services().rooms.directory.set_public(&body.room_id)?;
info!("{sender_user} made {0} public", body.room_id);
},
room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
_ => {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room visibility type is not supported.",
));
},
}
Ok(set_room_visibility::v3::Response {})
} }
/// # `GET /_matrix/client/r0/directory/list/room/{roomId}` /// # `GET /_matrix/client/r0/directory/list/room/{roomId}`
/// ///
/// Gets the visibility of a given room in the room directory. /// Gets the visibility of a given room in the room directory.
pub async fn get_room_visibility_route( pub async fn get_room_visibility_route(
body: Ruma<get_room_visibility::v3::Request>, body: Ruma<get_room_visibility::v3::Request>,
) -> Result<get_room_visibility::v3::Response> { ) -> Result<get_room_visibility::v3::Response> {
if !services().rooms.metadata.exists(&body.room_id)? { if !services().rooms.metadata.exists(&body.room_id)? {
// Return 404 if the room doesn't exist // Return 404 if the room doesn't exist
return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found")); return Err(Error::BadRequest(ErrorKind::NotFound, "Room not found"));
} }
Ok(get_room_visibility::v3::Response { Ok(get_room_visibility::v3::Response {
visibility: if services().rooms.directory.is_public_room(&body.room_id)? { visibility: if services().rooms.directory.is_public_room(&body.room_id)? {
room::Visibility::Public room::Visibility::Public
} else { } else {
room::Visibility::Private room::Visibility::Private
}, },
}) })
} }
pub(crate) async fn get_public_rooms_filtered_helper( pub(crate) async fn get_public_rooms_filtered_helper(
server: Option<&ServerName>, limit: Option<UInt>, since: Option<&str>, filter: &Filter, _network: &RoomNetwork, server: Option<&ServerName>,
limit: Option<UInt>,
since: Option<&str>,
filter: &Filter,
_network: &RoomNetwork,
) -> Result<get_public_rooms_filtered::v3::Response> { ) -> Result<get_public_rooms_filtered::v3::Response> {
if let Some(other_server) = server.filter(|server| *server != services().globals.server_name().as_str()) { if let Some(other_server) =
let response = services() server.filter(|server| *server != services().globals.server_name().as_str())
.sending {
.send_federation_request( let response = services()
other_server, .sending
federation::directory::get_public_rooms_filtered::v1::Request { .send_federation_request(
limit, other_server,
since: since.map(ToOwned::to_owned), federation::directory::get_public_rooms_filtered::v1::Request {
filter: Filter { limit,
generic_search_term: filter.generic_search_term.clone(), since: since.map(ToOwned::to_owned),
room_types: filter.room_types.clone(), filter: Filter {
}, generic_search_term: filter.generic_search_term.clone(),
room_network: RoomNetwork::Matrix, room_types: filter.room_types.clone(),
}, },
) room_network: RoomNetwork::Matrix,
.await?; },
)
.await?;
return Ok(get_public_rooms_filtered::v3::Response { return Ok(get_public_rooms_filtered::v3::Response {
chunk: response.chunk, chunk: response.chunk,
prev_batch: response.prev_batch, prev_batch: response.prev_batch,
next_batch: response.next_batch, next_batch: response.next_batch,
total_room_count_estimate: response.total_room_count_estimate, total_room_count_estimate: response.total_room_count_estimate,
}); });
} }
let limit = limit.map_or(10, u64::from); let limit = limit.map_or(10, u64::from);
let mut num_since = 0_u64; let mut num_since = 0_u64;
if let Some(s) = &since { if let Some(s) = &since {
let mut characters = s.chars(); let mut characters = s.chars();
let backwards = match characters.next() { let backwards = match characters.next() {
Some('n') => false, Some('n') => false,
Some('p') => true, Some('p') => true,
_ => return Err(Error::BadRequest(ErrorKind::InvalidParam, "Invalid `since` token")), _ => {
}; return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid `since` token",
))
}
};
num_since = characters num_since = characters
.collect::<String>() .collect::<String>()
.parse() .parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `since` token."))?; .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `since` token."))?;
if backwards { if backwards {
num_since = num_since.saturating_sub(limit); num_since = num_since.saturating_sub(limit);
} }
} }
let mut all_rooms: Vec<_> = services() let mut all_rooms: Vec<_> = services()
.rooms .rooms
.directory .directory
.public_rooms() .public_rooms()
.map(|room_id| { .map(|room_id| {
let room_id = room_id?; let room_id = room_id?;
let chunk = PublicRoomsChunk { let chunk = PublicRoomsChunk {
canonical_alias: services() canonical_alias: services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")? .room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")?
.map_or(Ok(None), |s| { .map_or(Ok(None), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomCanonicalAliasEventContent| c.alias) .map(|c: RoomCanonicalAliasEventContent| c.alias)
.map_err(|_| Error::bad_database("Invalid canonical alias event in database.")) .map_err(|_| {
})?, Error::bad_database("Invalid canonical alias event in database.")
name: services().rooms.state_accessor.get_name(&room_id)?, })
num_joined_members: services() })?,
.rooms name: services().rooms.state_accessor.get_name(&room_id)?,
.state_cache num_joined_members: services()
.room_joined_count(&room_id)? .rooms
.unwrap_or_else(|| { .state_cache
warn!("Room {} has no member count", room_id); .room_joined_count(&room_id)?
0 .unwrap_or_else(|| {
}) warn!("Room {} has no member count", room_id);
.try_into() 0
.expect("user count should not be that big"), })
topic: services() .try_into()
.rooms .expect("user count should not be that big"),
.state_accessor topic: services()
.room_state_get(&room_id, &StateEventType::RoomTopic, "")? .rooms
.map_or(Ok(None), |s| { .state_accessor
serde_json::from_str(s.content.get()) .room_state_get(&room_id, &StateEventType::RoomTopic, "")?
.map(|c: RoomTopicEventContent| Some(c.topic)) .map_or(Ok(None), |s| {
.map_err(|e| { serde_json::from_str(s.content.get())
error!("Invalid room topic event in database for room {room_id}: {e}"); .map(|c: RoomTopicEventContent| Some(c.topic))
Error::bad_database("Invalid room topic event in database.") .map_err(|_| {
}) error!("Invalid room topic event in database for room {}", room_id);
}) Error::bad_database("Invalid room topic event in database.")
.unwrap_or(None), })
world_readable: services() })
.rooms .unwrap_or(None),
.state_accessor world_readable: services()
.room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")? .rooms
.map_or(Ok(false), |s| { .state_accessor
serde_json::from_str(s.content.get()) .room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
.map(|c: RoomHistoryVisibilityEventContent| { .map_or(Ok(false), |s| {
c.history_visibility == HistoryVisibility::WorldReadable serde_json::from_str(s.content.get())
}) .map(|c: RoomHistoryVisibilityEventContent| {
c.history_visibility == HistoryVisibility::WorldReadable
})
.map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})
})?,
guest_can_join: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
.map_or(Ok(false), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomGuestAccessEventContent| {
c.guest_access == GuestAccess::CanJoin
})
.map_err(|_| {
Error::bad_database("Invalid room guest access event in database.")
})
})?,
avatar_url: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomAvatar, "")?
.map(|s| {
serde_json::from_str(s.content.get())
.map(|c: RoomAvatarEventContent| c.url)
.map_err(|_| {
Error::bad_database("Invalid room avatar event in database.")
})
})
.transpose()?
// url is now an Option<String> so we must flatten
.flatten(),
join_rule: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomJoinRules, "")?
.map(|s| {
serde_json::from_str(s.content.get())
.map(|c: RoomJoinRulesEventContent| match c.join_rule {
JoinRule::Public => Some(PublicRoomJoinRule::Public),
JoinRule::Knock => Some(PublicRoomJoinRule::Knock),
_ => None,
})
.map_err(|e| { .map_err(|e| {
error!( error!("Invalid room join rule event in database: {}", e);
"Invalid room history visibility event in database for room {room_id}, assuming is \"shared\": {e}", Error::BadDatabase("Invalid room join rule event in database.")
); })
Error::bad_database("Invalid room history visibility event in database.") })
})}).unwrap_or(false), .transpose()?
guest_can_join: services() .flatten()
.rooms .ok_or_else(|| Error::bad_database("Missing room join rule event for room."))?,
.state_accessor room_type: services()
.room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")? .rooms
.map_or(Ok(false), |s| { .state_accessor
serde_json::from_str(s.content.get()) .room_state_get(&room_id, &StateEventType::RoomCreate, "")?
.map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin) .map(|s| {
.map_err(|_| Error::bad_database("Invalid room guest access event in database.")) serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(
})?, |e| {
avatar_url: services() error!("Invalid room create event in database: {}", e);
.rooms Error::BadDatabase("Invalid room create event in database.")
.state_accessor },
.room_state_get(&room_id, &StateEventType::RoomAvatar, "")? )
.map(|s| { })
serde_json::from_str(s.content.get()) .transpose()?
.map(|c: RoomAvatarEventContent| c.url) .and_then(|e| e.room_type),
.map_err(|_| Error::bad_database("Invalid room avatar event in database.")) room_id,
}) };
.transpose()? Ok(chunk)
// url is now an Option<String> so we must flatten })
.flatten(), .filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
join_rule: services() .filter(|chunk| {
.rooms if let Some(query) = filter
.state_accessor .generic_search_term
.room_state_get(&room_id, &StateEventType::RoomJoinRules, "")? .as_ref()
.map(|s| { .map(|q| q.to_lowercase())
serde_json::from_str(s.content.get()) {
.map(|c: RoomJoinRulesEventContent| match c.join_rule { if let Some(name) = &chunk.name {
JoinRule::Public => Some(PublicRoomJoinRule::Public), if name.as_str().to_lowercase().contains(&query) {
JoinRule::Knock => Some(PublicRoomJoinRule::Knock), return true;
_ => None, }
}) }
.map_err(|e| {
error!("Invalid room join rule event in database: {}", e);
Error::BadDatabase("Invalid room join rule event in database.")
})
})
.transpose()?
.flatten()
.ok_or_else(|| Error::bad_database("Missing room join rule event for room."))?,
room_type: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCreate, "")?
.map(|s| {
serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(|e| {
error!("Invalid room create event in database: {}", e);
Error::BadDatabase("Invalid room create event in database.")
})
})
.transpose()?
.and_then(|e| e.room_type),
room_id,
};
Ok(chunk)
})
.filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
.filter(|chunk| {
if let Some(query) = filter.generic_search_term.as_ref().map(|q| q.to_lowercase()) {
if let Some(name) = &chunk.name {
if name.as_str().to_lowercase().contains(&query) {
return true;
}
}
if let Some(topic) = &chunk.topic { if let Some(topic) = &chunk.topic {
if topic.to_lowercase().contains(&query) { if topic.to_lowercase().contains(&query) {
return true; return true;
} }
} }
if let Some(canonical_alias) = &chunk.canonical_alias { if let Some(canonical_alias) = &chunk.canonical_alias {
if canonical_alias.as_str().to_lowercase().contains(&query) { if canonical_alias.as_str().to_lowercase().contains(&query) {
return true; return true;
} }
} }
false false
} else { } else {
// No search term // No search term
true true
} }
}) })
// We need to collect all, so we can sort by member count // We need to collect all, so we can sort by member count
.collect(); .collect();
all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members)); all_rooms.sort_by(|l, r| r.num_joined_members.cmp(&l.num_joined_members));
let total_room_count_estimate = (all_rooms.len() as u32).into(); let total_room_count_estimate = (all_rooms.len() as u32).into();
let chunk: Vec<_> = all_rooms let chunk: Vec<_> = all_rooms
.into_iter() .into_iter()
.skip(num_since as usize) .skip(num_since as usize)
.take(limit as usize) .take(limit as usize)
.collect(); .collect();
let prev_batch = if num_since == 0 { let prev_batch = if num_since == 0 {
None None
} else { } else {
Some(format!("p{num_since}")) Some(format!("p{num_since}"))
}; };
let next_batch = if chunk.len() < limit as usize { let next_batch = if chunk.len() < limit as usize {
None None
} else { } else {
Some(format!("n{}", num_since + limit)) Some(format!("n{}", num_since + limit))
}; };
Ok(get_public_rooms_filtered::v3::Response { Ok(get_public_rooms_filtered::v3::Response {
chunk, chunk,
prev_batch, prev_batch,
next_batch, next_batch,
total_room_count_estimate: Some(total_room_count_estimate), total_room_count_estimate: Some(total_room_count_estimate),
}) })
} }
+20 -16
View File
@@ -1,30 +1,34 @@
use ruma::api::client::{
error::ErrorKind,
filter::{create_filter, get_filter},
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{
error::ErrorKind,
filter::{create_filter, get_filter},
};
/// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}` /// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`
/// ///
/// Loads a filter that was previously created. /// Loads a filter that was previously created.
/// ///
/// - A user can only access their own filters /// - A user can only access their own filters
pub async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Result<get_filter::v3::Response> { pub async fn get_filter_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_filter::v3::Request>,
let Some(filter) = services().users.get_filter(sender_user, &body.filter_id)? else { ) -> Result<get_filter::v3::Response> {
return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found.")); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
}; let filter = match services().users.get_filter(sender_user, &body.filter_id)? {
Some(filter) => filter,
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found.")),
};
Ok(get_filter::v3::Response::new(filter)) Ok(get_filter::v3::Response::new(filter))
} }
/// # `PUT /_matrix/client/r0/user/{userId}/filter` /// # `PUT /_matrix/client/r0/user/{userId}/filter`
/// ///
/// Creates a new filter to be used by other endpoints. /// Creates a new filter to be used by other endpoints.
pub async fn create_filter_route(body: Ruma<create_filter::v3::Request>) -> Result<create_filter::v3::Response> { pub async fn create_filter_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<create_filter::v3::Request>,
Ok(create_filter::v3::Response::new( ) -> Result<create_filter::v3::Response> {
services().users.create_filter(sender_user, &body.filter)?, let sender_user = body.sender_user.as_ref().expect("user is authenticated");
)) Ok(create_filter::v3::Response::new(
services().users.create_filter(sender_user, &body.filter)?,
))
} }
+451 -422
View File
@@ -1,63 +1,65 @@
use std::{
collections::{hash_map, BTreeMap, HashMap, HashSet},
time::{Duration, Instant},
};
use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{
api::{
client::{
error::ErrorKind,
keys::{claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures, upload_signing_keys},
uiaa::{AuthFlow, AuthType, UiaaInfo},
},
federation,
},
serde::Raw,
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
};
use serde_json::json;
use tracing::{debug, error};
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{services, utils, Error, Result, Ruma}; use crate::{services, utils, Error, Result, Ruma};
use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{
api::{
client::{
error::ErrorKind,
keys::{
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
upload_signing_keys,
},
uiaa::{AuthFlow, AuthType, UiaaInfo},
},
federation,
},
serde::Raw,
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
};
use serde_json::json;
use std::{
collections::{hash_map, BTreeMap, HashMap, HashSet},
time::{Duration, Instant},
};
use tracing::{debug, error};
/// # `POST /_matrix/client/r0/keys/upload` /// # `POST /_matrix/client/r0/keys/upload`
/// ///
/// Publish end-to-end encryption keys for the sender device. /// Publish end-to-end encryption keys for the sender device.
/// ///
/// - Adds one time keys /// - Adds one time keys
/// - If there are no device keys yet: Adds device keys (TODO: merge with /// - If there are no device keys yet: Adds device keys (TODO: merge with existing keys?)
/// existing keys?) pub async fn upload_keys_route(
pub async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<upload_keys::v3::Response> { body: Ruma<upload_keys::v3::Request>,
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); ) -> Result<upload_keys::v3::Response> {
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
for (key_key, key_value) in &body.one_time_keys { for (key_key, key_value) in &body.one_time_keys {
services() services()
.users .users
.add_one_time_key(sender_user, sender_device, key_key, key_value)?; .add_one_time_key(sender_user, sender_device, key_key, key_value)?;
} }
if let Some(device_keys) = &body.device_keys { if let Some(device_keys) = &body.device_keys {
// TODO: merge this and the existing event? // TODO: merge this and the existing event?
// This check is needed to assure that signatures are kept // This check is needed to assure that signatures are kept
if services() if services()
.users .users
.get_device_keys(sender_user, sender_device)? .get_device_keys(sender_user, sender_device)?
.is_none() .is_none()
{ {
services() services()
.users .users
.add_device_keys(sender_user, sender_device, device_keys)?; .add_device_keys(sender_user, sender_device, device_keys)?;
} }
} }
Ok(upload_keys::v3::Response { Ok(upload_keys::v3::Response {
one_time_key_counts: services() one_time_key_counts: services()
.users .users
.count_one_time_keys(sender_user, sender_device)?, .count_one_time_keys(sender_user, sender_device)?,
}) })
} }
/// # `POST /_matrix/client/r0/keys/query` /// # `POST /_matrix/client/r0/keys/query`
@@ -66,29 +68,30 @@ pub async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<u
/// ///
/// - Always fetches users from other servers over federation /// - Always fetches users from other servers over federation
/// - Gets master keys, self-signing keys, user signing keys and device keys. /// - Gets master keys, self-signing keys, user signing keys and device keys.
/// - The master and self-signing keys contain signatures that the user is /// - The master and self-signing keys contain signatures that the user is allowed to see
/// allowed to see
pub async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_keys::v3::Response> { pub async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let response = get_keys_helper( let response = get_keys_helper(
Some(sender_user), Some(sender_user),
&body.device_keys, &body.device_keys,
|u| u == sender_user, |u| u == sender_user,
true, // Always allow local users to see device names of other local users true, // Always allow local users to see device names of other local users
) )
.await?; .await?;
Ok(response) Ok(response)
} }
/// # `POST /_matrix/client/r0/keys/claim` /// # `POST /_matrix/client/r0/keys/claim`
/// ///
/// Claims one-time keys /// Claims one-time keys
pub async fn claim_keys_route(body: Ruma<claim_keys::v3::Request>) -> Result<claim_keys::v3::Response> { pub async fn claim_keys_route(
let response = claim_keys_helper(&body.one_time_keys).await?; body: Ruma<claim_keys::v3::Request>,
) -> Result<claim_keys::v3::Response> {
let response = claim_keys_helper(&body.one_time_keys).await?;
Ok(response) Ok(response)
} }
/// # `POST /_matrix/client/r0/keys/device_signing/upload` /// # `POST /_matrix/client/r0/keys/device_signing/upload`
@@ -97,426 +100,452 @@ pub async fn claim_keys_route(body: Ruma<claim_keys::v3::Request>) -> Result<cla
/// ///
/// - Requires UIAA to verify password /// - Requires UIAA to verify password
pub async fn upload_signing_keys_route( pub async fn upload_signing_keys_route(
body: Ruma<upload_signing_keys::v3::Request>, body: Ruma<upload_signing_keys::v3::Request>,
) -> Result<upload_signing_keys::v3::Response> { ) -> Result<upload_signing_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
// UIAA // UIAA
let mut uiaainfo = UiaaInfo { let mut uiaainfo = UiaaInfo {
flows: vec![AuthFlow { flows: vec![AuthFlow {
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services() let (worked, uiaainfo) =
.uiaa services()
.try_auth(sender_user, sender_device, auth, &uiaainfo)?; .uiaa
if !worked { .try_auth(sender_user, sender_device, auth, &uiaainfo)?;
return Err(Error::Uiaa(uiaainfo)); if !worked {
} return Err(Error::Uiaa(uiaainfo));
// Success! }
} else if let Some(json) = body.json_body { // Success!
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); } else if let Some(json) = body.json_body {
services() uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
.uiaa services()
.create(sender_user, sender_device, &uiaainfo, &json)?; .uiaa
return Err(Error::Uiaa(uiaainfo)); .create(sender_user, sender_device, &uiaainfo, &json)?;
} else { return Err(Error::Uiaa(uiaainfo));
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); } else {
} return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
if let Some(master_key) = &body.master_key { if let Some(master_key) = &body.master_key {
services().users.add_cross_signing_keys( services().users.add_cross_signing_keys(
sender_user, sender_user,
master_key, master_key,
&body.self_signing_key, &body.self_signing_key,
&body.user_signing_key, &body.user_signing_key,
true, // notify so that other users see the new keys true, // notify so that other users see the new keys
)?; )?;
} }
Ok(upload_signing_keys::v3::Response {}) Ok(upload_signing_keys::v3::Response {})
} }
/// # `POST /_matrix/client/r0/keys/signatures/upload` /// # `POST /_matrix/client/r0/keys/signatures/upload`
/// ///
/// Uploads end-to-end key signatures from the sender user. /// Uploads end-to-end key signatures from the sender user.
pub async fn upload_signatures_route( pub async fn upload_signatures_route(
body: Ruma<upload_signatures::v3::Request>, body: Ruma<upload_signatures::v3::Request>,
) -> Result<upload_signatures::v3::Response> { ) -> Result<upload_signatures::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
for (user_id, keys) in &body.signed_keys { for (user_id, keys) in &body.signed_keys {
for (key_id, key) in keys { for (key_id, key) in keys {
let key = serde_json::to_value(key) let key = serde_json::to_value(key)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid key JSON"))?; .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid key JSON"))?;
for signature in key for signature in key
.get("signatures") .get("signatures")
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Missing signatures field."))? .ok_or(Error::BadRequest(
.get(sender_user.to_string()) ErrorKind::InvalidParam,
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid user in signatures field."))? "Missing signatures field.",
.as_object() ))?
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature."))? .get(sender_user.to_string())
.clone() .ok_or(Error::BadRequest(
{ ErrorKind::InvalidParam,
// Signature validation? "Invalid user in signatures field.",
let signature = ( ))?
signature.0, .as_object()
signature .ok_or(Error::BadRequest(
.1 ErrorKind::InvalidParam,
.as_str() "Invalid signature.",
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature value."))? ))?
.to_owned(), .clone()
); .into_iter()
services() {
.users // Signature validation?
.sign_key(user_id, key_id, signature, sender_user)?; let signature = (
} signature.0,
} signature
} .1
.as_str()
.ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid signature value.",
))?
.to_owned(),
);
services()
.users
.sign_key(user_id, key_id, signature, sender_user)?;
}
}
}
Ok(upload_signatures::v3::Response { Ok(upload_signatures::v3::Response {
failures: BTreeMap::new(), // TODO: integrate failures: BTreeMap::new(), // TODO: integrate
}) })
} }
/// # `POST /_matrix/client/r0/keys/changes` /// # `POST /_matrix/client/r0/keys/changes`
/// ///
/// Gets a list of users who have updated their device identity keys since the /// Gets a list of users who have updated their device identity keys since the previous sync token.
/// previous sync token.
/// ///
/// - TODO: left users /// - TODO: left users
pub async fn get_key_changes_route(body: Ruma<get_key_changes::v3::Request>) -> Result<get_key_changes::v3::Response> { pub async fn get_key_changes_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_key_changes::v3::Request>,
) -> Result<get_key_changes::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut device_list_updates = HashSet::new(); let mut device_list_updates = HashSet::new();
device_list_updates.extend( device_list_updates.extend(
services() services()
.users .users
.keys_changed( .keys_changed(
sender_user.as_str(), sender_user.as_str(),
body.from body.from
.parse() .parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?, .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some( Some(
body.to body.to
.parse() .parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?, .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?,
), ),
) )
.filter_map(Result::ok), .filter_map(|r| r.ok()),
); );
for room_id in services() for room_id in services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(Result::ok) .filter_map(|r| r.ok())
{ {
device_list_updates.extend( device_list_updates.extend(
services() services()
.users .users
.keys_changed( .keys_changed(
room_id.as_ref(), room_id.as_ref(),
body.from body.from.parse().map_err(|_| {
.parse() Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.")
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?, })?,
Some( Some(body.to.parse().map_err(|_| {
body.to Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`.")
.parse() })?),
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?, )
), .filter_map(|r| r.ok()),
) );
.filter_map(Result::ok), }
); Ok(get_key_changes::v3::Response {
} changed: device_list_updates.into_iter().collect(),
Ok(get_key_changes::v3::Response { left: Vec::new(), // TODO
changed: device_list_updates.into_iter().collect(), })
left: Vec::new(), // TODO
})
} }
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>( pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, allowed_signatures: F, sender_user: Option<&UserId>,
include_display_names: bool, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F,
include_display_names: bool,
) -> Result<get_keys::v3::Response> { ) -> Result<get_keys::v3::Response> {
let mut master_keys = BTreeMap::new(); let mut master_keys = BTreeMap::new();
let mut self_signing_keys = BTreeMap::new(); let mut self_signing_keys = BTreeMap::new();
let mut user_signing_keys = BTreeMap::new(); let mut user_signing_keys = BTreeMap::new();
let mut device_keys = BTreeMap::new(); let mut device_keys = BTreeMap::new();
let mut get_over_federation = HashMap::new(); let mut get_over_federation = HashMap::new();
for (user_id, device_ids) in device_keys_input { for (user_id, device_ids) in device_keys_input {
let user_id: &UserId = user_id; let user_id: &UserId = user_id;
if user_id.server_name() != services().globals.server_name() { if user_id.server_name() != services().globals.server_name() {
get_over_federation get_over_federation
.entry(user_id.server_name()) .entry(user_id.server_name())
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push((user_id, device_ids)); .push((user_id, device_ids));
continue; continue;
} }
if device_ids.is_empty() { if device_ids.is_empty() {
let mut container = BTreeMap::new(); let mut container = BTreeMap::new();
for device_id in services().users.all_device_ids(user_id) { for device_id in services().users.all_device_ids(user_id) {
let device_id = device_id?; let device_id = device_id?;
if let Some(mut keys) = services().users.get_device_keys(user_id, &device_id)? { if let Some(mut keys) = services().users.get_device_keys(user_id, &device_id)? {
let metadata = services() let metadata = services()
.users .users
.get_device_metadata(user_id, &device_id)? .get_device_metadata(user_id, &device_id)?
.ok_or_else(|| Error::bad_database("all_device_keys contained nonexistent device."))?; .ok_or_else(|| {
Error::bad_database("all_device_keys contained nonexistent device.")
})?;
add_unsigned_device_display_name(&mut keys, metadata, include_display_names) add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| Error::bad_database("invalid device keys in database"))?; .map_err(|_| Error::bad_database("invalid device keys in database"))?;
container.insert(device_id, keys); container.insert(device_id, keys);
} }
} }
device_keys.insert(user_id.to_owned(), container); device_keys.insert(user_id.to_owned(), container);
} else { } else {
for device_id in device_ids { for device_id in device_ids {
let mut container = BTreeMap::new(); let mut container = BTreeMap::new();
if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? { if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? {
let metadata = services() let metadata = services()
.users .users
.get_device_metadata(user_id, device_id)? .get_device_metadata(user_id, device_id)?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Tried to get keys for nonexistent device.", "Tried to get keys for nonexistent device.",
))?; ))?;
add_unsigned_device_display_name(&mut keys, metadata, include_display_names) add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| Error::bad_database("invalid device keys in database"))?; .map_err(|_| Error::bad_database("invalid device keys in database"))?;
container.insert(device_id.to_owned(), keys); container.insert(device_id.to_owned(), keys);
} }
device_keys.insert(user_id.to_owned(), container); device_keys.insert(user_id.to_owned(), container);
} }
} }
if let Some(master_key) = services() if let Some(master_key) =
.users services()
.get_master_key(sender_user, user_id, &allowed_signatures)? .users
{ .get_master_key(sender_user, user_id, &allowed_signatures)?
master_keys.insert(user_id.to_owned(), master_key); {
} master_keys.insert(user_id.to_owned(), master_key);
if let Some(self_signing_key) = }
services() if let Some(self_signing_key) =
.users services()
.get_self_signing_key(sender_user, user_id, &allowed_signatures)? .users
{ .get_self_signing_key(sender_user, user_id, &allowed_signatures)?
self_signing_keys.insert(user_id.to_owned(), self_signing_key); {
} self_signing_keys.insert(user_id.to_owned(), self_signing_key);
if Some(user_id) == sender_user { }
if let Some(user_signing_key) = services().users.get_user_signing_key(user_id)? { if Some(user_id) == sender_user {
user_signing_keys.insert(user_id.to_owned(), user_signing_key); if let Some(user_signing_key) = services().users.get_user_signing_key(user_id)? {
} user_signing_keys.insert(user_id.to_owned(), user_signing_key);
} }
} }
}
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let back_off = |id| async { let back_off = |id| match services()
match services() .globals
.globals .bad_query_ratelimiter
.bad_query_ratelimiter .write()
.write() .unwrap()
.await .entry(id)
.entry(id) {
{ hash_map::Entry::Vacant(e) => {
hash_map::Entry::Vacant(e) => { e.insert((Instant::now(), 1));
e.insert((Instant::now(), 1)); }
}, hash_map::Entry::Occupied(mut e) => *e.get_mut() = (Instant::now(), e.get().1 + 1),
hash_map::Entry::Occupied(mut e) => *e.get_mut() = (Instant::now(), e.get().1 + 1), };
}
};
let mut futures: FuturesUnordered<_> = get_over_federation let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter() .into_iter()
.map(|(server, vec)| async move { .map(|(server, vec)| async move {
if let Some((time, tries)) = services() if let Some((time, tries)) = services()
.globals .globals
.bad_query_ratelimiter .bad_query_ratelimiter
.read() .read()
.await .unwrap()
.get(server) .get(server)
{ {
// Exponential backoff // Exponential backoff
let mut min_elapsed_duration = Duration::from_secs(5 * 60) * (*tries) * (*tries); let mut min_elapsed_duration = Duration::from_secs(5 * 60) * (*tries) * (*tries);
if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) { if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) {
min_elapsed_duration = Duration::from_secs(60 * 60 * 24); min_elapsed_duration = Duration::from_secs(60 * 60 * 24);
} }
if time.elapsed() < min_elapsed_duration { if time.elapsed() < min_elapsed_duration {
debug!("Backing off query from {:?}", server); debug!("Backing off query from {:?}", server);
return (server, Err(Error::BadServerResponse("bad query, still backing off"))); return (
} server,
} Err(Error::BadServerResponse("bad query, still backing off")),
);
}
}
let mut device_keys_input_fed = BTreeMap::new(); let mut device_keys_input_fed = BTreeMap::new();
for (user_id, keys) in vec { for (user_id, keys) in vec {
device_keys_input_fed.insert(user_id.to_owned(), keys.clone()); device_keys_input_fed.insert(user_id.to_owned(), keys.clone());
} }
( (
server, server,
tokio::time::timeout( tokio::time::timeout(
Duration::from_secs(90), Duration::from_secs(50),
services().sending.send_federation_request( services().sending.send_federation_request(
server, server,
federation::keys::get_keys::v1::Request { federation::keys::get_keys::v1::Request {
device_keys: device_keys_input_fed, device_keys: device_keys_input_fed,
}, },
), ),
) )
.await .await
.map_err(|e| { .map_err(|e| {
error!("get_keys_helper query took too long: {e}"); error!("get_keys_helper query took too long: {}", e);
Error::BadServerResponse("get_keys_helper query took too long") Error::BadServerResponse("get_keys_helper query took too long")
}), }),
) )
}) })
.collect(); .collect();
while let Some((server, response)) = futures.next().await { while let Some((server, response)) = futures.next().await {
if let Ok(Ok(response)) = response { match response {
for (user, masterkey) in response.master_keys { Ok(Ok(response)) => {
let (master_key_id, mut master_key) = services().users.parse_master_key(&user, &masterkey)?; for (user, masterkey) in response.master_keys {
let (master_key_id, mut master_key) =
services().users.parse_master_key(&user, &masterkey)?;
if let Some(our_master_key) = if let Some(our_master_key) = services().users.get_key(
services() &master_key_id,
.users sender_user,
.get_key(&master_key_id, sender_user, &user, &allowed_signatures)? &user,
{ &allowed_signatures,
let (_, our_master_key) = services().users.parse_master_key(&user, &our_master_key)?; )? {
master_key.signatures.extend(our_master_key.signatures); let (_, our_master_key) =
} services().users.parse_master_key(&user, &our_master_key)?;
let json = serde_json::to_value(master_key).expect("to_value always works"); master_key.signatures.extend(our_master_key.signatures);
let raw = serde_json::from_value(json).expect("Raw::from_value always works"); }
services().users.add_cross_signing_keys( let json = serde_json::to_value(master_key).expect("to_value always works");
&user, &raw, &None, &None, let raw = serde_json::from_value(json).expect("Raw::from_value always works");
false, /* Dont notify. A notification would trigger another key request resulting in an services().users.add_cross_signing_keys(
* endless loop */ &user, &raw, &None, &None,
)?; false, // Dont notify. A notification would trigger another key request resulting in an endless loop
master_keys.insert(user, raw); )?;
} master_keys.insert(user, raw);
}
self_signing_keys.extend(response.self_signing_keys); self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys); device_keys.extend(response.device_keys);
} else { }
back_off(server.to_owned()).await; _ => {
failures.insert(server.to_string(), json!({})); back_off(server.to_owned());
} failures.insert(server.to_string(), json!({}));
} }
}
}
Ok(get_keys::v3::Response { Ok(get_keys::v3::Response {
failures, master_keys,
device_keys, self_signing_keys,
master_keys, user_signing_keys,
self_signing_keys, device_keys,
user_signing_keys, failures,
}) })
} }
fn add_unsigned_device_display_name( fn add_unsigned_device_display_name(
keys: &mut Raw<ruma::encryption::DeviceKeys>, metadata: ruma::api::client::device::Device, keys: &mut Raw<ruma::encryption::DeviceKeys>,
include_display_names: bool, metadata: ruma::api::client::device::Device,
include_display_names: bool,
) -> serde_json::Result<()> { ) -> serde_json::Result<()> {
if let Some(display_name) = metadata.display_name { if let Some(display_name) = metadata.display_name {
let mut object = keys.deserialize_as::<serde_json::Map<String, serde_json::Value>>()?; let mut object = keys.deserialize_as::<serde_json::Map<String, serde_json::Value>>()?;
let unsigned = object.entry("unsigned").or_insert_with(|| json!({})); let unsigned = object.entry("unsigned").or_insert_with(|| json!({}));
if let serde_json::Value::Object(unsigned_object) = unsigned { if let serde_json::Value::Object(unsigned_object) = unsigned {
if include_display_names { if include_display_names {
unsigned_object.insert("device_display_name".to_owned(), display_name.into()); unsigned_object.insert("device_display_name".to_owned(), display_name.into());
} else { } else {
unsigned_object.insert( unsigned_object.insert(
"device_display_name".to_owned(), "device_display_name".to_owned(),
Some(metadata.device_id.as_str().to_owned()).into(), Some(metadata.device_id.as_str().to_owned()).into(),
); );
} }
} }
*keys = Raw::from_json(serde_json::value::to_raw_value(&object)?); *keys = Raw::from_json(serde_json::value::to_raw_value(&object)?);
} }
Ok(()) Ok(())
} }
pub(crate) async fn claim_keys_helper( pub(crate) async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>, one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
) -> Result<claim_keys::v3::Response> { ) -> Result<claim_keys::v3::Response> {
let mut one_time_keys = BTreeMap::new(); let mut one_time_keys = BTreeMap::new();
let mut get_over_federation = BTreeMap::new(); let mut get_over_federation = BTreeMap::new();
for (user_id, map) in one_time_keys_input { for (user_id, map) in one_time_keys_input {
if user_id.server_name() != services().globals.server_name() { if user_id.server_name() != services().globals.server_name() {
get_over_federation get_over_federation
.entry(user_id.server_name()) .entry(user_id.server_name())
.or_insert_with(Vec::new) .or_insert_with(Vec::new)
.push((user_id, map)); .push((user_id, map));
} }
let mut container = BTreeMap::new(); let mut container = BTreeMap::new();
for (device_id, key_algorithm) in map { for (device_id, key_algorithm) in map {
if let Some(one_time_keys) = services() if let Some(one_time_keys) =
.users services()
.take_one_time_key(user_id, device_id, key_algorithm)? .users
{ .take_one_time_key(user_id, device_id, key_algorithm)?
let mut c = BTreeMap::new(); {
c.insert(one_time_keys.0, one_time_keys.1); let mut c = BTreeMap::new();
container.insert(device_id.clone(), c); c.insert(one_time_keys.0, one_time_keys.1);
} container.insert(device_id.clone(), c);
} }
one_time_keys.insert(user_id.clone(), container); }
} one_time_keys.insert(user_id.clone(), container);
}
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let mut futures: FuturesUnordered<_> = get_over_federation let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter() .into_iter()
.map(|(server, vec)| async move { .map(|(server, vec)| async move {
let mut one_time_keys_input_fed = BTreeMap::new(); let mut one_time_keys_input_fed = BTreeMap::new();
for (user_id, keys) in vec { for (user_id, keys) in vec {
one_time_keys_input_fed.insert(user_id.clone(), keys.clone()); one_time_keys_input_fed.insert(user_id.clone(), keys.clone());
} }
( (
server, server,
services() services()
.sending .sending
.send_federation_request( .send_federation_request(
server, server,
federation::keys::claim_keys::v1::Request { federation::keys::claim_keys::v1::Request {
one_time_keys: one_time_keys_input_fed, one_time_keys: one_time_keys_input_fed,
}, },
) )
.await, .await,
) )
}) })
.collect(); .collect();
while let Some((server, response)) = futures.next().await { while let Some((server, response)) = futures.next().await {
match response { match response {
Ok(keys) => { Ok(keys) => {
one_time_keys.extend(keys.one_time_keys); one_time_keys.extend(keys.one_time_keys);
}, }
Err(_e) => { Err(_e) => {
failures.insert(server.to_string(), json!({})); failures.insert(server.to_string(), json!({}));
}, }
} }
} }
Ok(claim_keys::v3::Response { Ok(claim_keys::v3::Response {
failures, failures,
one_time_keys, one_time_keys,
}) })
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+268 -241
View File
@@ -1,289 +1,316 @@
use std::{
collections::{BTreeMap, HashSet},
sync::Arc,
};
use ruma::{
api::client::{
error::ErrorKind,
filter::{RoomEventFilter, UrlFilter},
message::{get_message_events, send_message_event},
},
events::{MessageLikeEventType, StateEventType},
RoomId, UserId,
};
use serde_json::{from_str, Value};
use crate::{ use crate::{
service::{pdu::PduBuilder, rooms::timeline::PduCount}, service::{pdu::PduBuilder, rooms::timeline::PduCount},
services, utils, Error, PduEvent, Result, Ruma, services, utils, Error, Result, Ruma,
};
use ruma::{
api::client::{
error::ErrorKind,
message::{get_message_events, send_message_event},
},
events::{StateEventType, TimelineEventType},
};
use serde_json::from_str;
use std::{
collections::{BTreeMap, HashSet},
sync::Arc,
}; };
/// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}` /// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`
/// ///
/// Send a message event into the room. /// Send a message event into the room.
/// ///
/// - Is a NOOP if the txn id was already used before and returns the same event /// - Is a NOOP if the txn id was already used before and returns the same event id again
/// id again
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed
pub async fn send_message_event_route( pub async fn send_message_event_route(
body: Ruma<send_message_event::v3::Request>, body: Ruma<send_message_event::v3::Request>,
) -> Result<send_message_event::v3::Response> { ) -> Result<send_message_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
services() services()
.globals .globals
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.await .unwrap()
.entry(body.room_id.clone()) .entry(body.room_id.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Forbid m.room.encrypted if encryption is disabled // Forbid m.room.encrypted if encryption is disabled
if MessageLikeEventType::RoomEncrypted == body.event_type && !services().globals.allow_encryption() { if TimelineEventType::RoomEncrypted == body.event_type.to_string().into()
return Err(Error::BadRequest(ErrorKind::forbidden(), "Encryption has been disabled")); && !services().globals.allow_encryption()
} {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Encryption has been disabled",
));
}
if body.event_type == MessageLikeEventType::CallInvite // certain event types require certain fields to be valid in request bodies.
&& services().rooms.directory.is_public_room(&body.room_id)? // this helps prevent attempting to handle events that we can't deserialise later so don't waste resources on it.
{ //
return Err(Error::BadRequest( // see https://spec.matrix.org/v1.9/client-server-api/#events-2 for what's required per event type.
ErrorKind::forbidden(), match body.event_type.to_string().into() {
"Room call invites are not allowed in public rooms", TimelineEventType::RoomMessage => {
)); let body_field = body.body.body.get_field::<String>("body");
} let msgtype_field = body.body.body.get_field::<String>("msgtype");
// Check if this is a new transaction id if body_field.is_err() {
if let Some(response) = services() return Err(Error::BadRequest(
.transaction_ids ErrorKind::InvalidParam,
.existing_txnid(sender_user, sender_device, &body.txn_id)? "'body' field in JSON request is invalid",
{ ));
// The client might have sent a txnid of the /sendToDevice endpoint }
// This txnid has no response associated with it
if response.is_empty() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to use txn id already used for an incompatible endpoint.",
));
}
let event_id = utils::string_from_bytes(&response) if msgtype_field.is_err() {
.map_err(|_| Error::bad_database("Invalid txnid bytes in database."))? return Err(Error::BadRequest(
.try_into() ErrorKind::InvalidParam,
.map_err(|_| Error::bad_database("Invalid event id in txnid data."))?; "'msgtype' field in JSON request is invalid",
return Ok(send_message_event::v3::Response { ));
event_id, }
}); }
} TimelineEventType::RoomName => {
let name_field = body.body.body.get_field::<String>("name");
let mut unsigned = BTreeMap::new(); if name_field.is_err() {
unsigned.insert("transaction_id".to_owned(), body.txn_id.to_string().into()); return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"'name' field in JSON request is invalid",
));
}
}
TimelineEventType::RoomTopic => {
let topic_field = body.body.body.get_field::<String>("topic");
let event_id = services() if topic_field.is_err() {
.rooms return Err(Error::BadRequest(
.timeline ErrorKind::InvalidParam,
.build_and_append_pdu( "'topic' field in JSON request is invalid",
PduBuilder { ));
event_type: body.event_type.to_string().into(), }
content: from_str(body.body.body.json().get()) }
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid JSON body."))?, _ => {} // event may be custom/experimental or can be empty don't do anything with it
unsigned: Some(unsigned), };
state_key: None,
redacts: None,
},
sender_user,
&body.room_id,
&state_lock,
)
.await?;
services() // Check if this is a new transaction id
.transaction_ids if let Some(response) =
.add_txnid(sender_user, sender_device, &body.txn_id, event_id.as_bytes())?; services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
{
// The client might have sent a txnid of the /sendToDevice endpoint
// This txnid has no response associated with it
if response.is_empty() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to use txn id already used for an incompatible endpoint.",
));
}
drop(state_lock); let event_id = utils::string_from_bytes(&response)
.map_err(|_| Error::bad_database("Invalid txnid bytes in database."))?
.try_into()
.map_err(|_| Error::bad_database("Invalid event id in txnid data."))?;
return Ok(send_message_event::v3::Response { event_id });
}
Ok(send_message_event::v3::Response::new((*event_id).to_owned())) let mut unsigned = BTreeMap::new();
unsigned.insert("transaction_id".to_owned(), body.txn_id.to_string().into());
let event_id = services()
.rooms
.timeline
.build_and_append_pdu(
PduBuilder {
event_type: body.event_type.to_string().into(),
content: from_str(body.body.body.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid JSON body."))?,
unsigned: Some(unsigned),
state_key: None,
redacts: None,
},
sender_user,
&body.room_id,
&state_lock,
)
.await?;
services().transaction_ids.add_txnid(
sender_user,
sender_device,
&body.txn_id,
event_id.as_bytes(),
)?;
drop(state_lock);
Ok(send_message_event::v3::Response::new(
(*event_id).to_owned(),
))
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/messages` /// # `GET /_matrix/client/r0/rooms/{roomId}/messages`
/// ///
/// Allows paginating through room history. /// Allows paginating through room history.
/// ///
/// - Only works if the user is joined (TODO: always allow, but only show events /// - Only works if the user is joined (TODO: always allow, but only show events where the user was
/// where the user was /// joined, depending on history_visibility)
/// joined, depending on `history_visibility`)
pub async fn get_message_events_route( pub async fn get_message_events_route(
body: Ruma<get_message_events::v3::Request>, body: Ruma<get_message_events::v3::Request>,
) -> Result<get_message_events::v3::Response> { ) -> Result<get_message_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
let from = match body.from.clone() { let from = match body.from.clone() {
Some(from) => PduCount::try_from_string(&from)?, Some(from) => PduCount::try_from_string(&from)?,
None => match body.dir { None => match body.dir {
ruma::api::Direction::Forward => PduCount::min(), ruma::api::Direction::Forward => PduCount::min(),
ruma::api::Direction::Backward => PduCount::max(), ruma::api::Direction::Backward => PduCount::max(),
}, },
}; };
let to = body let to = body
.to .to
.as_ref() .as_ref()
.and_then(|t| PduCount::try_from_string(t).ok()); .and_then(|t| PduCount::try_from_string(t).ok());
services() services().rooms.lazy_loading.lazy_load_confirm_delivery(
.rooms sender_user,
.lazy_loading sender_device,
.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from) &body.room_id,
.await?; from,
)?;
let limit = u64::from(body.limit).min(100) as usize; let limit = u64::from(body.limit).min(100) as usize;
let next_token; let next_token;
let mut resp = get_message_events::v3::Response::new(); let mut resp = get_message_events::v3::Response::new();
let mut lazy_loaded = HashSet::new(); let mut lazy_loaded = HashSet::new();
match body.dir { match body.dir {
ruma::api::Direction::Forward => { ruma::api::Direction::Forward => {
let events_after: Vec<_> = services() let events_after: Vec<_> = services()
.rooms .rooms
.timeline .timeline
.pdus_after(sender_user, &body.room_id, from)? .pdus_after(sender_user, &body.room_id, from)?
.filter_map(Result::ok) // Filter out buggy events .take(limit)
.filter(|(_, pdu)| contains_url_filter(pdu, &body.filter)) .filter_map(|r| r.ok()) // Filter out buggy events
.filter(|(_, pdu)| visibility_filter(pdu, sender_user, &body.room_id)) .filter(|(_, pdu)| {
.take_while(|&(k, _)| Some(k) != to) // Stop at `to` services()
.take(limit) .rooms
.collect(); .state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.collect();
for (_, event) in &events_after { for (_, event) in &events_after {
/* TODO: Remove the not "element_hacks" check when these are resolved: /* TODO: Remove this when these are resolved:
* https://github.com/vector-im/element-android/issues/3417 * https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034 * https://github.com/vector-im/element-web/issues/21034
*/ if !services().rooms.lazy_loading.lazy_load_was_sent_before(
if !cfg!(feature = "element_hacks") sender_user,
&& !services().rooms.lazy_loading.lazy_load_was_sent_before( sender_device,
sender_user, &body.room_id,
sender_device, &event.sender,
&body.room_id, )? {
&event.sender, lazy_loaded.insert(event.sender.clone());
)? { }
lazy_loaded.insert(event.sender.clone()); */
} lazy_loaded.insert(event.sender.clone());
}
lazy_loaded.insert(event.sender.clone()); next_token = events_after.last().map(|(count, _)| count).copied();
}
next_token = events_after.last().map(|(count, _)| count).copied(); let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
let events_after: Vec<_> = events_after resp.start = from.stringify();
.into_iter() resp.end = next_token.map(|count| count.stringify());
.map(|(_, pdu)| pdu.to_room_event()) resp.chunk = events_after;
.collect(); }
ruma::api::Direction::Backward => {
services()
.rooms
.timeline
.backfill_if_required(&body.room_id, from)
.await?;
let events_before: Vec<_> = services()
.rooms
.timeline
.pdus_until(sender_user, &body.room_id, from)?
.take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events
.filter(|(_, pdu)| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.collect();
resp.start = from.stringify(); for (_, event) in &events_before {
resp.end = next_token.map(|count| count.stringify()); /* TODO: Remove this when these are resolved:
resp.chunk = events_after; * https://github.com/vector-im/element-android/issues/3417
}, * https://github.com/vector-im/element-web/issues/21034
ruma::api::Direction::Backward => { if !services().rooms.lazy_loading.lazy_load_was_sent_before(
services() sender_user,
.rooms sender_device,
.timeline &body.room_id,
.backfill_if_required(&body.room_id, from) &event.sender,
.await?; )? {
let events_before: Vec<_> = services() lazy_loaded.insert(event.sender.clone());
.rooms }
.timeline */
.pdus_until(sender_user, &body.room_id, from)? lazy_loaded.insert(event.sender.clone());
.filter_map(Result::ok) // Filter out buggy events }
.filter(|(_, pdu)| contains_url_filter(pdu, &body.filter))
.filter(|(_, pdu)| visibility_filter(pdu, sender_user, &body.room_id))
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.take(limit)
.collect();
for (_, event) in &events_before { next_token = events_before.last().map(|(count, _)| count).copied();
/* TODO: Remove the not "element_hacks" check when these are resolved:
* https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034
*/
if !cfg!(feature = "element_hacks")
&& !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user,
sender_device,
&body.room_id,
&event.sender,
)? {
lazy_loaded.insert(event.sender.clone());
}
lazy_loaded.insert(event.sender.clone()); let events_before: Vec<_> = events_before
} .into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
next_token = events_before.last().map(|(count, _)| count).copied(); resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify());
resp.chunk = events_before;
}
}
let events_before: Vec<_> = events_before resp.state = Vec::new();
.into_iter() for ll_id in &lazy_loaded {
.map(|(_, pdu)| pdu.to_room_event()) if let Some(member_event) = services().rooms.state_accessor.room_state_get(
.collect(); &body.room_id,
&StateEventType::RoomMember,
ll_id.as_str(),
)? {
resp.state.push(member_event.to_state_event());
}
}
resp.start = from.stringify(); // TODO: enable again when we are sure clients can handle it
resp.end = next_token.map(|count| count.stringify()); /*
resp.chunk = events_before; if let Some(next_token) = next_token {
}, services().rooms.lazy_loading.lazy_load_mark_sent(
} sender_user,
sender_device,
&body.room_id,
lazy_loaded,
next_token,
);
}
*/
resp.state = Vec::new(); Ok(resp)
for ll_id in &lazy_loaded {
if let Some(member_event) = services().rooms.state_accessor.room_state_get(
&body.room_id,
&StateEventType::RoomMember,
ll_id.as_str(),
)? {
resp.state.push(member_event.to_state_event());
}
}
// remove the feature check when we are sure clients like element can handle it
if !cfg!(feature = "element_hacks") {
if let Some(next_token) = next_token {
services()
.rooms
.lazy_loading
.lazy_load_mark_sent(sender_user, sender_device, &body.room_id, lazy_loaded, next_token)
.await;
}
}
Ok(resp)
}
fn visibility_filter(pdu: &PduEvent, user_id: &UserId, room_id: &RoomId) -> bool {
services()
.rooms
.state_accessor
.user_can_see_event(user_id, room_id, &pdu.event_id)
.unwrap_or(false)
}
fn contains_url_filter(pdu: &PduEvent, filter: &RoomEventFilter) -> bool {
if filter.url_filter.is_none() {
return true;
}
let content: Value = from_str(pdu.content.get()).unwrap();
match filter.url_filter {
Some(UrlFilter::EventsWithoutUrl) => !content["url"].is_string(),
Some(UrlFilter::EventsWithUrl) => content["url"].is_string(),
None => true,
}
} }
-2
View File
@@ -29,7 +29,6 @@ mod thirdparty;
mod threads; mod threads;
mod to_device; mod to_device;
mod typing; mod typing;
mod unstable;
mod unversioned; mod unversioned;
mod user_directory; mod user_directory;
mod voip; mod voip;
@@ -65,7 +64,6 @@ pub use thirdparty::*;
pub use threads::*; pub use threads::*;
pub use to_device::*; pub use to_device::*;
pub use typing::*; pub use typing::*;
pub use unstable::*;
pub use unversioned::*; pub use unversioned::*;
pub use user_directory::*; pub use user_directory::*;
pub use voip::*; pub use voip::*;
+73 -49
View File
@@ -1,26 +1,38 @@
use std::time::Duration;
use ruma::api::client::{
error::ErrorKind,
presence::{get_presence, set_presence},
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{
error::ErrorKind,
presence::{get_presence, set_presence},
};
use std::time::Duration;
/// # `PUT /_matrix/client/r0/presence/{userId}/status` /// # `PUT /_matrix/client/r0/presence/{userId}/status`
/// ///
/// Sets the presence state of the sender user. /// Sets the presence state of the sender user.
pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result<set_presence::v3::Response> { pub async fn set_presence_route(
if !services().globals.allow_local_presence() { body: Ruma<set_presence::v3::Request>,
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server")); ) -> Result<set_presence::v3::Response> {
} if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Presence is disabled on this server",
));
}
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() for room_id in services().rooms.state_cache.rooms_joined(sender_user) {
.presence let room_id = room_id?;
.set_presence(sender_user, &body.presence, None, None, body.status_msg.clone())?;
Ok(set_presence::v3::Response {}) services().rooms.edus.presence.set_presence(
&room_id,
sender_user,
body.presence.clone(),
None,
None,
body.status_msg.clone(),
)?;
}
Ok(set_presence::v3::Response {})
} }
/// # `GET /_matrix/client/r0/presence/{userId}/status` /// # `GET /_matrix/client/r0/presence/{userId}/status`
@@ -28,41 +40,53 @@ pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result
/// Gets the presence state of the given user. /// Gets the presence state of the given user.
/// ///
/// - Only works if you share a room with the user /// - Only works if you share a room with the user
pub async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result<get_presence::v3::Response> { pub async fn get_presence_route(
if !services().globals.allow_local_presence() { body: Ruma<get_presence::v3::Request>,
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server")); ) -> Result<get_presence::v3::Response> {
} if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Presence is disabled on this server",
));
}
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut presence_event = None; let mut presence_event = None;
for _room_id in services() for room_id in services()
.rooms .rooms
.user .user
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])? .get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
{ {
if let Some(presence) = services().presence.get_presence(sender_user)? { let room_id = room_id?;
presence_event = Some(presence);
break;
}
}
if let Some(presence) = presence_event { if let Some(presence) = services()
Ok(get_presence::v3::Response { .rooms
// TODO: Should ruma just use the presenceeventcontent type here? .edus
status_msg: presence.content.status_msg, .presence
currently_active: presence.content.currently_active, .get_presence(&room_id, sender_user)?
last_active_ago: presence {
.content presence_event = Some(presence);
.last_active_ago break;
.map(|millis| Duration::from_millis(millis.into())), }
presence: presence.content.presence, }
})
} else { if let Some(presence) = presence_event {
Err(Error::BadRequest( Ok(get_presence::v3::Response {
ErrorKind::NotFound, // TODO: Should ruma just use the presenceeventcontent type here?
"Presence state for this user was not found", status_msg: presence.content.status_msg,
)) currently_active: presence.content.currently_active,
} last_active_ago: presence
.content
.last_active_ago
.map(|millis| Duration::from_millis(millis.into())),
presence: presence.content.presence,
})
} else {
Err(Error::BadRequest(
ErrorKind::NotFound,
"Presence state for this user was not found",
))
}
} }
+308 -287
View File
@@ -1,19 +1,19 @@
use std::sync::Arc; use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
profile::{get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name}, profile::{
}, get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name,
federation, },
}, },
events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType}, federation::{self, query::get_profile_information::v1::ProfileField},
presence::PresenceState, },
events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType},
presence::PresenceState,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname` /// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
/// ///
@@ -21,79 +21,87 @@ use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
/// ///
/// - Also makes sure other users receive the update using presence EDUs /// - Also makes sure other users receive the update using presence EDUs
pub async fn set_displayname_route( pub async fn set_displayname_route(
body: Ruma<set_display_name::v3::Request>, body: Ruma<set_display_name::v3::Request>,
) -> Result<set_display_name::v3::Response> { ) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.users .users
.set_displayname(sender_user, body.displayname.clone()) .set_displayname(sender_user, body.displayname.clone())
.await?; .await?;
// Send a new membership event and presence update into all joined rooms // Send a new membership event and presence update into all joined rooms
let all_rooms_joined: Vec<_> = services() let all_rooms_joined: Vec<_> = services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(Result::ok) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
displayname: body.displayname.clone(), displayname: body.displayname.clone(),
join_authorized_via_users_server: None, ..serde_json::from_str(
..serde_json::from_str( services()
services() .rooms
.rooms .state_accessor
.state_accessor .room_state_get(
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())? &room_id,
.ok_or_else(|| { &StateEventType::RoomMember,
Error::bad_database("Tried to send displayname update for user not in the room.") sender_user.as_str(),
})? )?
.content .ok_or_else(|| {
.get(), Error::bad_database(
) "Tried to send displayname update for user not in the \
.map_err(|_| Error::bad_database("Database contains invalid PDU."))? room.",
}) )
.expect("event is valid, we just created it"), })?
unsigned: None, .content
state_key: Some(sender_user.to_string()), .get(),
redacts: None, )
}, .map_err(|_| Error::bad_database("Database contains invalid PDU."))?
room_id, })
)) .expect("event is valid, we just created it"),
}) unsigned: None,
.filter_map(Result::ok) state_key: Some(sender_user.to_string()),
.collect(); redacts: None,
},
room_id,
))
})
.filter_map(|r| r.ok())
.collect();
for (pdu_builder, room_id) in all_rooms_joined { for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
services() services()
.globals .globals
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.await .unwrap()
.entry(room_id.clone()) .entry(room_id.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
_ = services() let _ = services()
.rooms .rooms
.timeline .timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock) .build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await; .await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {
// Presence update // Presence update
services() services()
.presence .rooms
.ping_presence(sender_user, &PresenceState::Online)?; .edus
} .presence
.ping_presence(sender_user, PresenceState::Online)?;
}
Ok(set_display_name::v3::Response {}) Ok(set_display_name::v3::Response {})
} }
/// # `GET /_matrix/client/v3/profile/{userId}/displayname` /// # `GET /_matrix/client/v3/profile/{userId}/displayname`
@@ -103,193 +111,199 @@ pub async fn set_displayname_route(
/// - If user is on another server and we do not have a local copy already /// - If user is on another server and we do not have a local copy already
/// fetch displayname over federation /// fetch displayname over federation
pub async fn get_displayname_route( pub async fn get_displayname_route(
body: Ruma<get_display_name::v3::Request>, body: Ruma<get_display_name::v3::Request>,
) -> Result<get_display_name::v3::Response> { ) -> Result<get_display_name::v3::Response> {
if body.user_id.server_name() != services().globals.server_name() { if (services().users.exists(&body.user_id)?)
// Create and update our local copy of the user && (body.user_id.server_name() != services().globals.server_name())
if let Ok(response) = services() {
.sending let response = services()
.send_federation_request( .sending
body.user_id.server_name(), .send_federation_request(
federation::query::get_profile_information::v1::Request { body.user_id.server_name(),
user_id: body.user_id.clone(), federation::query::get_profile_information::v1::Request {
field: None, // we want the full user's profile to update locally too user_id: body.user_id.clone(),
}, field: Some(ProfileField::DisplayName),
) },
.await )
{ .await?;
if !services().users.exists(&body.user_id)? {
services().users.create(&body.user_id, None)?;
}
services() /*
.users TODO: ignore errors properly?
.set_displayname(&body.user_id, response.displayname.clone()) // Create and update our local copy of the user
.await?; // these are `let _` because it's fine if we can't find these for the user.
services() // also these requests are sent on room join so dead servers will make room joins annoying again
.users let _ = services().users.create(&body.user_id, None);
.set_avatar_url(&body.user_id, response.avatar_url.clone()) let _ = services()
.await?; .users
services() .set_displayname(&body.user_id, response.displayname.clone())
.users .await;
.set_blurhash(&body.user_id, response.blurhash.clone()) let _ = services()
.await?; .users
.set_avatar_url(&body.user_id, response.avatar_url)
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash)
.await;
*/
return Ok(get_display_name::v3::Response { return Ok(get_display_name::v3::Response {
displayname: response.displayname, displayname: response.displayname,
}); });
} }
}
if !services().users.exists(&body.user_id)? { Ok(get_display_name::v3::Response {
// Return 404 if this user doesn't exist and we couldn't fetch it over displayname: services().users.displayname(&body.user_id)?,
// federation })
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
}
Ok(get_display_name::v3::Response {
displayname: services().users.displayname(&body.user_id)?,
})
} }
/// # `PUT /_matrix/client/v3/profile/{userId}/avatar_url` /// # `PUT /_matrix/client/r0/profile/{userId}/avatar_url`
/// ///
/// Updates the `avatar_url` and `blurhash`. /// Updates the avatar_url and blurhash.
/// ///
/// - Also makes sure other users receive the update using presence EDUs /// - Also makes sure other users receive the update using presence EDUs
pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Result<set_avatar_url::v3::Response> { pub async fn set_avatar_url_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<set_avatar_url::v3::Request>,
) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.users .users
.set_avatar_url(sender_user, body.avatar_url.clone()) .set_avatar_url(sender_user, body.avatar_url.clone())
.await?; .await?;
services() services()
.users .users
.set_blurhash(sender_user, body.blurhash.clone()) .set_blurhash(sender_user, body.blurhash.clone())
.await?; .await?;
// Send a new membership event and presence update into all joined rooms // Send a new membership event and presence update into all joined rooms
let all_joined_rooms: Vec<_> = services() let all_joined_rooms: Vec<_> = services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(Result::ok) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomMember, event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent { content: to_raw_value(&RoomMemberEventContent {
avatar_url: body.avatar_url.clone(), avatar_url: body.avatar_url.clone(),
join_authorized_via_users_server: None, ..serde_json::from_str(
..serde_json::from_str( services()
services() .rooms
.rooms .state_accessor
.state_accessor .room_state_get(
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())? &room_id,
.ok_or_else(|| { &StateEventType::RoomMember,
Error::bad_database("Tried to send displayname update for user not in the room.") sender_user.as_str(),
})? )?
.content .ok_or_else(|| {
.get(), Error::bad_database(
) "Tried to send displayname update for user not in the \
.map_err(|_| Error::bad_database("Database contains invalid PDU."))? room.",
}) )
.expect("event is valid, we just created it"), })?
unsigned: None, .content
state_key: Some(sender_user.to_string()), .get(),
redacts: None, )
}, .map_err(|_| Error::bad_database("Database contains invalid PDU."))?
room_id, })
)) .expect("event is valid, we just created it"),
}) unsigned: None,
.filter_map(Result::ok) state_key: Some(sender_user.to_string()),
.collect(); redacts: None,
},
room_id,
))
})
.filter_map(|r| r.ok())
.collect();
for (pdu_builder, room_id) in all_joined_rooms { for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
services() services()
.globals .globals
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.await .unwrap()
.entry(room_id.clone()) .entry(room_id.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
_ = services() let _ = services()
.rooms .rooms
.timeline .timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock) .build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await; .await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {
// Presence update // Presence update
services() services()
.presence .rooms
.ping_presence(sender_user, &PresenceState::Online)?; .edus
} .presence
.ping_presence(sender_user, PresenceState::Online)?;
}
Ok(set_avatar_url::v3::Response {}) Ok(set_avatar_url::v3::Response {})
} }
/// # `GET /_matrix/client/v3/profile/{userId}/avatar_url` /// # `GET /_matrix/client/v3/profile/{userId}/avatar_url`
/// ///
/// Returns the `avatar_url` and `blurhash` of the user. /// Returns the avatar_url and blurhash of the user.
/// ///
/// - If user is on another server and we do not have a local copy already /// - If user is on another server and we do not have a local copy already
/// fetch `avatar_url` and blurhash over federation /// fetch avatar_url and blurhash over federation
pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Result<get_avatar_url::v3::Response> { pub async fn get_avatar_url_route(
if body.user_id.server_name() != services().globals.server_name() { body: Ruma<get_avatar_url::v3::Request>,
// Create and update our local copy of the user ) -> Result<get_avatar_url::v3::Response> {
if let Ok(response) = services() if (services().users.exists(&body.user_id)?)
.sending && (body.user_id.server_name() != services().globals.server_name())
.send_federation_request( {
body.user_id.server_name(), let response = services()
federation::query::get_profile_information::v1::Request { .sending
user_id: body.user_id.clone(), .send_federation_request(
field: None, // we want the full user's profile to update locally as well body.user_id.server_name(),
}, federation::query::get_profile_information::v1::Request {
) user_id: body.user_id.clone(),
.await field: Some(ProfileField::AvatarUrl),
{ },
if !services().users.exists(&body.user_id)? { )
services().users.create(&body.user_id, None)?; .await?;
}
services() /*
.users TODO: ignore errors properly?
.set_displayname(&body.user_id, response.displayname.clone()) // Create and update our local copy of the user
.await?; // these are `let _` because it's fine if we can't find these for the user.
services() // also these requests are sent on room join so dead servers will make room joins annoying again
.users let _ = services().users.create(&body.user_id, None);
.set_avatar_url(&body.user_id, response.avatar_url.clone()) let _ = services()
.await?; .users
services() .set_displayname(&body.user_id, response.displayname)
.users .await;
.set_blurhash(&body.user_id, response.blurhash.clone()) let _ = services()
.await?; .users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await;
*/
return Ok(get_avatar_url::v3::Response { return Ok(get_avatar_url::v3::Response {
avatar_url: response.avatar_url, avatar_url: response.avatar_url,
blurhash: response.blurhash, blurhash: response.blurhash,
}); });
} }
}
if !services().users.exists(&body.user_id)? { Ok(get_avatar_url::v3::Response {
// Return 404 if this user doesn't exist and we couldn't fetch it over avatar_url: services().users.avatar_url(&body.user_id)?,
// federation blurhash: services().users.blurhash(&body.user_id)?,
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); })
}
Ok(get_avatar_url::v3::Response {
avatar_url: services().users.avatar_url(&body.user_id)?,
blurhash: services().users.blurhash(&body.user_id)?,
})
} }
/// # `GET /_matrix/client/v3/profile/{userId}` /// # `GET /_matrix/client/v3/profile/{userId}`
@@ -298,54 +312,61 @@ pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Re
/// ///
/// - If user is on another server and we do not have a local copy already, /// - If user is on another server and we do not have a local copy already,
/// fetch profile over federation. /// fetch profile over federation.
pub async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<get_profile::v3::Response> { pub async fn get_profile_route(
if body.user_id.server_name() != services().globals.server_name() { body: Ruma<get_profile::v3::Request>,
// Create and update our local copy of the user ) -> Result<get_profile::v3::Response> {
if let Ok(response) = services() if (services().users.exists(&body.user_id)?)
.sending && (body.user_id.server_name() != services().globals.server_name())
.send_federation_request( {
body.user_id.server_name(), let response = services()
federation::query::get_profile_information::v1::Request { .sending
user_id: body.user_id.clone(), .send_federation_request(
field: None, body.user_id.server_name(),
}, federation::query::get_profile_information::v1::Request {
) user_id: body.user_id.clone(),
.await field: None,
{ },
if !services().users.exists(&body.user_id)? { )
services().users.create(&body.user_id, None)?; .await?;
}
services() /*
.users TODO: ignore errors properly?
.set_displayname(&body.user_id, response.displayname.clone()) // Create and update our local copy of the user
.await?; // these are `let _` because it's fine if we can't find these for the user.
services() // also these requests are sent on room join so dead servers will make room joins annoying again
.users let _ = services().users.create(&body.user_id, None);
.set_avatar_url(&body.user_id, response.avatar_url.clone()) let _ = services()
.await?; .users
services() .set_displayname(&body.user_id, response.displayname.clone())
.users .await;
.set_blurhash(&body.user_id, response.blurhash.clone()) let _ = services()
.await?; .users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await;
*/
return Ok(get_profile::v3::Response { return Ok(get_profile::v3::Response {
displayname: response.displayname, displayname: response.displayname,
avatar_url: response.avatar_url, avatar_url: response.avatar_url,
blurhash: response.blurhash, blurhash: response.blurhash,
}); });
} }
}
if !services().users.exists(&body.user_id)? { if !services().users.exists(&body.user_id)? {
// Return 404 if this user doesn't exist and we couldn't fetch it over // Return 404 if this user doesn't exist and we couldn't fetch it over federation
// federation return Err(Error::BadRequest(
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); ErrorKind::NotFound,
} "Profile was not found.",
));
}
Ok(get_profile::v3::Response { Ok(get_profile::v3::Response {
avatar_url: services().users.avatar_url(&body.user_id)?, avatar_url: services().users.avatar_url(&body.user_id)?,
blurhash: services().users.blurhash(&body.user_id)?, blurhash: services().users.blurhash(&body.user_id)?,
displayname: services().users.displayname(&body.user_id)?, displayname: services().users.displayname(&body.user_id)?,
}) })
} }
+323 -262
View File
@@ -1,358 +1,417 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
push::{ push::{
delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled, get_pushrules_all, delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled,
set_pusher, set_pushrule, set_pushrule_actions, set_pushrule_enabled, RuleScope, get_pushrules_all, set_pusher, set_pushrule, set_pushrule_actions,
}, set_pushrule_enabled, RuleScope,
}, },
events::{push_rules::PushRulesEvent, GlobalAccountDataEventType}, },
push::{InsertPushRuleError, RemovePushRuleError, Ruleset}, events::{push_rules::PushRulesEvent, GlobalAccountDataEventType},
push::{InsertPushRuleError, RemovePushRuleError},
}; };
use crate::{services, Error, Result, Ruma}; /// # `GET /_matrix/client/r0/pushrules`
/// # `GET /_matrix/client/r0/pushrules/`
/// ///
/// Retrieves the push rules event for this user. /// Retrieves the push rules event for this user.
pub async fn get_pushrules_all_route( pub async fn get_pushrules_all_route(
body: Ruma<get_pushrules_all::v3::Request>, body: Ruma<get_pushrules_all::v3::Request>,
) -> Result<get_pushrules_all::v3::Response> { ) -> Result<get_pushrules_all::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = let event = services()
services() .account_data
.account_data .get(
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
if let Some(event) = event { let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .content;
.content;
Ok(get_pushrules_all::v3::Response { Ok(get_pushrules_all::v3::Response {
global: account_data.global, global: account_data.global,
}) })
} else {
services().account_data.update(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent {
global: Ruleset::server_default(sender_user),
},
})
.expect("to json always works"),
)?;
Ok(get_pushrules_all::v3::Response {
global: Ruleset::server_default(sender_user),
})
}
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Retrieves a single specified push rule for this user. /// Retrieves a single specified push rule for this user.
pub async fn get_pushrule_route(body: Ruma<get_pushrule::v3::Request>) -> Result<get_pushrule::v3::Response> { pub async fn get_pushrule_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_pushrule::v3::Request>,
) -> Result<get_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
let rule = account_data let rule = account_data
.global .global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(Into::into); .map(Into::into);
if let Some(rule) = rule { if let Some(rule) = rule {
Ok(get_pushrule::v3::Response { Ok(get_pushrule::v3::Response { rule })
rule, } else {
}) Err(Error::BadRequest(
} else { ErrorKind::NotFound,
Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")) "Push rule not found.",
} ))
}
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Creates a single specified push rule for this user. /// Creates a single specified push rule for this user.
pub async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) -> Result<set_pushrule::v3::Response> { pub async fn set_pushrule_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<set_pushrule::v3::Request>,
let body = body.body; ) -> Result<set_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body;
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) = if let Err(error) = account_data.content.global.insert(
account_data body.rule.clone(),
.content body.after.as_deref(),
.global body.before.as_deref(),
.insert(body.rule.clone(), body.after.as_deref(), body.before.as_deref()) ) {
{ let err = match error {
let err = match error { InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest(
InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest( ErrorKind::InvalidParam,
ErrorKind::InvalidParam, "Rule IDs starting with a dot are reserved for server-default rules.",
"Rule IDs starting with a dot are reserved for server-default rules.", ),
), InsertPushRuleError::InvalidRuleId => Error::BadRequest(
InsertPushRuleError::InvalidRuleId => { ErrorKind::InvalidParam,
Error::BadRequest(ErrorKind::InvalidParam, "Rule ID containing invalid characters.") "Rule ID containing invalid characters.",
}, ),
InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest( InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Can't place a push rule relatively to a server-default rule.", "Can't place a push rule relatively to a server-default rule.",
), ),
InsertPushRuleError::UnknownRuleId => { InsertPushRuleError::UnknownRuleId => Error::BadRequest(
Error::BadRequest(ErrorKind::NotFound, "The before or after rule could not be found.") ErrorKind::NotFound,
}, "The before or after rule could not be found.",
InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest( ),
ErrorKind::InvalidParam, InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest(
"The before rule has a higher priority than the after rule.", ErrorKind::InvalidParam,
), "The before rule has a higher priority than the after rule.",
_ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."), ),
}; _ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."),
};
return Err(err); return Err(err);
} }
services().account_data.update( services().account_data.update(
None, None,
sender_user, sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(), GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(account_data).expect("to json value always works"), &serde_json::to_value(account_data).expect("to json value always works"),
)?; )?;
Ok(set_pushrule::v3::Response {}) Ok(set_pushrule::v3::Response {})
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
/// ///
/// Gets the actions of a single specified push rule for this user. /// Gets the actions of a single specified push rule for this user.
pub async fn get_pushrule_actions_route( pub async fn get_pushrule_actions_route(
body: Ruma<get_pushrule_actions::v3::Request>, body: Ruma<get_pushrule_actions::v3::Request>,
) -> Result<get_pushrule_actions::v3::Response> { ) -> Result<get_pushrule_actions::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
let global = account_data.global; let global = account_data.global;
let actions = global let actions = global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(|rule| rule.actions().to_owned()) .map(|rule| rule.actions().to_owned())
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
))?;
Ok(get_pushrule_actions::v3::Response { Ok(get_pushrule_actions::v3::Response { actions })
actions,
})
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
/// ///
/// Sets the actions of a single specified push rule for this user. /// Sets the actions of a single specified push rule for this user.
pub async fn set_pushrule_actions_route( pub async fn set_pushrule_actions_route(
body: Ruma<set_pushrule_actions::v3::Request>, body: Ruma<set_pushrule_actions::v3::Request>,
) -> Result<set_pushrule_actions::v3::Response> { ) -> Result<set_pushrule_actions::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data if account_data
.content .content
.global .global
.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone()) .set_actions(body.kind.clone(), &body.rule_id, body.actions.clone())
.is_err() .is_err()
{ {
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); return Err(Error::BadRequest(
} ErrorKind::NotFound,
"Push rule not found.",
));
}
services().account_data.update( services().account_data.update(
None, None,
sender_user, sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(), GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(account_data).expect("to json value always works"), &serde_json::to_value(account_data).expect("to json value always works"),
)?; )?;
Ok(set_pushrule_actions::v3::Response {}) Ok(set_pushrule_actions::v3::Response {})
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled` /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled`
/// ///
/// Gets the enabled status of a single specified push rule for this user. /// Gets the enabled status of a single specified push rule for this user.
pub async fn get_pushrule_enabled_route( pub async fn get_pushrule_enabled_route(
body: Ruma<get_pushrule_enabled::v3::Request>, body: Ruma<get_pushrule_enabled::v3::Request>,
) -> Result<get_pushrule_enabled::v3::Response> { ) -> Result<get_pushrule_enabled::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
let global = account_data.content.global; let global = account_data.content.global;
let enabled = global let enabled = global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(ruma::push::AnyPushRuleRef::enabled) .map(|r| r.enabled())
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
))?;
Ok(get_pushrule_enabled::v3::Response { Ok(get_pushrule_enabled::v3::Response { enabled })
enabled,
})
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled`
/// ///
/// Sets the enabled status of a single specified push rule for this user. /// Sets the enabled status of a single specified push rule for this user.
pub async fn set_pushrule_enabled_route( pub async fn set_pushrule_enabled_route(
body: Ruma<set_pushrule_enabled::v3::Request>, body: Ruma<set_pushrule_enabled::v3::Request>,
) -> Result<set_pushrule_enabled::v3::Response> { ) -> Result<set_pushrule_enabled::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data if account_data
.content .content
.global .global
.set_enabled(body.kind.clone(), &body.rule_id, body.enabled) .set_enabled(body.kind.clone(), &body.rule_id, body.enabled)
.is_err() .is_err()
{ {
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); return Err(Error::BadRequest(
} ErrorKind::NotFound,
"Push rule not found.",
));
}
services().account_data.update( services().account_data.update(
None, None,
sender_user, sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(), GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(account_data).expect("to json value always works"), &serde_json::to_value(account_data).expect("to json value always works"),
)?; )?;
Ok(set_pushrule_enabled::v3::Response {}) Ok(set_pushrule_enabled::v3::Response {})
} }
/// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Deletes a single specified push rule for this user. /// Deletes a single specified push rule for this user.
pub async fn delete_pushrule_route(body: Ruma<delete_pushrule::v3::Request>) -> Result<delete_pushrule::v3::Response> { pub async fn delete_pushrule_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<delete_pushrule::v3::Request>,
) -> Result<delete_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Scopes other than 'global' are not supported.", "Scopes other than 'global' are not supported.",
)); ));
} }
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) = account_data if let Err(error) = account_data
.content .content
.global .global
.remove(body.kind.clone(), &body.rule_id) .remove(body.kind.clone(), &body.rule_id)
{ {
let err = match error { let err = match error {
RemovePushRuleError::ServerDefault => { RemovePushRuleError::ServerDefault => Error::BadRequest(
Error::BadRequest(ErrorKind::InvalidParam, "Cannot delete a server-default pushrule.") ErrorKind::InvalidParam,
}, "Cannot delete a server-default pushrule.",
RemovePushRuleError::NotFound => Error::BadRequest(ErrorKind::NotFound, "Push rule not found."), ),
_ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."), RemovePushRuleError::NotFound => {
}; Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")
}
_ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."),
};
return Err(err); return Err(err);
} }
services().account_data.update( services().account_data.update(
None, None,
sender_user, sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(), GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(account_data).expect("to json value always works"), &serde_json::to_value(account_data).expect("to json value always works"),
)?; )?;
Ok(delete_pushrule::v3::Response {}) Ok(delete_pushrule::v3::Response {})
} }
/// # `GET /_matrix/client/r0/pushers` /// # `GET /_matrix/client/r0/pushers`
/// ///
/// Gets all currently active pushers for the sender user. /// Gets all currently active pushers for the sender user.
pub async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<get_pushers::v3::Response> { pub async fn get_pushers_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_pushers::v3::Request>,
) -> Result<get_pushers::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(get_pushers::v3::Response { Ok(get_pushers::v3::Response {
pushers: services().pusher.get_pushers(sender_user)?, pushers: services().pusher.get_pushers(sender_user)?,
}) })
} }
/// # `POST /_matrix/client/r0/pushers/set` /// # `POST /_matrix/client/r0/pushers/set`
@@ -360,12 +419,14 @@ pub async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<g
/// Adds a pusher for the sender user. /// Adds a pusher for the sender user.
/// ///
/// - TODO: Handle `append` /// - TODO: Handle `append`
pub async fn set_pushers_route(body: Ruma<set_pusher::v3::Request>) -> Result<set_pusher::v3::Response> { pub async fn set_pushers_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<set_pusher::v3::Request>,
) -> Result<set_pusher::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() services()
.pusher .pusher
.set_pusher(sender_user, body.action.clone())?; .set_pusher(sender_user, body.action.clone())?;
Ok(set_pusher::v3::Response::default()) Ok(set_pusher::v3::Response::default())
} }
+156 -147
View File
@@ -1,173 +1,182 @@
use std::collections::BTreeMap;
use ruma::{
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
events::{
receipt::{ReceiptThread, ReceiptType},
RoomAccountDataEventType,
},
MilliSecondsSinceUnixEpoch,
};
use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma}; use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma};
use ruma::{
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
events::{
receipt::{ReceiptThread, ReceiptType},
RoomAccountDataEventType,
},
MilliSecondsSinceUnixEpoch,
};
use std::collections::BTreeMap;
/// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers` /// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers`
/// ///
/// Sets different types of read markers. /// Sets different types of read markers.
/// ///
/// - Updates fully-read account data event to `fully_read` /// - Updates fully-read account data event to `fully_read`
/// - If `read_receipt` is set: Update private marker and public read receipt /// - If `read_receipt` is set: Update private marker and public read receipt EDU
/// EDU pub async fn set_read_marker_route(
pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) -> Result<set_read_marker::v3::Response> { body: Ruma<set_read_marker::v3::Request>,
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); ) -> Result<set_read_marker::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if let Some(fully_read) = &body.fully_read { if let Some(fully_read) = &body.fully_read {
let fully_read_event = ruma::events::fully_read::FullyReadEvent { let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent { content: ruma::events::fully_read::FullyReadEventContent {
event_id: fully_read.clone(), event_id: fully_read.clone(),
}, },
}; };
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
RoomAccountDataEventType::FullyRead, RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"), &serde_json::to_value(fully_read_event).expect("to json value always works"),
)?; )?;
} }
if body.private_read_receipt.is_some() || body.read_receipt.is_some() { if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
services() services()
.rooms .rooms
.user .user
.reset_notification_counts(sender_user, &body.room_id)?; .reset_notification_counts(sender_user, &body.room_id)?;
} }
if let Some(event) = &body.private_read_receipt { if let Some(event) = &body.private_read_receipt {
let count = services() let count = services()
.rooms .rooms
.timeline .timeline
.get_pdu_count(event)? .get_pdu_count(event)?
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Event does not exist."))?; .ok_or(Error::BadRequest(
let count = match count { ErrorKind::InvalidParam,
PduCount::Backfilled(_) => { "Event does not exist.",
return Err(Error::BadRequest( ))?;
ErrorKind::InvalidParam, let count = match count {
"Read receipt is in backfilled timeline", PduCount::Backfilled(_) => {
)) return Err(Error::BadRequest(
}, ErrorKind::InvalidParam,
PduCount::Normal(c) => c, "Read receipt is in backfilled timeline",
}; ))
services() }
.rooms PduCount::Normal(c) => c,
.read_receipt };
.private_read_set(&body.room_id, sender_user, count)?; services()
} .rooms
.edus
.read_receipt
.private_read_set(&body.room_id, sender_user, count)?;
}
if let Some(event) = &body.read_receipt { if let Some(event) = &body.read_receipt {
let mut user_receipts = BTreeMap::new(); let mut user_receipts = BTreeMap::new();
user_receipts.insert( user_receipts.insert(
sender_user.clone(), sender_user.clone(),
ruma::events::receipt::Receipt { ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()), ts: Some(MilliSecondsSinceUnixEpoch::now()),
thread: ReceiptThread::Unthreaded, thread: ReceiptThread::Unthreaded,
}, },
); );
let mut receipts = BTreeMap::new(); let mut receipts = BTreeMap::new();
receipts.insert(ReceiptType::Read, user_receipts); receipts.insert(ReceiptType::Read, user_receipts);
let mut receipt_content = BTreeMap::new(); let mut receipt_content = BTreeMap::new();
receipt_content.insert(event.to_owned(), receipts); receipt_content.insert(event.to_owned(), receipts);
services().rooms.read_receipt.readreceipt_update( services().rooms.edus.read_receipt.readreceipt_update(
sender_user, sender_user,
&body.room_id, &body.room_id,
ruma::events::receipt::ReceiptEvent { ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content), content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(), room_id: body.room_id.clone(),
}, },
)?; )?;
} }
Ok(set_read_marker::v3::Response {}) Ok(set_read_marker::v3::Response {})
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}` /// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`
/// ///
/// Sets private read marker and public read receipt EDU. /// Sets private read marker and public read receipt EDU.
pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Result<create_receipt::v3::Response> { pub async fn create_receipt_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<create_receipt::v3::Request>,
) -> Result<create_receipt::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if matches!( if matches!(
&body.receipt_type, &body.receipt_type,
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
) { ) {
services() services()
.rooms .rooms
.user .user
.reset_notification_counts(sender_user, &body.room_id)?; .reset_notification_counts(sender_user, &body.room_id)?;
} }
match body.receipt_type { match body.receipt_type {
create_receipt::v3::ReceiptType::FullyRead => { create_receipt::v3::ReceiptType::FullyRead => {
let fully_read_event = ruma::events::fully_read::FullyReadEvent { let fully_read_event = ruma::events::fully_read::FullyReadEvent {
content: ruma::events::fully_read::FullyReadEventContent { content: ruma::events::fully_read::FullyReadEventContent {
event_id: body.event_id.clone(), event_id: body.event_id.clone(),
}, },
}; };
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
RoomAccountDataEventType::FullyRead, RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"), &serde_json::to_value(fully_read_event).expect("to json value always works"),
)?; )?;
}, }
create_receipt::v3::ReceiptType::Read => { create_receipt::v3::ReceiptType::Read => {
let mut user_receipts = BTreeMap::new(); let mut user_receipts = BTreeMap::new();
user_receipts.insert( user_receipts.insert(
sender_user.clone(), sender_user.clone(),
ruma::events::receipt::Receipt { ruma::events::receipt::Receipt {
ts: Some(MilliSecondsSinceUnixEpoch::now()), ts: Some(MilliSecondsSinceUnixEpoch::now()),
thread: ReceiptThread::Unthreaded, thread: ReceiptThread::Unthreaded,
}, },
); );
let mut receipts = BTreeMap::new(); let mut receipts = BTreeMap::new();
receipts.insert(ReceiptType::Read, user_receipts); receipts.insert(ReceiptType::Read, user_receipts);
let mut receipt_content = BTreeMap::new(); let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.clone(), receipts); receipt_content.insert(body.event_id.to_owned(), receipts);
services().rooms.read_receipt.readreceipt_update( services().rooms.edus.read_receipt.readreceipt_update(
sender_user, sender_user,
&body.room_id, &body.room_id,
ruma::events::receipt::ReceiptEvent { ruma::events::receipt::ReceiptEvent {
content: ruma::events::receipt::ReceiptEventContent(receipt_content), content: ruma::events::receipt::ReceiptEventContent(receipt_content),
room_id: body.room_id.clone(), room_id: body.room_id.clone(),
}, },
)?; )?;
}, }
create_receipt::v3::ReceiptType::ReadPrivate => { create_receipt::v3::ReceiptType::ReadPrivate => {
let count = services() let count = services()
.rooms .rooms
.timeline .timeline
.get_pdu_count(&body.event_id)? .get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Event does not exist."))?; .ok_or(Error::BadRequest(
let count = match count { ErrorKind::InvalidParam,
PduCount::Backfilled(_) => { "Event does not exist.",
return Err(Error::BadRequest( ))?;
ErrorKind::InvalidParam, let count = match count {
"Read receipt is in backfilled timeline", PduCount::Backfilled(_) => {
)) return Err(Error::BadRequest(
}, ErrorKind::InvalidParam,
PduCount::Normal(c) => c, "Read receipt is in backfilled timeline",
}; ))
services() }
.rooms PduCount::Normal(c) => c,
.read_receipt };
.private_read_set(&body.room_id, sender_user, count)?; services().rooms.edus.read_receipt.private_read_set(
}, &body.room_id,
_ => return Err(Error::bad_database("Unsupported receipt type")), sender_user,
} count,
)?;
}
_ => return Err(Error::bad_database("Unsupported receipt type")),
}
Ok(create_receipt::v3::Response {}) Ok(create_receipt::v3::Response {})
} }
+44 -44
View File
@@ -1,58 +1,58 @@
use std::sync::Arc; use std::sync::Arc;
use ruma::{
api::client::redact::redact_event,
events::{room::redaction::RoomRedactionEventContent, TimelineEventType},
};
use serde_json::value::to_raw_value;
use crate::{service::pdu::PduBuilder, services, Result, Ruma}; use crate::{service::pdu::PduBuilder, services, Result, Ruma};
use ruma::{
api::client::redact::redact_event,
events::{room::redaction::RoomRedactionEventContent, TimelineEventType},
};
use serde_json::value::to_raw_value;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
/// ///
/// Tries to send a redaction event into the room. /// Tries to send a redaction event into the room.
/// ///
/// - TODO: Handle txn id /// - TODO: Handle txn id
pub async fn redact_event_route(body: Ruma<redact_event::v3::Request>) -> Result<redact_event::v3::Response> { pub async fn redact_event_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<redact_event::v3::Request>,
let body = body.body; ) -> Result<redact_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body;
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
services() services()
.globals .globals
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.await .unwrap()
.entry(body.room_id.clone()) .entry(body.room_id.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let event_id = services() let event_id = services()
.rooms .rooms
.timeline .timeline
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomRedaction, event_type: TimelineEventType::RoomRedaction,
content: to_raw_value(&RoomRedactionEventContent { content: to_raw_value(&RoomRedactionEventContent {
redacts: Some(body.event_id.clone()), redacts: Some(body.event_id.clone()),
reason: body.reason.clone(), reason: body.reason.clone(),
}) })
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: None, state_key: None,
redacts: Some(body.event_id.into()), redacts: Some(body.event_id.into()),
}, },
sender_user, sender_user,
&body.room_id, &body.room_id,
&state_lock, &state_lock,
) )
.await?; .await?;
drop(state_lock); drop(state_lock);
let event_id = (*event_id).to_owned(); let event_id = (*event_id).to_owned();
Ok(redact_event::v3::Response { Ok(redact_event::v3::Response { event_id })
event_id,
})
} }
+123 -65
View File
@@ -1,88 +1,146 @@
use ruma::api::client::relations::{ use ruma::api::client::relations::{
get_relating_events, get_relating_events_with_rel_type, get_relating_events_with_rel_type_and_event_type, get_relating_events, get_relating_events_with_rel_type,
get_relating_events_with_rel_type_and_event_type,
}; };
use crate::{services, Result, Ruma}; use crate::{service::rooms::timeline::PduCount, services, Result, Ruma};
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}` /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`
pub async fn get_relating_events_with_rel_type_and_event_type_route( pub async fn get_relating_events_with_rel_type_and_event_type_route(
body: Ruma<get_relating_events_with_rel_type_and_event_type::v1::Request>, body: Ruma<get_relating_events_with_rel_type_and_event_type::v1::Request>,
) -> Result<get_relating_events_with_rel_type_and_event_type::v1::Response> { ) -> Result<get_relating_events_with_rel_type_and_event_type::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let res = services() let from = match body.from.clone() {
.rooms Some(from) => PduCount::try_from_string(&from)?,
.pdu_metadata None => match ruma::api::Direction::Backward {
.paginate_relations_with_filter( // TODO: fix ruma so `body.dir` exists
sender_user, ruma::api::Direction::Forward => PduCount::min(),
&body.room_id, ruma::api::Direction::Backward => PduCount::max(),
&body.event_id, },
&Some(body.event_type.clone()), };
&Some(body.rel_type.clone()),
&body.from,
&body.to,
&body.limit,
body.recurse,
body.dir,
)?;
Ok(get_relating_events_with_rel_type_and_event_type::v1::Response { let to = body
chunk: res.chunk, .to
next_batch: res.next_batch, .as_ref()
prev_batch: res.prev_batch, .and_then(|t| PduCount::try_from_string(t).ok());
recursion_depth: res.recursion_depth,
}) // Use limit or else 10, with maximum 100
let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
Some(body.event_type.clone()),
Some(body.rel_type.clone()),
from,
to,
limit,
)?;
Ok(
get_relating_events_with_rel_type_and_event_type::v1::Response {
chunk: res.chunk,
next_batch: res.next_batch,
prev_batch: res.prev_batch,
},
)
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}` /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}`
pub async fn get_relating_events_with_rel_type_route( pub async fn get_relating_events_with_rel_type_route(
body: Ruma<get_relating_events_with_rel_type::v1::Request>, body: Ruma<get_relating_events_with_rel_type::v1::Request>,
) -> Result<get_relating_events_with_rel_type::v1::Response> { ) -> Result<get_relating_events_with_rel_type::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let res = services() let from = match body.from.clone() {
.rooms Some(from) => PduCount::try_from_string(&from)?,
.pdu_metadata None => match ruma::api::Direction::Backward {
.paginate_relations_with_filter( // TODO: fix ruma so `body.dir` exists
sender_user, ruma::api::Direction::Forward => PduCount::min(),
&body.room_id, ruma::api::Direction::Backward => PduCount::max(),
&body.event_id, },
&None, };
&Some(body.rel_type.clone()),
&body.from,
&body.to,
&body.limit,
body.recurse,
body.dir,
)?;
Ok(get_relating_events_with_rel_type::v1::Response { let to = body
chunk: res.chunk, .to
next_batch: res.next_batch, .as_ref()
prev_batch: res.prev_batch, .and_then(|t| PduCount::try_from_string(t).ok());
recursion_depth: res.recursion_depth,
}) // Use limit or else 10, with maximum 100
let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
None,
Some(body.rel_type.clone()),
from,
to,
limit,
)?;
Ok(get_relating_events_with_rel_type::v1::Response {
chunk: res.chunk,
next_batch: res.next_batch,
prev_batch: res.prev_batch,
})
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}` /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}`
pub async fn get_relating_events_route( pub async fn get_relating_events_route(
body: Ruma<get_relating_events::v1::Request>, body: Ruma<get_relating_events::v1::Request>,
) -> Result<get_relating_events::v1::Response> { ) -> Result<get_relating_events::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services() let from = match body.from.clone() {
.rooms Some(from) => PduCount::try_from_string(&from)?,
.pdu_metadata None => match ruma::api::Direction::Backward {
.paginate_relations_with_filter( // TODO: fix ruma so `body.dir` exists
sender_user, ruma::api::Direction::Forward => PduCount::min(),
&body.room_id, ruma::api::Direction::Backward => PduCount::max(),
&body.event_id, },
&None, };
&None,
&body.from, let to = body
&body.to, .to
&body.limit, .as_ref()
body.recurse, .and_then(|t| PduCount::try_from_string(t).ok());
body.dir,
) // Use limit or else 10, with maximum 100
let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
None,
None,
from,
to,
limit,
)
} }
+92 -85
View File
@@ -1,111 +1,118 @@
use std::time::Duration; use std::time::Duration;
use crate::{services, utils::HtmlEscape, Error, Result, Ruma};
use rand::Rng; use rand::Rng;
use ruma::{ use ruma::{
api::client::{error::ErrorKind, room::report_content}, api::client::{error::ErrorKind, room::report_content},
events::room::message, events::room::message,
int, int,
}; };
use tokio::time::sleep; use tokio::time::sleep;
use tracing::{debug, info}; use tracing::{debug, info};
use crate::{services, utils::HtmlEscape, Error, Result, Ruma};
/// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}` /// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}`
/// ///
/// Reports an inappropriate event to homeserver admins /// Reports an inappropriate event to homeserver admins
pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Result<report_content::v3::Response> { ///
// user authentication pub async fn report_event_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<report_content::v3::Request>,
) -> Result<report_content::v3::Response> {
// user authentication
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
info!("Received /report request by user {}", sender_user); info!("Received /report request by user {}", sender_user);
// check if we know about the reported event ID or if it's invalid // check if we know about the reported event ID or if it's invalid
let Some(pdu) = services().rooms.timeline.get_pdu(&body.event_id)? else { let pdu = match services().rooms.timeline.get_pdu(&body.event_id)? {
return Err(Error::BadRequest( Some(pdu) => pdu,
ErrorKind::NotFound, _ => {
"Event ID is not known to us or Event ID is invalid", return Err(Error::BadRequest(
)); ErrorKind::NotFound,
}; "Event ID is not known to us or Event ID is invalid",
))
}
};
// check if the room ID from the URI matches the PDU's room ID // check if the room ID from the URI matches the PDU's room ID
if body.room_id != pdu.room_id { if body.room_id != pdu.room_id {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"Event ID does not belong to the reported room", "Event ID does not belong to the reported room",
)); ));
} }
// check if reporting user is in the reporting room // check if reporting user is in the reporting room
if !services() if !services()
.rooms .rooms
.state_cache .state_cache
.room_members(&pdu.room_id) .room_members(&pdu.room_id)
.filter_map(Result::ok) .filter_map(|r| r.ok())
.any(|user_id| user_id == *sender_user) .any(|user_id| user_id == *sender_user)
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"You are not in the room you are reporting.", "You are not in the room you are reporting.",
)); ));
} }
// check if score is in valid range // check if score is in valid range
if let Some(true) = body.score.map(|s| s > int!(0) || s < int!(-100)) { if let Some(true) = body.score.map(|s| s > int!(0) || s < int!(-100)) {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Invalid score, must be within 0 to -100", "Invalid score, must be within 0 to -100",
)); ));
}; };
// check if report reasoning is less than or equal to 750 characters // check if report reasoning is less than or equal to 750 characters
if let Some(true) = body.reason.clone().map(|s| s.chars().count() >= 750) { if let Some(true) = body.reason.clone().map(|s| s.chars().count() >= 750) {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Reason too long, should be 750 characters or fewer", "Reason too long, should be 750 characters or fewer",
)); ));
}; };
// send admin room message that we received the report with an @room ping for // send admin room message that we received the report with an @room ping for urgency
// urgency services()
services() .admin
.admin .send_message(message::RoomMessageEventContent::text_html(
.send_message(message::RoomMessageEventContent::text_html( format!(
format!( "@room Report received from: {}\n\n\
"@room Report received from: {}\n\nEvent ID: {}\nRoom ID: {}\nSent By: {}\n\nReport Score: {}\nReport \ Event ID: {}\n\
Reason: {}", Room ID: {}\n\
sender_user.to_owned(), Sent By: {}\n\n\
pdu.event_id, Report Score: {}\n\
pdu.room_id, Report Reason: {}",
pdu.sender.clone(), sender_user.to_owned(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), pdu.event_id,
body.reason.as_deref().unwrap_or("") pdu.room_id,
), pdu.sender.to_owned(),
format!( body.score.unwrap_or(ruma::Int::from(0)),
"<details><summary>@room Report received from: <a href=\"https://matrix.to/#/{0}\">{0}\ body.reason.as_deref().unwrap_or("")
),
format!(
"<details><summary>@room Report received from: <a href=\"https://matrix.to/#/{0}\">{0}\
</a></summary><ul><li>Event Info<ul><li>Event ID: <code>{1}</code>\ </a></summary><ul><li>Event Info<ul><li>Event ID: <code>{1}</code>\
<a href=\"https://matrix.to/#/{2}/{1}\">🔗</a></li><li>Room ID: <code>{2}</code>\ <a href=\"https://matrix.to/#/{2}/{1}\">🔗</a></li><li>Room ID: <code>{2}</code>\
</li><li>Sent By: <a href=\"https://matrix.to/#/{3}\">{3}</a></li></ul></li><li>\ </li><li>Sent By: <a href=\"https://matrix.to/#/{3}\">{3}</a></li></ul></li><li>\
Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\ Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\
</ul></details>", </ul></details>",
sender_user.to_owned(), sender_user.to_owned(),
pdu.event_id.clone(), pdu.event_id.to_owned(),
pdu.room_id.clone(), pdu.room_id.to_owned(),
pdu.sender.clone(), pdu.sender.to_owned(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), body.score.unwrap_or(ruma::Int::from(0)),
HtmlEscape(body.reason.as_deref().unwrap_or("")) HtmlEscape(body.reason.as_deref().unwrap_or(""))
), ),
)); ));
// even though this is kinda security by obscurity, let's still make a small // even though this is kinda security by obscurity, let's still make a small random delay sending a successful response
// random delay sending a successful response per spec suggestion regarding // per spec suggestion regarding enumerating for potential events existing in our server.
// enumerating for potential events existing in our server. let time_to_wait = rand::thread_rng().gen_range(8..21);
let time_to_wait = rand::thread_rng().gen_range(8..21); debug!(
debug!( "Got successful /report request, waiting {} seconds before sending successful response.",
"Got successful /report request, waiting {} seconds before sending successful response.", time_to_wait
time_to_wait );
); sleep(Duration::from_secs(time_to_wait)).await;
sleep(Duration::from_secs(time_to_wait)).await;
Ok(report_content::v3::Response {}) Ok(report_content::v3::Response {})
} }
File diff suppressed because it is too large Load Diff
+120 -164
View File
@@ -1,182 +1,138 @@
use std::collections::BTreeMap;
use ruma::{
api::client::{
error::ErrorKind,
search::search_events::{
self,
v3::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult},
},
},
events::AnyStateEvent,
serde::Raw,
OwnedRoomId,
};
use tracing::debug;
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{
error::ErrorKind,
search::search_events::{
self,
v3::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult},
},
};
use std::collections::BTreeMap;
/// # `POST /_matrix/client/r0/search` /// # `POST /_matrix/client/r0/search`
/// ///
/// Searches rooms for messages. /// Searches rooms for messages.
/// ///
/// - Only works if the user is currently joined to the room (TODO: Respect /// - Only works if the user is currently joined to the room (TODO: Respect history visibility)
/// history visibility) pub async fn search_events_route(
pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Result<search_events::v3::Response> { body: Ruma<search_events::v3::Request>,
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); ) -> Result<search_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let search_criteria = body.search_categories.room_events.as_ref().unwrap(); let search_criteria = body.search_categories.room_events.as_ref().unwrap();
let filter = &search_criteria.filter; let filter = &search_criteria.filter;
let include_state = &search_criteria.include_state;
let room_ids = filter.rooms.clone().unwrap_or_else(|| { let room_ids = filter.rooms.clone().unwrap_or_else(|| {
services() services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(Result::ok) .filter_map(|r| r.ok())
.collect() .collect()
}); });
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = filter.limit.map_or(10, u64::from).min(100) as usize; let limit = filter.limit.map_or(10, u64::from).min(100) as usize;
let mut room_states: BTreeMap<OwnedRoomId, Vec<Raw<AnyStateEvent>>> = BTreeMap::new(); let mut searches = Vec::new();
if include_state.is_some_and(|include_state| include_state) { for room_id in room_ids {
for room_id in &room_ids { if !services()
if !services() .rooms
.rooms .state_cache
.state_cache .is_joined(sender_user, &room_id)?
.is_joined(sender_user, room_id)? {
{ return Err(Error::BadRequest(
return Err(Error::BadRequest( ErrorKind::Forbidden,
ErrorKind::forbidden(), "You don't have permission to view this room.",
"You don't have permission to view this room.", ));
)); }
}
// check if sender_user can see state events if let Some(search) = services()
if services() .rooms
.rooms .search
.state_accessor .search_pdus(&room_id, &search_criteria.search_term)?
.user_can_see_state_events(sender_user, room_id)? {
{ searches.push(search.0.peekable());
let room_state = services() }
.rooms }
.state_accessor
.room_state_full(room_id)
.await?
.values()
.map(|pdu| pdu.to_state_event())
.collect::<Vec<_>>();
debug!("Room state: {:?}", room_state); let skip = match body.next_batch.as_ref().map(|s| s.parse()) {
Some(Ok(s)) => s,
Some(Err(_)) => {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid next_batch token.",
))
}
None => 0, // Default to the start
};
room_states.insert(room_id.clone(), room_state); let mut results = Vec::new();
} else { for _ in 0..skip + limit {
return Err(Error::BadRequest( if let Some(s) = searches
ErrorKind::forbidden(), .iter_mut()
"You don't have permission to view this room.", .map(|s| (s.peek().cloned(), s))
)); .max_by_key(|(peek, _)| peek.clone())
} .and_then(|(_, i)| i.next())
} {
} results.push(s);
}
}
let mut searches = Vec::new(); let results: Vec<_> = results
.iter()
.filter_map(|result| {
services()
.rooms
.timeline
.get_pdu_from_id(result)
.ok()?
.filter(|pdu| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &pdu.room_id, &pdu.event_id)
.unwrap_or(false)
})
.map(|pdu| pdu.to_room_event())
})
.map(|result| {
Ok::<_, Error>(SearchResult {
context: EventContextResult {
end: None,
events_after: Vec::new(),
events_before: Vec::new(),
profile_info: BTreeMap::new(),
start: None,
},
rank: None,
result: Some(result),
})
})
.filter_map(|r| r.ok())
.skip(skip)
.take(limit)
.collect();
for room_id in &room_ids { let next_batch = if results.len() < limit {
if !services() None
.rooms } else {
.state_cache Some((skip + limit).to_string())
.is_joined(sender_user, room_id)? };
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"You don't have permission to view this room.",
));
}
if let Some(search) = services() Ok(search_events::v3::Response::new(ResultCategories {
.rooms room_events: ResultRoomEvents {
.search count: Some((results.len() as u32).into()), // TODO: set this to none. Element shouldn't depend on it
.search_pdus(room_id, &search_criteria.search_term)? groups: BTreeMap::new(), // TODO
{ next_batch,
searches.push(search.0.peekable()); results,
} state: BTreeMap::new(), // TODO
} highlights: search_criteria
.search_term
let skip = match body.next_batch.as_ref().map(|s| s.parse()) { .split_terminator(|c: char| !c.is_alphanumeric())
Some(Ok(s)) => s, .map(str::to_lowercase)
Some(Err(_)) => return Err(Error::BadRequest(ErrorKind::InvalidParam, "Invalid next_batch token.")), .collect(),
None => 0, // Default to the start },
}; }))
let mut results = Vec::new();
for _ in 0..skip + limit {
if let Some(s) = searches
.iter_mut()
.map(|s| (s.peek().cloned(), s))
.max_by_key(|(peek, _)| peek.clone())
.and_then(|(_, i)| i.next())
{
results.push(s);
}
}
let results: Vec<_> = results
.iter()
.filter_map(|result| {
services()
.rooms
.timeline
.get_pdu_from_id(result)
.ok()?
.filter(|pdu| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &pdu.room_id, &pdu.event_id)
.unwrap_or(false)
})
.map(|pdu| pdu.to_room_event())
})
.map(|result| {
Ok::<_, Error>(SearchResult {
context: EventContextResult {
end: None,
events_after: Vec::new(),
events_before: Vec::new(),
profile_info: BTreeMap::new(),
start: None,
},
rank: None,
result: Some(result),
})
})
.filter_map(Result::ok)
.skip(skip)
.take(limit)
.collect();
let next_batch = if results.len() < limit {
None
} else {
Some((skip + limit).to_string())
};
Ok(search_events::v3::Response::new(ResultCategories {
room_events: ResultRoomEvents {
count: Some((results.len() as u32).into()),
groups: BTreeMap::new(), // TODO
next_batch,
results,
state: room_states,
highlights: search_criteria
.search_term
.split_terminator(|c: char| !c.is_alphanumeric())
.map(str::to_lowercase)
.collect(),
},
}))
} }
+220 -207
View File
@@ -1,229 +1,243 @@
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
use argon2::{PasswordHash, PasswordVerifier}; use argon2::{PasswordHash, PasswordVerifier};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
session::{ session::{
get_login_types::{ get_login_types,
self, login::{
v3::{ApplicationServiceLoginType, PasswordLoginType}, self,
}, v3::{DiscoveryInfo, HomeserverInfo},
login::{ },
self, logout, logout_all,
v3::{DiscoveryInfo, HomeserverInfo}, },
}, uiaa::UserIdentifier,
logout, logout_all, },
}, UserId,
uiaa::UserIdentifier,
},
UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Claims { struct Claims {
sub: String, sub: String,
//exp: usize, //exp: usize,
} }
/// # `GET /_matrix/client/v3/login` /// # `GET /_matrix/client/v3/login`
/// ///
/// Get the supported login types of this server. One of these should be used as /// Get the supported login types of this server. One of these should be used as the `type` field
/// the `type` field when logging in. /// when logging in.
pub async fn get_login_types_route(_body: Ruma<get_login_types::v3::Request>) -> Result<get_login_types::v3::Response> { pub async fn get_login_types_route(
Ok(get_login_types::v3::Response::new(vec![ _body: Ruma<get_login_types::v3::Request>,
get_login_types::v3::LoginType::Password(PasswordLoginType::default()), ) -> Result<get_login_types::v3::Response> {
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), Ok(get_login_types::v3::Response::new(vec![
])) get_login_types::v3::LoginType::Password(Default::default()),
get_login_types::v3::LoginType::ApplicationService(Default::default()),
]))
} }
/// # `POST /_matrix/client/v3/login` /// # `POST /_matrix/client/v3/login`
/// ///
/// Authenticates the user and returns an access token it can use in subsequent /// Authenticates the user and returns an access token it can use in subsequent requests.
/// requests.
/// ///
/// - The user needs to authenticate using their password (or if enabled using a /// - The user needs to authenticate using their password (or if enabled using a json web token)
/// json web token)
/// - If `device_id` is known: invalidates old access token of that device /// - If `device_id` is known: invalidates old access token of that device
/// - If `device_id` is unknown: creates a new device /// - If `device_id` is unknown: creates a new device
/// - Returns access token that is associated with the user and device /// - Returns access token that is associated with the user and device
/// ///
/// Note: You can use [`GET /// Note: You can use [`GET /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// supported login types. /// supported login types.
pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Response> { pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Response> {
// Validate login method // Validate login method
// TODO: Other login methods // TODO: Other login methods
let user_id = match &body.login_info { let user_id = match &body.login_info {
#[allow(deprecated)] #[allow(deprecated)]
login::v3::LoginInfo::Password(login::v3::Password { login::v3::LoginInfo::Password(login::v3::Password {
identifier, identifier,
password, password,
user, user,
.. ..
}) => { }) => {
debug!("Got password login type"); debug!("Got password login type");
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name()) debug!("Using username from identifier field");
} else if let Some(user) = user { user_id.to_lowercase()
UserId::parse(user) } else if let Some(user_id) = user {
} else { warn!("User \"{}\" is attempting to login with the deprecated \"user\" field at \"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is destined to be removed in a future Matrix release.", user_id);
warn!("Bad login type: {:?}", &body.login_info); user_id.to_lowercase()
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type.")); } else {
} warn!("Bad login type: {:?}", &body.login_info);
.map_err(|e| { return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
warn!("Failed to parse username from user logging in: {e}"); };
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
if services().appservice.is_exclusive_user_id(&user_id).await { let user_id =
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice.")); UserId::parse_with_server_name(username, services().globals.server_name())
} .map_err(|e| {
warn!("Failed to parse username from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
let hash = services() let hash = services()
.users .users
.password_hash(&user_id)? .password_hash(&user_id)?
.ok_or(Error::BadRequest(ErrorKind::forbidden(), "Wrong username or password."))?; .ok_or(Error::BadRequest(
ErrorKind::Forbidden,
"Wrong username or password.",
))?;
if hash.is_empty() { if hash.is_empty() {
return Err(Error::BadRequest(ErrorKind::UserDeactivated, "The user has been deactivated")); return Err(Error::BadRequest(
} ErrorKind::UserDeactivated,
"The user has been deactivated",
));
}
let Ok(parsed_hash) = PasswordHash::new(&hash) else { let Ok(parsed_hash) = PasswordHash::new(&hash) else {
error!("error while hashing user {}", user_id); error!("error while hashing user {}", user_id);
return Err(Error::BadServerResponse("could not hash")); return Err(Error::BadServerResponse("could not hash"));
}; };
let hash_matches = services() let hash_matches = services()
.globals .globals
.argon .argon
.verify_password(password.as_bytes(), &parsed_hash) .verify_password(password.as_bytes(), &parsed_hash)
.is_ok(); .is_ok();
if !hash_matches { if !hash_matches {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Wrong username or password.")); return Err(Error::BadRequest(
} ErrorKind::Forbidden,
"Wrong username or password.",
));
}
user_id user_id
}, }
login::v3::LoginInfo::Token(login::v3::Token { login::v3::LoginInfo::Token(login::v3::Token { token }) => {
token, debug!("Got token login type");
}) => { if let Some(jwt_decoding_key) = services().globals.jwt_decoding_key() {
debug!("Got token login type"); let token = jsonwebtoken::decode::<Claims>(
if let Some(jwt_decoding_key) = services().globals.jwt_decoding_key() { token,
let token = jwt_decoding_key,
jsonwebtoken::decode::<Claims>(token, jwt_decoding_key, &jsonwebtoken::Validation::default()) &jsonwebtoken::Validation::default(),
.map_err(|e| { )
warn!("Failed to parse JWT token from user logging in: {e}"); .map_err(|e| {
Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.") warn!("Failed to parse JWT token from user logging in: {}", e);
})?; Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.")
})?;
let username = token.claims.sub.to_lowercase(); let username = token.claims.sub.to_lowercase();
let user_id = UserId::parse_with_server_name(username, services().globals.server_name()).map_err(
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| { |e| {
warn!("Failed to parse username from user logging in: {e}"); warn!("Failed to parse username from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?; },
)?
} else {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Token login is not supported (server has no jwt decoding key).",
));
}
}
#[allow(deprecated)]
login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier,
user,
}) => {
debug!("Got appservice login type");
if !body.from_appservice {
info!("User tried logging in as an appservice, but request body is not from a known/registered appservice");
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Forbidden login type.",
));
};
let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
user_id.to_lowercase()
} else if let Some(user_id) = user {
warn!("Appservice \"{}\" is attempting to login with the deprecated \"user\" field at \"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is destined to be removed in a future Matrix release.", user_id);
user_id.to_lowercase()
} else {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
};
if services().appservice.is_exclusive_user_id(&user_id).await { UserId::parse_with_server_name(username, services().globals.server_name()).map_err(
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice.")); |e| {
} warn!("Failed to parse username from appservice logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
},
)?
}
_ => {
warn!("Unsupported or unknown login type: {:?}", &body.login_info);
debug!("JSON body: {:?}", &body.json_body);
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Unsupported or unknown login type.",
));
}
};
user_id // Generate new device id if the user didn't specify one
} else { let device_id = body
return Err(Error::BadRequest( .device_id
ErrorKind::Unknown, .clone()
"Token login is not supported (server has no jwt decoding key).", .unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
));
}
},
#[allow(deprecated)]
login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier,
user,
}) => {
debug!("Got appservice login type");
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
} else if let Some(user) = user {
UserId::parse(user)
} else {
warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
}
.map_err(|e| {
warn!("Failed to parse username from appservice logging in: {e}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
if let Some(ref info) = body.appservice_info { // Generate a new token for the device
if !info.is_user_match(&user_id) { let token = utils::random_string(TOKEN_LENGTH);
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace."));
}
} else {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
}
user_id // Determine if device_id was provided and exists in the db for this user
}, let device_exists = body.device_id.as_ref().map_or(false, |device_id| {
_ => { services()
warn!("Unsupported or unknown login type: {:?}", &body.login_info); .users
debug!("JSON body: {:?}", &body.json_body); .all_device_ids(&user_id)
return Err(Error::BadRequest(ErrorKind::Unknown, "Unsupported or unknown login type.")); .any(|x| x.as_ref().map_or(false, |v| v == device_id))
}, });
};
// Generate new device id if the user didn't specify one if device_exists {
let device_id = body services().users.set_token(&user_id, &device_id, &token)?;
.device_id } else {
.clone() services().users.create_device(
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into()); &user_id,
&device_id,
&token,
body.initial_device_display_name.clone(),
)?;
}
// Generate a new token for the device // send client well-known if specified so the client knows to reconfigure itself
let token = utils::random_string(TOKEN_LENGTH); let client_discovery_info = DiscoveryInfo::new(HomeserverInfo::new(
services()
.globals
.well_known_client()
.to_owned()
.unwrap_or("".to_owned()),
));
// Determine if device_id was provided and exists in the db for this user info!("{} logged in", user_id);
let device_exists = body.device_id.as_ref().map_or(false, |device_id| {
services()
.users
.all_device_ids(&user_id)
.any(|x| x.as_ref().map_or(false, |v| v == device_id))
});
if device_exists { // home_server is deprecated but apparently must still be sent despite it being deprecated over 6 years ago.
services().users.set_token(&user_id, &device_id, &token)?; // initially i thought this macro was unnecessary, but ruma uses this same macro for the same reason so...
} else { #[allow(deprecated)]
services() Ok(login::v3::Response {
.users user_id,
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?; access_token: token,
} device_id,
well_known: {
// send client well-known if specified so the client knows to reconfigure itself if client_discovery_info.homeserver.base_url.as_str() == "" {
let client_discovery_info: Option<DiscoveryInfo> = services() None
.globals } else {
.well_known_client() Some(client_discovery_info)
.as_ref() }
.map(|server| DiscoveryInfo::new(HomeserverInfo::new(server.to_string()))); },
expires_in: None,
info!("{user_id} logged in"); home_server: Some(services().globals.server_name().to_owned()),
refresh_token: None,
// home_server is deprecated but apparently must still be sent despite it being })
// deprecated over 6 years ago. initially i thought this macro was unnecessary,
// but ruma uses this same macro for the same reason so...
#[allow(deprecated)]
Ok(login::v3::Response {
user_id,
access_token: token,
device_id,
well_known: client_discovery_info,
expires_in: None,
home_server: Some(services().globals.server_name().to_owned()),
refresh_token: None,
})
} }
/// # `POST /_matrix/client/v3/logout` /// # `POST /_matrix/client/v3/logout`
@@ -231,20 +245,19 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
/// Log out the current device. /// Log out the current device.
/// ///
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3::Response> { pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
services().users.remove_device(sender_user, sender_device)?; services().users.remove_device(sender_user, sender_device)?;
// send device list update for user after logout // send device list update for user after logout
services().users.mark_device_key_update(sender_user)?; services().users.mark_device_key_update(sender_user)?;
Ok(logout::v3::Response::new()) Ok(logout::v3::Response::new())
} }
/// # `POST /_matrix/client/r0/logout/all` /// # `POST /_matrix/client/r0/logout/all`
@@ -252,23 +265,23 @@ pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3:
/// Log out all devices of this user. /// Log out all devices of this user.
/// ///
/// - Invalidates all access tokens /// - Invalidates all access tokens
/// - Deletes all device metadata (device id, device display name, last seen ip, /// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets all to-device events /// - Forgets all to-device events
/// - Triggers device list updates /// - Triggers device list updates
/// ///
/// Note: This is equivalent to calling [`GET /// Note: This is equivalent to calling [`GET /_matrix/client/r0/logout`](fn.logout_route.html)
/// /_matrix/client/r0/logout`](fn.logout_route.html) from each device of this /// from each device of this user.
/// user. pub async fn logout_all_route(
pub async fn logout_all_route(body: Ruma<logout_all::v3::Request>) -> Result<logout_all::v3::Response> { body: Ruma<logout_all::v3::Request>,
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); ) -> Result<logout_all::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
for device_id in services().users.all_device_ids(sender_user).flatten() { for device_id in services().users.all_device_ids(sender_user).flatten() {
services().users.remove_device(sender_user, &device_id)?; services().users.remove_device(sender_user, &device_id)?;
} }
// send device list update for user after logout // send device list update for user after logout
services().users.mark_device_key_update(sender_user)?; services().users.mark_device_key_update(sender_user)?;
Ok(logout_all::v3::Response::new()) Ok(logout_all::v3::Response::new())
} }
+27 -47
View File
@@ -1,54 +1,34 @@
use std::str::FromStr; use crate::{services, Result, Ruma};
use ruma::api::client::space::get_hierarchy;
use ruma::{ /// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy``
api::client::{error::ErrorKind, space::get_hierarchy},
UInt,
};
use crate::{service::rooms::spaces::PagnationToken, services, Error, Result, Ruma};
/// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy`
/// ///
/// Paginates over the space tree in a depth-first manner to locate child rooms /// Paginates over the space tree in a depth-first manner to locate child rooms of a given space.
/// of a given space. pub async fn get_hierarchy_route(
pub async fn get_hierarchy_route(body: Ruma<get_hierarchy::v1::Request>) -> Result<get_hierarchy::v1::Response> { body: Ruma<get_hierarchy::v1::Request>,
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); ) -> Result<get_hierarchy::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = body let skip = body
.limit .from
.unwrap_or_else(|| UInt::from(10_u32)) .as_ref()
.min(UInt::from(100_u32)); .and_then(|s| s.parse::<usize>().ok())
.unwrap_or(0);
let max_depth = body let limit = body.limit.map_or(10, u64::from).min(100) as usize;
.max_depth
.unwrap_or_else(|| UInt::from(3_u32))
.min(UInt::from(10_u32));
let key = body let max_depth = body.max_depth.map_or(3, u64::from).min(10) as usize + 1; // +1 to skip the space room itself
.from
.as_ref()
.and_then(|s| PagnationToken::from_str(s).ok());
// Should prevent unexpeded behaviour in (bad) clients services()
if let Some(ref token) = key { .rooms
if token.suggested_only != body.suggested_only || token.max_depth != max_depth { .spaces
return Err(Error::BadRequest( .get_hierarchy(
ErrorKind::InvalidParam, sender_user,
"suggested_only and max_depth cannot change on paginated requests", &body.room_id,
)); limit,
} skip,
} max_depth,
body.suggested_only,
services() )
.rooms .await
.spaces
.get_client_hierarchy(
sender_user,
&body.room_id,
u64::from(limit) as usize,
key.map_or(0, |token| u64::from(token.skip) as usize),
u64::from(max_depth) as usize,
body.suggested_only,
)
.await
} }
+228 -248
View File
@@ -1,312 +1,292 @@
use std::sync::Arc; use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma, RumaResponse};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
state::{get_state_events, get_state_events_for_key, send_state_event}, state::{get_state_events, get_state_events_for_key, send_state_event},
}, },
events::{ events::{
room::{ room::canonical_alias::RoomCanonicalAliasEventContent, AnyStateEventContent, StateEventType,
canonical_alias::RoomCanonicalAliasEventContent, },
join_rules::{JoinRule, RoomJoinRulesEventContent}, serde::Raw,
}, EventId, RoomId, UserId,
AnyStateEventContent, StateEventType,
},
serde::Raw,
EventId, RoomId, UserId,
}; };
use tracing::{error, log::warn}; use tracing::{error, log::warn};
use crate::{ /// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}`
service::{self, pdu::PduBuilder},
services, Error, Result, Ruma, RumaResponse,
};
/// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`
/// ///
/// Sends a state event into the room. /// Sends a state event into the room.
/// ///
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed /// - If event is new canonical_alias: Rejects if alias is incorrect
/// - If event is new `canonical_alias`: Rejects if alias is incorrect
pub async fn send_state_event_for_key_route( pub async fn send_state_event_for_key_route(
body: Ruma<send_state_event::v3::Request>, body: Ruma<send_state_event::v3::Request>,
) -> Result<send_state_event::v3::Response> { ) -> Result<send_state_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event_id = send_state_event_for_key_helper( let event_id = send_state_event_for_key_helper(
sender_user, sender_user,
&body.room_id, &body.room_id,
&body.event_type, &body.event_type,
&body.body.body, // Yes, I hate it too &body.body.body, // Yes, I hate it too
body.state_key.clone(), body.state_key.to_owned(),
) )
.await?; .await?;
let event_id = (*event_id).to_owned(); let event_id = (*event_id).to_owned();
Ok(send_state_event::v3::Response { Ok(send_state_event::v3::Response { event_id })
event_id,
})
} }
/// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}`
/// ///
/// Sends a state event into the room. /// Sends a state event into the room.
/// ///
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed /// - If event is new canonical_alias: Rejects if alias is incorrect
/// - If event is new `canonical_alias`: Rejects if alias is incorrect
pub async fn send_state_event_for_empty_key_route( pub async fn send_state_event_for_empty_key_route(
body: Ruma<send_state_event::v3::Request>, body: Ruma<send_state_event::v3::Request>,
) -> Result<RumaResponse<send_state_event::v3::Response>> { ) -> Result<RumaResponse<send_state_event::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event_id = send_state_event_for_key_helper( // Forbid m.room.encryption if encryption is disabled
sender_user, if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() {
&body.room_id, return Err(Error::BadRequest(
&body.event_type.to_string().into(), ErrorKind::Forbidden,
&body.body.body, "Encryption has been disabled",
body.state_key.clone(), ));
) }
.await?;
let event_id = (*event_id).to_owned(); let event_id = send_state_event_for_key_helper(
Ok(send_state_event::v3::Response { sender_user,
event_id, &body.room_id,
} &body.event_type.to_string().into(),
.into()) &body.body.body,
body.state_key.to_owned(),
)
.await?;
let event_id = (*event_id).to_owned();
Ok(send_state_event::v3::Response { event_id }.into())
} }
/// # `GET /_matrix/client/v3/rooms/{roomid}/state` /// # `GET /_matrix/client/r0/rooms/{roomid}/state`
/// ///
/// Get all state events for a room. /// Get all state events for a room.
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_route( pub async fn get_state_events_route(
body: Ruma<get_state_events::v3::Request>, body: Ruma<get_state_events::v3::Request>,
) -> Result<get_state_events::v3::Response> { ) -> Result<get_state_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services() if !services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::forbidden(), ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
Ok(get_state_events::v3::Response { Ok(get_state_events::v3::Response {
room_state: services() room_state: services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_full(&body.room_id) .room_state_full(&body.room_id)
.await? .await?
.values() .values()
.map(|pdu| pdu.to_state_event()) .map(|pdu| pdu.to_state_event())
.collect(), .collect(),
}) })
} }
/// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}` /// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}`
/// ///
/// Get single state event of a room with the specified state key. /// Get single state event of a room with the specified state key.
/// The optional query parameter `?format=event|content` allows returning the /// The optional query parameter `?format=event|content` allows returning the full room state event
/// full room state event or just the state event's content (default behaviour) /// or just the state event's content (default behaviour)
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_for_key_route( pub async fn get_state_events_for_key_route(
body: Ruma<get_state_events_for_key::v3::Request>, body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<get_state_events_for_key::v3::Response> { ) -> Result<get_state_events_for_key::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services() if !services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::forbidden(), ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
let event = services() let event = services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(&body.room_id, &body.event_type, &body.state_key)? .room_state_get(&body.room_id, &body.event_type, &body.state_key)?
.ok_or_else(|| { .ok_or_else(|| {
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id); warn!(
Error::BadRequest(ErrorKind::NotFound, "State event not found.") "State event {:?} not found in room {:?}",
})?; &body.event_type, &body.room_id
if body );
.format Error::BadRequest(ErrorKind::NotFound, "State event not found.")
.as_ref() })?;
.is_some_and(|f| f.to_lowercase().eq("event")) if body
{ .format
Ok(get_state_events_for_key::v3::Response { .as_ref()
content: None, .is_some_and(|f| f.to_lowercase().eq("event"))
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| { {
error!("Invalid room state event in database: {}", e); Ok(get_state_events_for_key::v3::Response {
Error::bad_database("Invalid room state event in database") content: None,
})?, event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
}) error!("Invalid room state event in database: {}", e);
} else { Error::bad_database("Invalid room state event in database")
Ok(get_state_events_for_key::v3::Response { })?,
content: Some(serde_json::from_str(event.content.get()).map_err(|e| { })
error!("Invalid room state event content in database: {}", e); } else {
Error::bad_database("Invalid room state event content in database") Ok(get_state_events_for_key::v3::Response {
})?), content: Some(serde_json::from_str(event.content.get()).map_err(|e| {
event: None, error!("Invalid room state event content in database: {}", e);
}) Error::bad_database("Invalid room state event content in database")
} })?),
event: None,
})
}
} }
/// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}` /// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}`
/// ///
/// Get single state event of a room. /// Get single state event of a room.
/// The optional query parameter `?format=event|content` allows returning the /// The optional query parameter `?format=event|content` allows returning the full room state event
/// full room state event or just the state event's content (default behaviour) /// or just the state event's content (default behaviour)
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_for_empty_key_route( pub async fn get_state_events_for_empty_key_route(
body: Ruma<get_state_events_for_key::v3::Request>, body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> { ) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services() if !services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_state_events(sender_user, &body.room_id)? .user_can_see_state_events(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::forbidden(), ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
let event = services() let event = services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(&body.room_id, &body.event_type, "")? .room_state_get(&body.room_id, &body.event_type, "")?
.ok_or_else(|| { .ok_or_else(|| {
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id); warn!(
Error::BadRequest(ErrorKind::NotFound, "State event not found.") "State event {:?} not found in room {:?}",
})?; &body.event_type, &body.room_id
);
Error::BadRequest(ErrorKind::NotFound, "State event not found.")
})?;
if body if body
.format .format
.as_ref() .as_ref()
.is_some_and(|f| f.to_lowercase().eq("event")) .is_some_and(|f| f.to_lowercase().eq("event"))
{ {
Ok(get_state_events_for_key::v3::Response { Ok(get_state_events_for_key::v3::Response {
content: None, content: None,
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| { event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
error!("Invalid room state event in database: {}", e); error!("Invalid room state event in database: {}", e);
Error::bad_database("Invalid room state event in database") Error::bad_database("Invalid room state event in database")
})?, })?,
} }
.into()) .into())
} else { } else {
Ok(get_state_events_for_key::v3::Response { Ok(get_state_events_for_key::v3::Response {
content: Some(serde_json::from_str(event.content.get()).map_err(|e| { content: Some(serde_json::from_str(event.content.get()).map_err(|e| {
error!("Invalid room state event content in database: {}", e); error!("Invalid room state event content in database: {}", e);
Error::bad_database("Invalid room state event content in database") Error::bad_database("Invalid room state event content in database")
})?), })?),
event: None, event: None,
} }
.into()) .into())
} }
} }
async fn send_state_event_for_key_helper( async fn send_state_event_for_key_helper(
sender: &UserId, room_id: &RoomId, event_type: &StateEventType, json: &Raw<AnyStateEventContent>, state_key: String, sender: &UserId,
room_id: &RoomId,
event_type: &StateEventType,
json: &Raw<AnyStateEventContent>,
state_key: String,
) -> Result<Arc<EventId>> { ) -> Result<Arc<EventId>> {
match *event_type { let sender_user = sender;
// Forbid m.room.encryption if encryption is disabled
StateEventType::RoomEncryption => {
if !services().globals.allow_encryption() {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Encryption has been disabled"));
}
},
// admin room is a sensitive room, it should not ever be made public
StateEventType::RoomJoinRules => {
if let Some(admin_room_id) = service::admin::Service::get_admin_room()? {
if admin_room_id == room_id {
if let Ok(join_rule) = serde_json::from_str::<RoomJoinRulesEventContent>(json.json().get()) {
if join_rule.join_rule == JoinRule::Public {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Admin room is not allowed to be public.",
));
}
}
}
}
},
// TODO: allow alias if it previously existed
StateEventType::RoomCanonicalAlias => {
if let Ok(canonical_alias) = serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get()) {
let mut aliases = canonical_alias.alt_aliases.clone();
if let Some(alias) = canonical_alias.alias { // TODO: Review this check, error if event is unparsable, use event type, allow alias if it
aliases.push(alias); // previously existed
} if let Ok(canonical_alias) =
serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get())
{
let mut aliases = canonical_alias.alt_aliases.clone();
for alias in aliases { if let Some(alias) = canonical_alias.alias {
if alias.server_name() != services().globals.server_name() aliases.push(alias);
|| services() }
.rooms
.alias
.resolve_local_alias(&alias)?
.filter(|room| room == room_id) // Make sure it's the right room
.is_none()
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"You are only allowed to send canonical_alias events when its aliases already exist",
));
}
}
}
},
_ => {},
}
let mutex_state = Arc::clone( for alias in aliases {
services() if alias.server_name() != services().globals.server_name()
.globals || services()
.roomid_mutex_state .rooms
.write() .alias
.await .resolve_local_alias(&alias)?
.entry(room_id.to_owned()) .filter(|room| room == room_id) // Make sure it's the right room
.or_default(), .is_none()
); {
let state_lock = mutex_state.lock().await; return Err(Error::BadRequest(
ErrorKind::Forbidden,
"You are only allowed to send canonical_alias \
events when it's aliases already exists",
));
}
}
}
let event_id = services() let mutex_state = Arc::clone(
.rooms services()
.timeline .globals
.build_and_append_pdu( .roomid_mutex_state
PduBuilder { .write()
event_type: event_type.to_string().into(), .unwrap()
content: serde_json::from_str(json.json().get()).expect("content is valid json"), .entry(room_id.to_owned())
unsigned: None, .or_default(),
state_key: Some(state_key), );
redacts: None, let state_lock = mutex_state.lock().await;
},
sender,
room_id,
&state_lock,
)
.await?;
Ok(event_id) let event_id = services()
.rooms
.timeline
.build_and_append_pdu(
PduBuilder {
event_type: event_type.to_string().into(),
content: serde_json::from_str(json.json().get()).expect("content is valid json"),
unsigned: None,
state_key: Some(state_key),
redacts: None,
},
sender_user,
room_id,
&state_lock,
)
.await?;
Ok(event_id)
} }
+1550 -1508
View File
File diff suppressed because it is too large Load Diff
+90 -76
View File
@@ -1,51 +1,55 @@
use std::collections::BTreeMap;
use ruma::{
api::client::tag::{create_tag, delete_tag, get_tags},
events::{
tag::{TagEvent, TagEventContent},
RoomAccountDataEventType,
},
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::{
api::client::tag::{create_tag, delete_tag, get_tags},
events::{
tag::{TagEvent, TagEventContent},
RoomAccountDataEventType,
},
};
use std::collections::BTreeMap;
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}` /// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`
/// ///
/// Adds a tag to the room. /// Adds a tag to the room.
/// ///
/// - Inserts the tag into the tag event of the room account data. /// - Inserts the tag into the tag event of the room account data.
pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<create_tag::v3::Response> { pub async fn update_tag_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<create_tag::v3::Request>,
) -> Result<create_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services() let event = services().account_data.get(
.account_data Some(&body.room_id),
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; sender_user,
RoomAccountDataEventType::Tag,
)?;
let mut tags_event = event.map_or_else( let mut tags_event = event
|| { .map(|e| {
Ok(TagEvent { serde_json::from_str(e.get())
content: TagEventContent { .map_err(|_| Error::bad_database("Invalid account data event in db."))
tags: BTreeMap::new(), })
}, .unwrap_or_else(|| {
}) Ok(TagEvent {
}, content: TagEventContent {
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")), tags: BTreeMap::new(),
)?; },
})
})?;
tags_event tags_event
.content .content
.tags .tags
.insert(body.tag.clone().into(), body.tag_info.clone()); .insert(body.tag.clone().into(), body.tag_info.clone());
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
RoomAccountDataEventType::Tag, RoomAccountDataEventType::Tag,
&serde_json::to_value(tags_event).expect("to json value always works"), &serde_json::to_value(tags_event).expect("to json value always works"),
)?; )?;
Ok(create_tag::v3::Response {}) Ok(create_tag::v3::Response {})
} }
/// # `DELETE /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}` /// # `DELETE /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`
@@ -53,34 +57,40 @@ pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<cre
/// Deletes a tag from the room. /// Deletes a tag from the room.
/// ///
/// - Removes the tag from the tag event of the room account data. /// - Removes the tag from the tag event of the room account data.
pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<delete_tag::v3::Response> { pub async fn delete_tag_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<delete_tag::v3::Request>,
) -> Result<delete_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services() let event = services().account_data.get(
.account_data Some(&body.room_id),
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; sender_user,
RoomAccountDataEventType::Tag,
)?;
let mut tags_event = event.map_or_else( let mut tags_event = event
|| { .map(|e| {
Ok(TagEvent { serde_json::from_str(e.get())
content: TagEventContent { .map_err(|_| Error::bad_database("Invalid account data event in db."))
tags: BTreeMap::new(), })
}, .unwrap_or_else(|| {
}) Ok(TagEvent {
}, content: TagEventContent {
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")), tags: BTreeMap::new(),
)?; },
})
})?;
tags_event.content.tags.remove(&body.tag.clone().into()); tags_event.content.tags.remove(&body.tag.clone().into());
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
sender_user, sender_user,
RoomAccountDataEventType::Tag, RoomAccountDataEventType::Tag,
&serde_json::to_value(tags_event).expect("to json value always works"), &serde_json::to_value(tags_event).expect("to json value always works"),
)?; )?;
Ok(delete_tag::v3::Response {}) Ok(delete_tag::v3::Response {})
} }
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags` /// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags`
@@ -89,24 +99,28 @@ pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<del
/// ///
/// - Gets the tag event of the room account data. /// - Gets the tag event of the room account data.
pub async fn get_tags_route(body: Ruma<get_tags::v3::Request>) -> Result<get_tags::v3::Response> { pub async fn get_tags_route(body: Ruma<get_tags::v3::Request>) -> Result<get_tags::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services() let event = services().account_data.get(
.account_data Some(&body.room_id),
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; sender_user,
RoomAccountDataEventType::Tag,
)?;
let tags_event = event.map_or_else( let tags_event = event
|| { .map(|e| {
Ok(TagEvent { serde_json::from_str(e.get())
content: TagEventContent { .map_err(|_| Error::bad_database("Invalid account data event in db."))
tags: BTreeMap::new(), })
}, .unwrap_or_else(|| {
}) Ok(TagEvent {
}, content: TagEventContent {
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")), tags: BTreeMap::new(),
)?; },
})
})?;
Ok(get_tags::v3::Response { Ok(get_tags::v3::Response {
tags: tags_event.content.tags, tags: tags_event.content.tags,
}) })
} }
+9 -8
View File
@@ -1,15 +1,16 @@
use std::collections::BTreeMap; use crate::{Result, Ruma};
use ruma::api::client::thirdparty::get_protocols; use ruma::api::client::thirdparty::get_protocols;
use crate::{Result, Ruma}; use std::collections::BTreeMap;
/// # `GET /_matrix/client/r0/thirdparty/protocols` /// # `GET /_matrix/client/r0/thirdparty/protocols`
/// ///
/// TODO: Fetches all metadata about protocols supported by the homeserver. /// TODO: Fetches all metadata about protocols supported by the homeserver.
pub async fn get_protocols_route(_body: Ruma<get_protocols::v3::Request>) -> Result<get_protocols::v3::Response> { pub async fn get_protocols_route(
// TODO _body: Ruma<get_protocols::v3::Request>,
Ok(get_protocols::v3::Response { ) -> Result<get_protocols::v3::Response> {
protocols: BTreeMap::new(), // TODO
}) Ok(get_protocols::v3::Response {
protocols: BTreeMap::new(),
})
} }
+38 -36
View File
@@ -3,45 +3,47 @@ use ruma::api::client::{error::ErrorKind, threads::get_threads};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/rooms/{roomId}/threads` /// # `GET /_matrix/client/r0/rooms/{roomId}/threads`
pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<get_threads::v1::Response> { pub async fn get_threads_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<get_threads::v1::Request>,
) -> Result<get_threads::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = body let limit = body
.limit .limit
.and_then(|l| l.try_into().ok()) .and_then(|l| l.try_into().ok())
.unwrap_or(10) .unwrap_or(10)
.min(100); .min(100);
let from = if let Some(from) = &body.from { let from = if let Some(from) = &body.from {
from.parse() from.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))? .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))?
} else { } else {
u64::MAX u64::MAX
}; };
let threads = services() let threads = services()
.rooms .rooms
.threads .threads
.threads_until(sender_user, &body.room_id, from, &body.include)? .threads_until(sender_user, &body.room_id, from, &body.include)?
.take(limit) .take(limit)
.filter_map(Result::ok) .filter_map(|r| r.ok())
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
.state_accessor .state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id) .user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false) .unwrap_or(false)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let next_batch = threads.last().map(|(count, _)| count.to_string()); let next_batch = threads.last().map(|(count, _)| count.to_string());
Ok(get_threads::v1::Response { Ok(get_threads::v1::Response {
chunk: threads chunk: threads
.into_iter() .into_iter()
.map(|(_, pdu)| pdu.to_room_event()) .map(|(_, pdu)| pdu.to_room_event())
.collect(), .collect(),
next_batch, next_batch,
}) })
} }
+74 -72
View File
@@ -1,90 +1,92 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma::{
api::{
client::{error::ErrorKind, to_device::send_event_to_device},
federation::{self, transactions::edu::DirectDeviceContent},
},
to_device::DeviceIdOrAllDevices,
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
use ruma::{
api::{
client::{error::ErrorKind, to_device::send_event_to_device},
federation::{self, transactions::edu::DirectDeviceContent},
},
to_device::DeviceIdOrAllDevices,
};
/// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}` /// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`
/// ///
/// Send a to-device event to a set of client devices. /// Send a to-device event to a set of client devices.
pub async fn send_event_to_device_route( pub async fn send_event_to_device_route(
body: Ruma<send_event_to_device::v3::Request>, body: Ruma<send_event_to_device::v3::Request>,
) -> Result<send_event_to_device::v3::Response> { ) -> Result<send_event_to_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
// Check if this is a new transaction id // Check if this is a new transaction id
if services() if services()
.transaction_ids .transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)? .existing_txnid(sender_user, sender_device, &body.txn_id)?
.is_some() .is_some()
{ {
return Ok(send_event_to_device::v3::Response {}); return Ok(send_event_to_device::v3::Response {});
} }
for (target_user_id, map) in &body.messages { for (target_user_id, map) in &body.messages {
for (target_device_id_maybe, event) in map { for (target_device_id_maybe, event) in map {
if target_user_id.server_name() != services().globals.server_name() { if target_user_id.server_name() != services().globals.server_name() {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert(target_device_id_maybe.clone(), event.clone()); map.insert(target_device_id_maybe.clone(), event.clone());
let mut messages = BTreeMap::new(); let mut messages = BTreeMap::new();
messages.insert(target_user_id.clone(), map); messages.insert(target_user_id.clone(), map);
let count = services().globals.next_count()?; let count = services().globals.next_count()?;
services().sending.send_edu_server( services().sending.send_reliable_edu(
target_user_id.server_name(), target_user_id.server_name(),
serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(DirectDeviceContent { serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(
sender: sender_user.clone(), DirectDeviceContent {
ev_type: body.event_type.clone(), sender: sender_user.clone(),
message_id: count.to_string().into(), ev_type: body.event_type.clone(),
messages, message_id: count.to_string().into(),
})) messages,
.expect("DirectToDevice EDU can be serialized"), },
)?; ))
.expect("DirectToDevice EDU can be serialized"),
count,
)?;
continue; continue;
} }
match target_device_id_maybe { match target_device_id_maybe {
DeviceIdOrAllDevices::DeviceId(target_device_id) => { DeviceIdOrAllDevices::DeviceId(target_device_id) => {
services().users.add_to_device_event( services().users.add_to_device_event(
sender_user, sender_user,
target_user_id, target_user_id,
target_device_id, target_device_id,
&body.event_type.to_string(), &body.event_type.to_string(),
event event.deserialize_as().map_err(|_| {
.deserialize_as() Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid"))?, })?,
)?; )?
}, }
DeviceIdOrAllDevices::AllDevices => { DeviceIdOrAllDevices::AllDevices => {
for target_device_id in services().users.all_device_ids(target_user_id) { for target_device_id in services().users.all_device_ids(target_user_id) {
services().users.add_to_device_event( services().users.add_to_device_event(
sender_user, sender_user,
target_user_id, target_user_id,
&target_device_id?, &target_device_id?,
&body.event_type.to_string(), &body.event_type.to_string(),
event event.deserialize_as().map_err(|_| {
.deserialize_as() Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid"))?, })?,
)?; )?;
} }
}, }
} }
} }
} }
// Save transaction id with empty data // Save transaction id with empty data
services() services()
.transaction_ids .transaction_ids
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?; .add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
Ok(send_event_to_device::v3::Response {}) Ok(send_event_to_device::v3::Response {})
} }
+28 -31
View File
@@ -1,43 +1,40 @@
use ruma::api::client::{error::ErrorKind, typing::create_typing_event};
use crate::{services, utils, Error, Result, Ruma}; use crate::{services, utils, Error, Result, Ruma};
use ruma::api::client::{error::ErrorKind, typing::create_typing_event};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`
/// ///
/// Sets the typing state of the sender user. /// Sets the typing state of the sender user.
pub async fn create_typing_event_route( pub async fn create_typing_event_route(
body: Ruma<create_typing_event::v3::Request>, body: Ruma<create_typing_event::v3::Request>,
) -> Result<create_typing_event::v3::Response> { ) -> Result<create_typing_event::v3::Response> {
use create_typing_event::v3::Typing; use create_typing_event::v3::Typing;
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services() if !services()
.rooms .rooms
.state_cache .state_cache
.is_joined(sender_user, &body.room_id)? .is_joined(sender_user, &body.room_id)?
{ {
return Err(Error::BadRequest(ErrorKind::forbidden(), "You are not in this room.")); return Err(Error::BadRequest(
} ErrorKind::Forbidden,
"You are not in this room.",
));
}
if let Typing::Yes(duration) = body.state { if let Typing::Yes(duration) = body.state {
let duration = utils::clamp( services().rooms.edus.typing.typing_add(
duration.as_millis() as u64, sender_user,
services().globals.config.typing_client_timeout_min_s * 1000, &body.room_id,
services().globals.config.typing_client_timeout_max_s * 1000, duration.as_millis() as u64 + utils::millis_since_unix_epoch(),
); )?;
services() } else {
.rooms services()
.typing .rooms
.typing_add(sender_user, &body.room_id, utils::millis_since_unix_epoch() + duration) .edus
.await?; .typing
} else { .typing_remove(sender_user, &body.room_id)?;
services() }
.rooms
.typing
.typing_remove(sender_user, &body.room_id)
.await?;
}
Ok(create_typing_event::v3::Response {}) Ok(create_typing_event::v3::Response {})
} }
-45
View File
@@ -1,45 +0,0 @@
use ruma::{
api::client::{error::ErrorKind, membership::mutual_rooms},
OwnedRoomId,
};
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms`
///
/// Gets all the rooms the sender shares with the specified user.
///
/// TODO: Implement pagination, currently this just returns everything
///
/// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666)
pub async fn get_mutual_rooms_route(
body: Ruma<mutual_rooms::unstable::Request>,
) -> Result<mutual_rooms::unstable::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if sender_user == &body.user_id {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"You cannot request rooms in common with yourself.",
));
}
if !services().users.exists(&body.user_id)? {
return Ok(mutual_rooms::unstable::Response {
joined: vec![],
next_batch_token: None,
});
}
let mutual_rooms: Vec<OwnedRoomId> = services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
.filter_map(Result::ok)
.collect();
Ok(mutual_rooms::unstable::Response {
joined: mutual_rooms,
next_batch_token: None,
})
}
+53 -143
View File
@@ -1,168 +1,78 @@
use std::collections::BTreeMap; use std::{collections::BTreeMap, iter::FromIterator};
use axum::{response::IntoResponse, Json}; use axum::{response::IntoResponse, Json};
use ruma::api::client::{ use ruma::api::client::{discovery::get_supported_versions, error::ErrorKind};
discovery::{
discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo},
discover_support::{self, Contact},
get_supported_versions,
},
error::ErrorKind,
};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/versions` /// # `GET /_matrix/client/versions`
/// ///
/// Get the versions of the specification and unstable features supported by /// Get the versions of the specification and unstable features supported by this server.
/// this server.
/// ///
/// - Versions take the form MAJOR.MINOR.PATCH /// - Versions take the form MAJOR.MINOR.PATCH
/// - Only the latest PATCH release will be reported for each MAJOR.MINOR value /// - Only the latest PATCH release will be reported for each MAJOR.MINOR value
/// - Unstable features are namespaced and may include version information in /// - Unstable features are namespaced and may include version information in their name
/// their name
/// ///
/// Note: Unstable features are used while developing new features. Clients /// Note: Unstable features are used while developing new features. Clients should avoid using
/// should avoid using unstable features in their stable releases /// unstable features in their stable releases
pub async fn get_supported_versions_route( pub async fn get_supported_versions_route(
_body: Ruma<get_supported_versions::Request>, _body: Ruma<get_supported_versions::Request>,
) -> Result<get_supported_versions::Response> { ) -> Result<get_supported_versions::Response> {
let resp = get_supported_versions::Response { let resp = get_supported_versions::Response {
versions: vec![ versions: vec![
"r0.0.1".to_owned(), "r0.0.1".to_owned(),
"r0.1.0".to_owned(), "r0.1.0".to_owned(),
"r0.2.0".to_owned(), "r0.2.0".to_owned(),
"r0.3.0".to_owned(), "r0.3.0".to_owned(),
"r0.4.0".to_owned(), "r0.4.0".to_owned(),
"r0.5.0".to_owned(), "r0.5.0".to_owned(),
"r0.6.0".to_owned(), "r0.6.0".to_owned(),
"r0.6.1".to_owned(), "r0.6.1".to_owned(),
"v1.1".to_owned(), "v1.1".to_owned(),
"v1.2".to_owned(), "v1.2".to_owned(),
"v1.3".to_owned(), "v1.3".to_owned(),
"v1.4".to_owned(), "v1.4".to_owned(),
"v1.5".to_owned(), "v1.5".to_owned(),
], ],
unstable_features: BTreeMap::from_iter([ unstable_features: BTreeMap::from_iter([
("org.matrix.e2e_cross_signing".to_owned(), true), ("org.matrix.e2e_cross_signing".to_owned(), true),
("org.matrix.msc2285.stable".to_owned(), true), ("org.matrix.msc2836".to_owned(), true),
("uk.half-shot.msc2666.query_mutual_rooms".to_owned(), true), ("org.matrix.msc3827".to_owned(), true),
("org.matrix.msc2836".to_owned(), true), ("org.matrix.msc2946".to_owned(), true),
("org.matrix.msc2946".to_owned(), true), ]),
("org.matrix.msc3026.busy_presence".to_owned(), true), };
("org.matrix.msc3827".to_owned(), true),
]),
};
Ok(resp) Ok(resp)
} }
/// # `GET /.well-known/matrix/client` /// # `GET /.well-known/matrix/client`
/// pub async fn well_known_client_route() -> Result<impl IntoResponse> {
/// Returns the .well-known URL if it is configured, otherwise returns 404. let client_url = match services().globals.well_known_client() {
pub async fn well_known_client(_body: Ruma<discover_homeserver::Request>) -> Result<discover_homeserver::Response> { Some(url) => url.clone(),
let client_url = match services().globals.well_known_client() { None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")),
Some(url) => url.to_string(), };
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")),
};
Ok(discover_homeserver::Response { Ok(Json(serde_json::json!({
homeserver: HomeserverInfo { "m.homeserver": {"base_url": client_url},
base_url: client_url.clone(), "org.matrix.msc3575.proxy": {"url": client_url}
}, })))
identity_server: None,
sliding_sync_proxy: Some(SlidingSyncProxyInfo {
url: client_url,
}),
tile_server: None,
})
}
/// # `GET /.well-known/matrix/support`
///
/// Server support contact and support page of a homeserver's domain.
pub async fn well_known_support(_body: Ruma<discover_support::Request>) -> Result<discover_support::Response> {
let support_page = services()
.globals
.well_known_support_page()
.as_ref()
.map(ToString::to_string);
let role = services().globals.well_known_support_role().clone();
// support page or role must be either defined for this to be valid
if support_page.is_none() && role.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
let email_address = services().globals.well_known_support_email().clone();
let matrix_id = services().globals.well_known_support_mxid().clone();
// if a role is specified, an email address or matrix id is required
if role.is_some() && (email_address.is_none() && matrix_id.is_none()) {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
// TOOD: support defining multiple contacts in the config
let mut contacts: Vec<Contact> = vec![];
if let Some(role) = role {
let contact = Contact {
role,
email_address,
matrix_id,
};
contacts.push(contact);
}
// support page or role+contacts must be either defined for this to be valid
if contacts.is_empty() && support_page.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
Ok(discover_support::Response {
contacts,
support_page,
})
} }
/// # `GET /client/server.json` /// # `GET /client/server.json`
/// ///
/// Endpoint provided by sliding sync proxy used by some clients such as Element /// Endpoint provided by sliding sync proxy used by some clients such as Element Web
/// Web as a non-standard health check. /// as a non-standard health check.
pub async fn syncv3_client_server_json() -> Result<impl IntoResponse> { pub async fn syncv3_client_server_json() -> Result<impl IntoResponse> {
let server_url = match services().globals.well_known_client() { let server_url = match services().globals.well_known_client() {
Some(url) => url.to_string(), Some(url) => url.clone(),
None => match services().globals.well_known_server() { None => match services().globals.well_known_server() {
Some(url) => url.to_string(), Some(url) => url.clone(),
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")), None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")),
}, },
}; };
let version = match option_env!("CONDUIT_VERSION_EXTRA") { Ok(Json(serde_json::json!({
Some(extra) => format!("{} ({})", env!("CARGO_PKG_VERSION"), extra), "server": server_url,
None => env!("CARGO_PKG_VERSION").to_owned(), "version": format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
}; })))
Ok(Json(serde_json::json!({
"server": server_url,
"version": version,
})))
}
/// # `GET /_conduwuit/server_version`
///
/// Conduwuit-specific API to get the server version, results akin to
/// `/_matrix/federation/v1/version`
pub async fn conduwuit_server_version() -> Result<impl IntoResponse> {
let version = match option_env!("CONDUIT_VERSION_EXTRA") {
Some(extra) => format!("{} ({})", env!("CARGO_PKG_VERSION"), extra),
None => env!("CARGO_PKG_VERSION").to_owned(),
};
Ok(Json(serde_json::json!({
"name": "Conduwuit",
"version": version,
})))
} }
+74 -82
View File
@@ -1,102 +1,94 @@
use ruma::{
api::client::user_directory::search_users,
events::{
room::join_rules::{JoinRule, RoomJoinRulesEventContent},
StateEventType,
},
};
use crate::{services, Result, Ruma}; use crate::{services, Result, Ruma};
use ruma::{
api::client::user_directory::search_users,
events::{
room::join_rules::{JoinRule, RoomJoinRulesEventContent},
StateEventType,
},
};
/// # `POST /_matrix/client/r0/user_directory/search` /// # `POST /_matrix/client/r0/user_directory/search`
/// ///
/// Searches all known users for a match. /// Searches all known users for a match.
/// ///
/// - Hides any local users that aren't in any public rooms (i.e. those that /// - Hides any local users that aren't in any public rooms (i.e. those that have the join rule set to public)
/// have the join rule set to public)
/// and don't share a room with the sender /// and don't share a room with the sender
pub async fn search_users_route(body: Ruma<search_users::v3::Request>) -> Result<search_users::v3::Response> { pub async fn search_users_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<search_users::v3::Request>,
let limit = u64::from(body.limit) as usize; ) -> Result<search_users::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = u64::from(body.limit) as usize;
let mut users = services().users.iter().filter_map(|user_id| { let mut users = services().users.iter().filter_map(|user_id| {
// Filter out buggy users (they should not exist, but you never know...) // Filter out buggy users (they should not exist, but you never know...)
let user_id = user_id.ok()?; let user_id = user_id.ok()?;
let user = search_users::v3::User { let user = search_users::v3::User {
user_id: user_id.clone(), user_id: user_id.clone(),
display_name: services().users.displayname(&user_id).ok()?, display_name: services().users.displayname(&user_id).ok()?,
avatar_url: services().users.avatar_url(&user_id).ok()?, avatar_url: services().users.avatar_url(&user_id).ok()?,
}; };
let user_id_matches = user let user_id_matches = user
.user_id .user_id
.to_string() .to_string()
.to_lowercase() .to_lowercase()
.contains(&body.search_term.to_lowercase()); .contains(&body.search_term.to_lowercase());
let user_displayname_matches = user let user_displayname_matches = user
.display_name .display_name
.as_ref() .as_ref()
.filter(|name| { .filter(|name| {
name.to_lowercase() name.to_lowercase()
.contains(&body.search_term.to_lowercase()) .contains(&body.search_term.to_lowercase())
}) })
.is_some(); .is_some();
if !user_id_matches && !user_displayname_matches { if !user_id_matches && !user_displayname_matches {
return None; return None;
} }
// It's a matching user, but is the sender allowed to see them? let user_is_in_public_rooms = services()
let mut user_visible = false; .rooms
.state_cache
.rooms_joined(&user_id)
.filter_map(|r| r.ok())
.any(|room| {
services()
.rooms
.state_accessor
.room_state_get(&room, &StateEventType::RoomJoinRules, "")
.map_or(false, |event| {
event.map_or(false, |event| {
serde_json::from_str(event.content.get())
.map_or(false, |r: RoomJoinRulesEventContent| {
r.join_rule == JoinRule::Public
})
})
})
});
let user_is_in_public_rooms = services() if user_is_in_public_rooms {
.rooms return Some(user);
.state_cache }
.rooms_joined(&user_id)
.filter_map(Result::ok)
.any(|room| {
services()
.rooms
.state_accessor
.room_state_get(&room, &StateEventType::RoomJoinRules, "")
.map_or(false, |event| {
event.map_or(false, |event| {
serde_json::from_str(event.content.get())
.map_or(false, |r: RoomJoinRulesEventContent| r.join_rule == JoinRule::Public)
})
})
});
if user_is_in_public_rooms { let user_is_in_shared_rooms = services()
user_visible = true; .rooms
} else { .user
let user_is_in_shared_rooms = services() .get_shared_rooms(vec![sender_user.clone(), user_id])
.rooms .ok()?
.user .next()
.get_shared_rooms(vec![sender_user.clone(), user_id]) .is_some();
.ok()?
.next()
.is_some();
if user_is_in_shared_rooms { if user_is_in_shared_rooms {
user_visible = true; return Some(user);
} }
}
if !user_visible { None
return None; });
}
Some(user) let results = users.by_ref().take(limit).collect();
}); let limited = users.next().is_some();
let results = users.by_ref().take(limit).collect(); Ok(search_users::v3::Response { results, limited })
let limited = users.next().is_some();
Ok(search_users::v3::Response {
results,
limited,
})
} }
+28 -29
View File
@@ -1,11 +1,9 @@
use std::time::{Duration, SystemTime}; use crate::{services, Result, Ruma};
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
use hmac::{Hmac, Mac}; use hmac::{Hmac, Mac};
use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch}; use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch};
use sha1::Sha1; use sha1::Sha1;
use std::time::{Duration, SystemTime};
use crate::{services, Result, Ruma};
type HmacSha1 = Hmac<Sha1>; type HmacSha1 = Hmac<Sha1>;
@@ -13,37 +11,38 @@ type HmacSha1 = Hmac<Sha1>;
/// ///
/// TODO: Returns information about the recommended turn server. /// TODO: Returns information about the recommended turn server.
pub async fn turn_server_route( pub async fn turn_server_route(
body: Ruma<get_turn_server_info::v3::Request>, body: Ruma<get_turn_server_info::v3::Request>,
) -> Result<get_turn_server_info::v3::Response> { ) -> Result<get_turn_server_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let turn_secret = services().globals.turn_secret().clone(); let turn_secret = services().globals.turn_secret().clone();
let (username, password) = if !turn_secret.is_empty() { let (username, password) = if !turn_secret.is_empty() {
let expiry = SecondsSinceUnixEpoch::from_system_time( let expiry = SecondsSinceUnixEpoch::from_system_time(
SystemTime::now() + Duration::from_secs(services().globals.turn_ttl()), SystemTime::now() + Duration::from_secs(services().globals.turn_ttl()),
) )
.expect("time is valid"); .expect("time is valid");
let username: String = format!("{}:{}", expiry.get(), sender_user); let username: String = format!("{}:{}", expiry.get(), sender_user);
let mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes()).expect("HMAC can take key of any size"); let mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes())
mac.update(username.as_bytes()); .expect("HMAC can take key of any size");
mac.update(username.as_bytes());
let password: String = general_purpose::STANDARD.encode(mac.finalize().into_bytes()); let password: String = general_purpose::STANDARD.encode(mac.finalize().into_bytes());
(username, password) (username, password)
} else { } else {
( (
services().globals.turn_username().clone(), services().globals.turn_username().clone(),
services().globals.turn_password().clone(), services().globals.turn_password().clone(),
) )
}; };
Ok(get_turn_server_info::v3::Response { Ok(get_turn_server_info::v3::Response {
username, username,
password, password,
uris: services().globals.turn_uris().to_vec(), uris: services().globals.turn_uris().to_vec(),
ttl: Duration::from_secs(services().globals.turn_ttl()), ttl: Duration::from_secs(services().globals.turn_ttl()),
}) })
} }
+1
View File
@@ -1,3 +1,4 @@
pub mod appservice_server;
pub mod client_server; pub mod client_server;
pub mod ruma_wrapper; pub mod ruma_wrapper;
pub mod server_server; pub mod server_server;
+374 -351
View File
@@ -1,401 +1,424 @@
use std::{collections::BTreeMap, str}; use std::{collections::BTreeMap, iter::FromIterator, str};
use axum::{ use axum::{
async_trait, async_trait,
body::{Full, HttpBody}, body::{Full, HttpBody},
extract::{rejection::TypedHeaderRejectionReason, FromRequest, Path, TypedHeader}, extract::{rejection::TypedHeaderRejectionReason, FromRequest, Path, TypedHeader},
headers::{ headers::{
authorization::{Bearer, Credentials}, authorization::{Bearer, Credentials},
Authorization, Authorization,
}, },
response::{IntoResponse, Response}, response::{IntoResponse, Response},
BoxError, RequestExt, RequestPartsExt, BoxError, RequestExt, RequestPartsExt,
}; };
use bytes::{Buf, BufMut, Bytes, BytesMut}; use bytes::{Buf, BufMut, Bytes, BytesMut};
use http::{uri::PathAndQuery, Request, StatusCode}; use http::{Request, StatusCode};
use ruma::{ use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse}, api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, error, trace, warn}; use tracing::{debug, error, warn};
use super::{Ruma, RumaResponse}; use super::{Ruma, RumaResponse};
use crate::{service::appservice::RegistrationInfo, services, Error, Result}; use crate::{services, Error, Result};
enum Token {
Appservice(Box<RegistrationInfo>),
User((OwnedUserId, OwnedDeviceId)),
Invalid,
None,
}
#[derive(Deserialize)] #[derive(Deserialize)]
struct QueryParams { struct QueryParams {
access_token: Option<String>, access_token: Option<String>,
user_id: Option<String>, user_id: Option<String>,
} }
#[async_trait] #[async_trait]
impl<T, S, B> FromRequest<S, B> for Ruma<T> impl<T, S, B> FromRequest<S, B> for Ruma<T>
where where
T: IncomingRequest, T: IncomingRequest,
B: HttpBody + Send + 'static, B: HttpBody + Send + 'static,
B::Data: Send, B::Data: Send,
B::Error: Into<BoxError>, B::Error: Into<BoxError>,
{ {
type Rejection = Error; type Rejection = Error;
#[allow(unused_qualifications)] // async traits async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> {
async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> { let (mut parts, mut body) = match req.with_limited_body() {
let (mut parts, mut body) = match req.with_limited_body() { Ok(limited_req) => {
Ok(limited_req) => { let (parts, body) = limited_req.into_parts();
let (parts, body) = limited_req.into_parts(); let body = to_bytes(body)
let body = to_bytes(body) .await
.await .map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; (parts, body)
(parts, body) }
}, Err(original_req) => {
Err(original_req) => { let (parts, body) = original_req.into_parts();
let (parts, body) = original_req.into_parts(); let body = to_bytes(body)
let body = to_bytes(body) .await
.await .map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; (parts, body)
(parts, body) }
}, };
};
let metadata = T::METADATA; let metadata = T::METADATA;
let auth_header: Option<TypedHeader<Authorization<Bearer>>> = parts.extract().await?; let auth_header: Option<TypedHeader<Authorization<Bearer>>> = parts.extract().await?;
let path_params: Path<Vec<String>> = parts.extract().await?; let path_params: Path<Vec<String>> = parts.extract().await?;
let query = parts.uri.query().unwrap_or_default(); let query = parts.uri.query().unwrap_or_default();
let query_params: QueryParams = match serde_html_form::from_str(query) { let query_params: QueryParams = match serde_html_form::from_str(query) {
Ok(params) => params, Ok(params) => params,
Err(e) => { Err(e) => {
error!(%query, "Failed to deserialize query parameters: {e}"); error!(%query, "Failed to deserialize query parameters: {}", e);
return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to read query parameters")); return Err(Error::BadRequest(
}, ErrorKind::Unknown,
}; "Failed to read query parameters",
));
}
};
let token = match &auth_header { let token = match &auth_header {
Some(TypedHeader(Authorization(bearer))) => Some(bearer.token()), Some(TypedHeader(Authorization(bearer))) => Some(bearer.token()),
None => query_params.access_token.as_deref(), None => query_params.access_token.as_deref(),
}; };
let token = if let Some(token) = token { let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
if let Some(reg_info) = services().appservice.find_from_token(token).await {
Token::Appservice(Box::new(reg_info))
} else if let Some((user_id, device_id)) = services().users.find_from_token(token)? {
Token::User((user_id, OwnedDeviceId::from(device_id)))
} else {
Token::Invalid
}
} else {
Token::None
};
if metadata.authentication == AuthScheme::None { let appservices = services().appservice.all().unwrap();
match parts.uri.path() { let appservice_registration = appservices
// TODO: can we check this better? .iter()
"/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => { .find(|(_id, registration)| Some(registration.as_token.as_str()) == token);
if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
match token {
Token::Appservice(_) | Token::User(_) => {
// we should have validated the token above
// already
},
Token::None | Token::Invalid => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing or invalid access token.",
));
},
}
}
},
_ => {},
};
}
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok(); let (sender_user, sender_device, sender_servername, from_appservice) =
if let Some((_id, registration)) = appservice_registration {
match metadata.authentication {
AuthScheme::AccessToken => {
let user_id = query_params.user_id.map_or_else(
|| {
UserId::parse_with_server_name(
registration.sender_localpart.as_str(),
services().globals.server_name(),
)
.unwrap()
},
|s| UserId::parse(s).unwrap(),
);
let (sender_user, sender_device, sender_servername, appservice_info) = match (metadata.authentication, token) { if !services().users.exists(&user_id).unwrap() {
(_, Token::Invalid) => { return Err(Error::BadRequest(
return Err(Error::BadRequest( ErrorKind::Forbidden,
ErrorKind::UnknownToken { "User does not exist.",
soft_logout: false, ));
}, }
"Unknown access token.",
))
},
(AuthScheme::AccessToken | AuthScheme::AccessTokenOptional, Token::Appservice(info)) => {
let user_id = query_params
.user_id
.map_or_else(
|| {
UserId::parse_with_server_name(
info.registration.sender_localpart.as_str(),
services().globals.server_name(),
)
},
UserId::parse,
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
if !info.is_user_match(&user_id) { // TODO: Check if appservice is allowed to be that user
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace.")); (Some(user_id), None, None, true)
} }
AuthScheme::ServerSignatures => (None, None, None, true),
AuthScheme::None => (None, None, None, true),
}
} else {
match metadata.authentication {
AuthScheme::AccessToken => {
let token = match token {
Some(token) => token,
_ => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing access token.",
))
}
};
if !services().users.exists(&user_id)? { match services().users.find_from_token(token).unwrap() {
return Err(Error::BadRequest(ErrorKind::forbidden(), "User does not exist.")); None => {
} return Err(Error::BadRequest(
ErrorKind::UnknownToken { soft_logout: false },
"Unknown access token.",
))
}
Some((user_id, device_id)) => (
Some(user_id),
Some(OwnedDeviceId::from(device_id)),
None,
false,
),
}
}
AuthScheme::ServerSignatures => {
let TypedHeader(Authorization(x_matrix)) = parts
.extract::<TypedHeader<Authorization<XMatrix>>>()
.await
.map_err(|e| {
warn!("Missing or invalid Authorization header: {}", e);
(Some(user_id), None, None, Some(*info)) let msg = match e.reason() {
}, TypedHeaderRejectionReason::Missing => {
(AuthScheme::None | AuthScheme::AppserviceToken, Token::Appservice(info)) => { "Missing Authorization header."
(None, None, None, Some(*info)) }
}, TypedHeaderRejectionReason::Error(_) => {
(AuthScheme::AccessToken, Token::None) => { "Invalid X-Matrix signatures."
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")); }
}, _ => "Unknown header-related error",
( };
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None,
Token::User((user_id, device_id)),
) => (Some(user_id), Some(device_id), None, None),
(AuthScheme::ServerSignatures, Token::None) => {
if !services().globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled."));
}
let TypedHeader(Authorization(x_matrix)) = parts Error::BadRequest(ErrorKind::Forbidden, msg)
.extract::<TypedHeader<Authorization<XMatrix>>>() })?;
.await
.map_err(|e| {
warn!("Missing or invalid Authorization header: {e}");
let msg = match e.reason() { let origin_signatures = BTreeMap::from_iter([(
TypedHeaderRejectionReason::Missing => "Missing Authorization header.", x_matrix.key.clone(),
TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.", CanonicalJsonValue::String(x_matrix.sig),
_ => "Unknown header-related error", )]);
};
Error::BadRequest(ErrorKind::forbidden(), msg) let signatures = BTreeMap::from_iter([(
})?; x_matrix.origin.as_str().to_owned(),
CanonicalJsonValue::Object(origin_signatures),
)]);
let origin_signatures = let server_destination =
BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]); services().globals.server_name().as_str().to_owned();
let signatures = BTreeMap::from_iter([( if let Some(destination) = x_matrix.destination.as_ref() {
x_matrix.origin.as_str().to_owned(), if destination != &server_destination {
CanonicalJsonValue::Object(origin_signatures), return Err(Error::BadRequest(
)]); ErrorKind::Forbidden,
"Invalid authorization.",
));
}
}
let server_destination = services().globals.server_name().as_str().to_owned(); let mut request_map = BTreeMap::from_iter([
(
"method".to_owned(),
CanonicalJsonValue::String(parts.method.to_string()),
),
(
"uri".to_owned(),
CanonicalJsonValue::String(parts.uri.to_string()),
),
(
"origin".to_owned(),
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()),
),
(
"destination".to_owned(),
CanonicalJsonValue::String(server_destination),
),
(
"signatures".to_owned(),
CanonicalJsonValue::Object(signatures),
),
]);
if let Some(destination) = x_matrix.destination.as_ref() { if let Some(json_body) = &json_body {
if destination != &server_destination { request_map.insert("content".to_owned(), json_body.clone());
return Err(Error::BadRequest(ErrorKind::forbidden(), "Invalid authorization.")); };
}
}
let signature_uri = CanonicalJsonValue::String( let keys_result = services()
parts .rooms
.uri .event_handler
.path_and_query() .fetch_signing_keys_for_server(
.unwrap_or(&PathAndQuery::from_static("/")) &x_matrix.origin,
.to_string(), vec![x_matrix.key.to_owned()],
); )
.await;
let mut request_map = BTreeMap::from_iter([ let keys = match keys_result {
("method".to_owned(), CanonicalJsonValue::String(parts.method.to_string())), Ok(b) => b,
("uri".to_owned(), signature_uri), Err(e) => {
( warn!("Failed to fetch signing keys: {}", e);
"origin".to_owned(), return Err(Error::BadRequest(
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()), ErrorKind::Forbidden,
), "Failed to fetch signing keys.",
("destination".to_owned(), CanonicalJsonValue::String(server_destination)), ));
("signatures".to_owned(), CanonicalJsonValue::Object(signatures)), }
]); };
if let Some(json_body) = &json_body { let pub_key_map =
request_map.insert("content".to_owned(), json_body.clone()); BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]);
};
let keys_result = services() match ruma::signatures::verify_json(&pub_key_map, &request_map) {
.rooms Ok(()) => (None, None, Some(x_matrix.origin), false),
.event_handler Err(e) => {
.fetch_signing_keys_for_server(&x_matrix.origin, vec![x_matrix.key.clone()]) warn!(
.await; "Failed to verify json request from {}: {}\n{:?}",
x_matrix.origin, e, request_map
);
let keys = keys_result.map_err(|e| { if parts.uri.to_string().contains('@') {
warn!("Failed to fetch signing keys: {e}"); warn!(
Error::BadRequest(ErrorKind::forbidden(), "Failed to fetch signing keys.") "Request uri contained '@' character. Make sure your \
})?; reverse proxy gives Conduit the raw uri (apache: use \
nocanon)"
);
}
let pub_key_map = BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Failed to verify X-Matrix signatures.",
));
}
}
}
AuthScheme::None => match parts.uri.path() {
// allow_public_room_directory_without_auth
"/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => {
if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
let token = match token {
Some(token) => token,
_ => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing access token.",
))
}
};
match ruma::signatures::verify_json(&pub_key_map, &request_map) { match services().users.find_from_token(token).unwrap() {
Ok(()) => (None, None, Some(x_matrix.origin), None), None => {
Err(e) => { return Err(Error::BadRequest(
warn!("Failed to verify json request from {}: {e}\n{request_map:?}", x_matrix.origin); ErrorKind::UnknownToken { soft_logout: false },
"Unknown access token.",
))
}
Some((user_id, device_id)) => (
Some(user_id),
Some(OwnedDeviceId::from(device_id)),
None,
false,
),
}
} else {
(None, None, None, false)
}
}
_ => (None, None, None, false),
},
}
};
if parts.uri.to_string().contains('@') { let mut http_request = http::Request::builder().uri(parts.uri).method(parts.method);
warn!( *http_request.headers_mut().unwrap() = parts.headers;
"Request uri contained '@' character. Make sure your reverse proxy gives Conduit the \
raw uri (apache: use nocanon)"
);
}
return Err(Error::BadRequest( if let Some(CanonicalJsonValue::Object(json_body)) = &mut json_body {
ErrorKind::forbidden(), let user_id = sender_user.clone().unwrap_or_else(|| {
"Failed to verify X-Matrix signatures.", UserId::parse_with_server_name("", services().globals.server_name())
)); .expect("we know this is valid")
}, });
}
},
(AuthScheme::None | AuthScheme::AppserviceToken | AuthScheme::AccessTokenOptional, Token::None) => {
(None, None, None, None)
},
(AuthScheme::ServerSignatures, Token::Appservice(_) | Token::User(_)) => {
return Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only server signatures should be used on this endpoint.",
));
},
(AuthScheme::AppserviceToken, Token::User(_)) => {
return Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only appservice access tokens should be used on this endpoint.",
));
},
};
let mut http_request = Request::builder().uri(parts.uri).method(parts.method); let uiaa_request = json_body
*http_request.headers_mut().unwrap() = parts.headers; .get("auth")
.and_then(|auth| auth.as_object())
.and_then(|auth| auth.get("session"))
.and_then(|session| session.as_str())
.and_then(|session| {
services().uiaa.get_uiaa_request(
&user_id,
&sender_device.clone().unwrap_or_else(|| "".into()),
session,
)
});
if let Some(CanonicalJsonValue::Object(json_body)) = &mut json_body { if let Some(CanonicalJsonValue::Object(initial_request)) = uiaa_request {
let user_id = sender_user.clone().unwrap_or_else(|| { for (key, value) in initial_request {
UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid") json_body.entry(key).or_insert(value);
}); }
}
let uiaa_request = json_body let mut buf = BytesMut::new().writer();
.get("auth") serde_json::to_writer(&mut buf, json_body).expect("value serialization can't fail");
.and_then(|auth| auth.as_object()) body = buf.into_inner().freeze();
.and_then(|auth| auth.get("session")) }
.and_then(|session| session.as_str())
.and_then(|session| {
services().uiaa.get_uiaa_request(
&user_id,
&sender_device.clone().unwrap_or_else(|| "".into()),
session,
)
});
if let Some(CanonicalJsonValue::Object(initial_request)) = uiaa_request { let http_request = http_request.body(&*body).unwrap();
for (key, value) in initial_request {
json_body.entry(key).or_insert(value);
}
}
let mut buf = BytesMut::new().writer(); debug!("{:?}", http_request);
serde_json::to_writer(&mut buf, json_body).expect("value serialization can't fail");
body = buf.into_inner().freeze();
}
let http_request = http_request.body(&*body).unwrap(); let body = T::try_from_http_request(http_request, &path_params).map_err(|e| {
debug!( warn!("try_from_http_request failed: {:?}", e);
"{:?} {:?} {:?}", debug!("JSON body: {:?}", json_body);
http_request.method(), Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.")
http_request.uri(), })?;
http_request.headers()
);
trace!("{:?} {:?} {:?}", http_request.method(), http_request.uri(), json_body); Ok(Ruma {
let body = T::try_from_http_request(http_request, &path_params).map_err(|e| { body,
warn!("try_from_http_request failed: {e:?}\nPath parameters: {path_params:?}",); sender_user,
debug!("JSON body: {:?}", json_body); sender_device,
Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.") sender_servername,
})?; from_appservice,
json_body,
Ok(Ruma { })
body, }
sender_user,
sender_device,
sender_servername,
json_body,
appservice_info,
})
}
} }
struct XMatrix { struct XMatrix {
origin: OwnedServerName, origin: OwnedServerName,
destination: Option<String>, destination: Option<String>,
key: String, // KeyName? key: String, // KeyName?
sig: String, sig: String,
} }
impl Credentials for XMatrix { impl Credentials for XMatrix {
const SCHEME: &'static str = "X-Matrix"; const SCHEME: &'static str = "X-Matrix";
fn decode(value: &http::HeaderValue) -> Option<Self> { fn decode(value: &http::HeaderValue) -> Option<Self> {
debug_assert!( debug_assert!(
value.as_bytes().starts_with(b"X-Matrix "), value.as_bytes().starts_with(b"X-Matrix "),
"HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}", "HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}",
); );
let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..]) let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..])
.ok()? .ok()?
.trim_start(); .trim_start();
let mut origin = None; let mut origin = None;
let mut destination = None; let mut destination = None;
let mut key = None; let mut key = None;
let mut sig = None; let mut sig = None;
for entry in parameters.split_terminator(',') { for entry in parameters.split_terminator(',') {
let (name, value) = entry.split_once('=')?; let (name, value) = entry.split_once('=')?;
// It's not at all clear why some fields are quoted and others not in the spec, // It's not at all clear why some fields are quoted and others not in the spec,
// let's simply accept either form for every field. // let's simply accept either form for every field.
let value = value let value = value
.strip_prefix('"') .strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"')) .and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(value); .unwrap_or(value);
// FIXME: Catch multiple fields of the same name // FIXME: Catch multiple fields of the same name
match name { match name {
"origin" => origin = Some(value.try_into().ok()?), "origin" => origin = Some(value.try_into().ok()?),
"key" => key = Some(value.to_owned()), "key" => key = Some(value.to_owned()),
"sig" => sig = Some(value.to_owned()), "sig" => sig = Some(value.to_owned()),
"destination" => destination = Some(value.to_owned()), "destination" => destination = Some(value.to_owned()),
_ => debug!("Unexpected field `{name}` in X-Matrix Authorization header"), _ => debug!(
} "Unexpected field `{}` in X-Matrix Authorization header",
} name
),
}
}
Some(Self { Some(Self {
origin: origin?, origin: origin?,
key: key?, key: key?,
sig: sig?, sig: sig?,
destination, destination,
}) })
} }
fn encode(&self) -> http::HeaderValue { todo!() } fn encode(&self) -> http::HeaderValue {
todo!()
}
} }
impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> { impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> {
fn into_response(self) -> Response { fn into_response(self) -> Response {
match self.0.try_into_http_response::<BytesMut>() { match self.0.try_into_http_response::<BytesMut>() {
Ok(res) => res.map(BytesMut::freeze).map(Full::new).into_response(), Ok(res) => res.map(BytesMut::freeze).map(Full::new).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
} }
} }
} }
// copied from hyper under the following license: // copied from hyper under the following license:
@@ -420,32 +443,32 @@ impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> {
// THE SOFTWARE. // THE SOFTWARE.
pub(crate) async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error> pub(crate) async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
where where
T: HttpBody, T: HttpBody,
{ {
futures_util::pin_mut!(body); futures_util::pin_mut!(body);
// If there's only 1 chunk, we can just return Buf::to_bytes() // If there's only 1 chunk, we can just return Buf::to_bytes()
let mut first = if let Some(buf) = body.data().await { let mut first = if let Some(buf) = body.data().await {
buf? buf?
} else { } else {
return Ok(Bytes::new()); return Ok(Bytes::new());
}; };
let second = if let Some(buf) = body.data().await { let second = if let Some(buf) = body.data().await {
buf? buf?
} else { } else {
return Ok(first.copy_to_bytes(first.remaining())); return Ok(first.copy_to_bytes(first.remaining()));
}; };
// With more than 1 buf, we gotta flatten into a Vec first. // With more than 1 buf, we gotta flatten into a Vec first.
let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize; let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize;
let mut vec = Vec::with_capacity(cap); let mut vec = Vec::with_capacity(cap);
vec.put(first); vec.put(first);
vec.put(second); vec.put(second);
while let Some(buf) = body.data().await { while let Some(buf) = body.data().await {
vec.put(buf?); vec.put(buf?);
} }
Ok(vec.into()) Ok(vec.into())
} }
+23 -15
View File
@@ -1,35 +1,43 @@
use crate::Error;
use ruma::{
api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName,
OwnedUserId,
};
use std::ops::Deref; use std::ops::Deref;
use ruma::{api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId}; #[cfg(feature = "conduit_bin")]
use crate::{service::appservice::RegistrationInfo, Error};
mod axum; mod axum;
/// Extractor for Ruma request structs /// Extractor for Ruma request structs
pub struct Ruma<T> { pub struct Ruma<T> {
pub body: T, pub body: T,
pub sender_user: Option<OwnedUserId>, pub sender_user: Option<OwnedUserId>,
pub sender_device: Option<OwnedDeviceId>, pub sender_device: Option<OwnedDeviceId>,
pub sender_servername: Option<OwnedServerName>, pub sender_servername: Option<OwnedServerName>,
// This is None when body is not a valid string // This is None when body is not a valid string
pub json_body: Option<CanonicalJsonValue>, pub json_body: Option<CanonicalJsonValue>,
pub appservice_info: Option<RegistrationInfo>, pub from_appservice: bool,
} }
impl<T> Deref for Ruma<T> { impl<T> Deref for Ruma<T> {
type Target = T; type Target = T;
fn deref(&self) -> &Self::Target { &self.body } fn deref(&self) -> &Self::Target {
&self.body
}
} }
#[derive(Clone)] #[derive(Clone)]
pub struct RumaResponse<T>(pub T); pub struct RumaResponse<T>(pub T);
impl<T> From<T> for RumaResponse<T> { impl<T> From<T> for RumaResponse<T> {
fn from(t: T) -> Self { Self(t) } fn from(t: T) -> Self {
Self(t)
}
} }
impl From<Error> for RumaResponse<UiaaResponse> { impl From<Error> for RumaResponse<UiaaResponse> {
fn from(t: Error) -> Self { t.to_response() } fn from(t: Error) -> Self {
t.to_response()
}
} }
+1885 -1630
View File
File diff suppressed because it is too large Load Diff
-33
View File
@@ -1,33 +0,0 @@
//! Integration with `clap`
use std::path::PathBuf;
use clap::Parser;
/// Returns the current version of the crate with extra info if supplied
///
/// Set the environment variable `CONDUIT_VERSION_EXTRA` to any UTF-8 string to
/// include it in parenthesis after the SemVer version. A common value are git
/// commit hashes.
#[allow(clippy::doc_markdown)]
fn version() -> String {
let cargo_pkg_version = env!("CARGO_PKG_VERSION");
match option_env!("CONDUIT_VERSION_EXTRA") {
Some(x) => format!("{} ({})", cargo_pkg_version, x),
None => cargo_pkg_version.to_owned(),
}
}
/// Commandline arguments
#[derive(Parser, Debug)]
#[clap(version = version(), about, long_about = None)]
pub struct Args {
#[arg(short, long)]
/// Optional argument to the path of a conduwuit config TOML file
pub config: Option<PathBuf>,
}
/// Parse commandline arguments into structured data
#[must_use]
pub fn parse() -> Args { Args::parse() }
-166
View File
@@ -1,166 +0,0 @@
#[cfg(unix)]
use std::path::Path; // not unix specific, just only for UNIX sockets stuff and *nix container checks
use tracing::{debug, error, info, warn};
use crate::{utils::error::Error, Config};
pub fn check(config: &Config) -> Result<(), Error> {
config.warn_deprecated();
config.warn_unknown_key();
if cfg!(feature = "hardened_malloc") && cfg!(feature = "jemalloc") {
warn!(
"hardened_malloc and jemalloc were built together, this causes neither to be used. Conduwuit will still \
function, but consider rebuilding and pick one as this is now no-op."
);
}
if config.unix_socket_path.is_some() && !cfg!(unix) {
return Err(Error::bad_config(
"UNIX socket support is only available on *nix platforms. Please remove \"unix_socket_path\" from your \
config.",
));
}
if config.address.is_loopback() && cfg!(unix) {
debug!(
"Found loopback listening address {}, running checks if we're in a container.",
config.address
);
#[cfg(unix)]
if Path::new("/proc/vz").exists() /* Guest */ && !Path::new("/proc/bz").exists()
/* Host */
{
error!(
"You are detected using OpenVZ with a loopback/localhost listening address of {}. If you are using \
OpenVZ for containers and you use NAT-based networking to communicate with the host and guest, this \
will NOT work. Please change this to \"0.0.0.0\". If this is expected, you can ignore.",
config.address
);
}
#[cfg(unix)]
if Path::new("/.dockerenv").exists() {
error!(
"You are detected using Docker with a loopback/localhost listening address of {}. If you are using a \
reverse proxy on the host and require communication to conduwuit in the Docker container via \
NAT-based networking, this will NOT work. Please change this to \"0.0.0.0\". If this is expected, \
you can ignore.",
config.address
);
}
#[cfg(unix)]
if Path::new("/run/.containerenv").exists() {
error!(
"You are detected using Podman with a loopback/localhost listening address of {}. If you are using a \
reverse proxy on the host and require communication to conduwuit in the Podman container via \
NAT-based networking, this will NOT work. Please change this to \"0.0.0.0\". If this is expected, \
you can ignore.",
config.address
);
}
}
// rocksdb does not allow max_log_files to be 0
if config.rocksdb_max_log_files == 0 && cfg!(feature = "rocksdb") {
return Err(Error::bad_config(
"When using RocksDB, rocksdb_max_log_files cannot be 0. Please set a value at least 1.",
));
}
// yeah, unless the user built a debug build hopefully for local testing only
if config.server_name == "your.server.name" && !cfg!(debug_assertions) {
return Err(Error::bad_config(
"You must specify a valid server name for production usage of conduwuit.",
));
}
if cfg!(debug_assertions) {
info!("Note: conduwuit was built without optimisations (i.e. debug build)");
}
// check if the user specified a registration token as `""`
if config.registration_token == Some(String::new()) {
return Err(Error::bad_config("Registration token was specified but is empty (\"\")"));
}
if config.max_request_size < 16384 {
return Err(Error::bad_config("Max request size is less than 16KB. Please increase it."));
}
// check if user specified valid IP CIDR ranges on startup
for cidr in &config.ip_range_denylist {
if let Err(e) = ipaddress::IPAddress::parse(cidr) {
error!("Error parsing specified IP CIDR range from string: {e}");
return Err(Error::bad_config("Error parsing specified IP CIDR ranges from strings"));
}
}
if config.allow_registration
&& !config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none()
{
return Err(Error::bad_config(
"!! You have `allow_registration` enabled without a token configured in your config which means you are \
allowing ANYONE to register on your conduwuit instance without any 2nd-step (e.g. registration token).\n
If this is not the intended behaviour, please set a registration token with the `registration_token` config option.\n
For security and safety reasons, conduwuit will shut down. If you are extra sure this is the desired behaviour you \
want, please set the following config option to true:
`yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`",
));
}
if config.allow_registration
&& config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none()
{
warn!(
"Open registration is enabled via setting \
`yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` and `allow_registration` to \
true without a registration token configured. You are expected to be aware of the risks now.\n
If this is not the desired behaviour, please set a registration token."
);
}
if config.allow_outgoing_presence && !config.allow_local_presence {
return Err(Error::bad_config(
"Outgoing presence requires allowing local presence. Please enable \"allow_local_presence\".",
));
}
if config
.url_preview_domain_contains_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_domain_contains_allowlist\" to \"*\". \
This opens up significant attack surface to your server. You are expected to be aware of the risks by \
doing this."
);
}
if config
.url_preview_domain_explicit_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_domain_explicit_allowlist\" to \"*\". \
This opens up significant attack surface to your server. You are expected to be aware of the risks by \
doing this."
);
}
if config
.url_preview_url_contains_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_url_contains_allowlist\" to \"*\". This \
opens up significant attack surface to your server. You are expected to be aware of the risks by doing \
this."
);
}
Ok(())
}
+430 -906
View File
File diff suppressed because it is too large Load Diff
+93 -98
View File
@@ -24,124 +24,119 @@ use crate::Result;
/// ## Include vs. Exclude /// ## Include vs. Exclude
/// If include is an empty list, it is assumed to be `["*"]`. /// If include is an empty list, it is assumed to be `["*"]`.
/// ///
/// If a domain matches both the exclude and include list, the proxy will only /// If a domain matches both the exclude and include list, the proxy will only be used if it was
/// be used if it was included because of a more specific rule than it was /// included because of a more specific rule than it was excluded. In the above example, the proxy
/// excluded. In the above example, the proxy would be used for /// would be used for `ordinary.onion`, `matrix.myspecial.onion`, but not `hello.myspecial.onion`.
/// `ordinary.onion`, `matrix.myspecial.onion`, but not `hello.myspecial.onion`.
#[derive(Clone, Default, Debug, Deserialize)] #[derive(Clone, Default, Debug, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum ProxyConfig { pub enum ProxyConfig {
#[default] #[default]
None, None,
Global { Global {
#[serde(deserialize_with = "crate::utils::deserialize_from_str")] #[serde(deserialize_with = "crate::utils::deserialize_from_str")]
url: Url, url: Url,
}, },
ByDomain(Vec<PartialProxyConfig>), ByDomain(Vec<PartialProxyConfig>),
} }
impl ProxyConfig { impl ProxyConfig {
pub fn to_proxy(&self) -> Result<Option<Proxy>> { pub fn to_proxy(&self) -> Result<Option<Proxy>> {
Ok(match self.clone() { Ok(match self.clone() {
ProxyConfig::None => None, ProxyConfig::None => None,
ProxyConfig::Global { ProxyConfig::Global { url } => Some(Proxy::all(url)?),
url, ProxyConfig::ByDomain(proxies) => Some(Proxy::custom(move |url| {
} => Some(Proxy::all(url)?), proxies.iter().find_map(|proxy| proxy.for_url(url)).cloned() // first matching proxy
ProxyConfig::ByDomain(proxies) => Some(Proxy::custom(move |url| { })),
proxies.iter().find_map(|proxy| proxy.for_url(url)).cloned() // first matching })
// proxy }
})),
})
}
} }
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
pub struct PartialProxyConfig { pub struct PartialProxyConfig {
#[serde(deserialize_with = "crate::utils::deserialize_from_str")] #[serde(deserialize_with = "crate::utils::deserialize_from_str")]
url: Url, url: Url,
#[serde(default)] #[serde(default)]
include: Vec<WildCardedDomain>, include: Vec<WildCardedDomain>,
#[serde(default)] #[serde(default)]
exclude: Vec<WildCardedDomain>, exclude: Vec<WildCardedDomain>,
} }
impl PartialProxyConfig { impl PartialProxyConfig {
pub fn for_url(&self, url: &Url) -> Option<&Url> { pub fn for_url(&self, url: &Url) -> Option<&Url> {
let domain = url.domain()?; let domain = url.domain()?;
let mut included_because = None; // most specific reason it was included let mut included_because = None; // most specific reason it was included
let mut excluded_because = None; // most specific reason it was excluded let mut excluded_because = None; // most specific reason it was excluded
if self.include.is_empty() { if self.include.is_empty() {
// treat empty include list as `*` // treat empty include list as `*`
included_because = Some(&WildCardedDomain::WildCard); included_because = Some(&WildCardedDomain::WildCard)
} }
for wc_domain in &self.include { for wc_domain in &self.include {
if wc_domain.matches(domain) { if wc_domain.matches(domain) {
match included_because { match included_because {
Some(prev) if !wc_domain.more_specific_than(prev) => (), Some(prev) if !wc_domain.more_specific_than(prev) => (),
_ => included_because = Some(wc_domain), _ => included_because = Some(wc_domain),
} }
} }
} }
for wc_domain in &self.exclude { for wc_domain in &self.exclude {
if wc_domain.matches(domain) { if wc_domain.matches(domain) {
match excluded_because { match excluded_because {
Some(prev) if !wc_domain.more_specific_than(prev) => (), Some(prev) if !wc_domain.more_specific_than(prev) => (),
_ => excluded_because = Some(wc_domain), _ => excluded_because = Some(wc_domain),
} }
} }
} }
match (included_because, excluded_because) { match (included_because, excluded_because) {
(Some(a), Some(b)) if a.more_specific_than(b) => Some(&self.url), /* included for a more specific reason */ (Some(a), Some(b)) if a.more_specific_than(b) => Some(&self.url), // included for a more specific reason than excluded
// than excluded (Some(_), None) => Some(&self.url),
(Some(_), None) => Some(&self.url), _ => None,
_ => None, }
} }
}
} }
/// A domain name, that optionally allows a * as its first subdomain. /// A domain name, that optionally allows a * as its first subdomain.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
enum WildCardedDomain { enum WildCardedDomain {
WildCard, WildCard,
WildCarded(String), WildCarded(String),
Exact(String), Exact(String),
} }
impl WildCardedDomain { impl WildCardedDomain {
fn matches(&self, domain: &str) -> bool { fn matches(&self, domain: &str) -> bool {
match self { match self {
WildCardedDomain::WildCard => true, WildCardedDomain::WildCard => true,
WildCardedDomain::WildCarded(d) => domain.ends_with(d), WildCardedDomain::WildCarded(d) => domain.ends_with(d),
WildCardedDomain::Exact(d) => domain == d, WildCardedDomain::Exact(d) => domain == d,
} }
} }
fn more_specific_than(&self, other: &Self) -> bool {
fn more_specific_than(&self, other: &Self) -> bool { match (self, other) {
match (self, other) { (WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false,
(WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false, (_, WildCardedDomain::WildCard) => true,
(_, WildCardedDomain::WildCard) => true, (WildCardedDomain::Exact(a), WildCardedDomain::WildCarded(_)) => other.matches(a),
(WildCardedDomain::Exact(a), WildCardedDomain::WildCarded(_)) => other.matches(a), (WildCardedDomain::WildCarded(a), WildCardedDomain::WildCarded(b)) => {
(WildCardedDomain::WildCarded(a), WildCardedDomain::WildCarded(b)) => a != b && a.ends_with(b), a != b && a.ends_with(b)
_ => false, }
} _ => false,
} }
}
} }
impl std::str::FromStr for WildCardedDomain { impl std::str::FromStr for WildCardedDomain {
type Err = std::convert::Infallible; type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
fn from_str(s: &str) -> Result<Self, Self::Err> { // maybe do some domain validation?
// maybe do some domain validation? Ok(if s.starts_with("*.") {
Ok(if s.starts_with("*.") { WildCardedDomain::WildCarded(s[1..].to_owned())
WildCardedDomain::WildCarded(s[1..].to_owned()) } else if s == "*" {
} else if s == "*" { WildCardedDomain::WildCarded("".to_owned())
WildCardedDomain::WildCarded(String::new()) } else {
} else { WildCardedDomain::Exact(s.to_owned())
WildCardedDomain::Exact(s.to_owned()) })
}) }
}
} }
impl<'de> Deserialize<'de> for WildCardedDomain { impl<'de> Deserialize<'de> for WildCardedDomain {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: serde::de::Deserializer<'de>, D: serde::de::Deserializer<'de>,
{ {
crate::utils::deserialize_from_str(deserializer) crate::utils::deserialize_from_str(deserializer)
} }
} }
+63
View File
@@ -0,0 +1,63 @@
use super::Config;
use crate::Result;
use std::{future::Future, pin::Pin, sync::Arc};
#[cfg(feature = "sqlite")]
pub mod sqlite;
#[cfg(feature = "rocksdb")]
pub(crate) mod rocksdb;
#[cfg(any(feature = "sqlite", feature = "rocksdb"))]
pub(crate) mod watchers;
pub(crate) trait KeyValueDatabaseEngine: Send + Sync {
fn open(config: &Config) -> Result<Self>
where
Self: Sized;
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>>;
fn flush(&self) -> Result<()>;
fn cleanup(&self) -> Result<()> {
Ok(())
}
fn memory_usage(&self) -> Result<String> {
Ok("Current database engine does not support memory usage reporting.".to_owned())
}
fn clear_caches(&self) {}
}
pub(crate) trait KvTree: Send + Sync {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>;
fn remove(&self, key: &[u8]) -> Result<()>;
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()>;
fn scan_prefix<'a>(
&'a self,
prefix: Vec<u8>,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
fn clear(&self) -> Result<()> {
for (key, _) in self.iter() {
self.remove(&key)?;
}
Ok(())
}
}
+282
View File
@@ -0,0 +1,282 @@
use super::{super::Config, watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{utils, Result};
use std::{
future::Future,
pin::Pin,
sync::{Arc, RwLock},
};
use rocksdb::LogLevel::{Debug, Error, Fatal, Info, Warn};
use tracing::{debug, info};
pub(crate) struct Engine {
rocks: rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>,
cache: rocksdb::Cache,
old_cfs: Vec<String>,
config: Config,
}
struct RocksDbEngineTree<'a> {
db: Arc<Engine>,
name: &'a str,
watchers: Watchers,
write_lock: RwLock<()>,
}
fn db_options(rocksdb_cache: &rocksdb::Cache, config: &Config) -> rocksdb::Options {
// block-based options: https://docs.rs/rocksdb/latest/rocksdb/struct.BlockBasedOptions.html#
let mut block_based_options = rocksdb::BlockBasedOptions::default();
block_based_options.set_block_cache(rocksdb_cache);
// "Difference of spinning disk"
// https://zhangyuchi.gitbooks.io/rocksdbbook/content/RocksDB-Tuning-Guide.html
block_based_options.set_block_size(64 * 1024);
block_based_options.set_cache_index_and_filter_blocks(true);
// database options: https://docs.rs/rocksdb/latest/rocksdb/struct.Options.html#
let mut db_opts = rocksdb::Options::default();
let rocksdb_log_level = match config.rocksdb_log_level.as_ref() {
"debug" => Debug,
"info" => Info,
"warn" => Warn,
"error" => Error,
"fatal" => Fatal,
_ => Warn,
};
db_opts.set_log_level(rocksdb_log_level);
db_opts.set_max_log_file_size(config.rocksdb_max_log_file_size);
db_opts.set_log_file_time_to_roll(config.rocksdb_log_time_to_roll);
if config.rocksdb_optimize_for_spinning_disks {
// useful for hard drives but on literally any half-decent SSD this is not useful
// and the benefits of improved compaction based on up to date stats are good.
// current conduwut users have NVMe/SSDs.
db_opts.set_skip_stats_update_on_db_open(true);
db_opts.set_compaction_readahead_size(2 * 1024 * 1024); // default compaction_readahead_size is 0 which is good for SSDs
db_opts.set_target_file_size_base(256 * 1024 * 1024); // default target_file_size is 64MB which is good for SSDs
db_opts.set_optimize_filters_for_hits(true); // doesn't really seem useful for fast storage
} else {
db_opts.set_skip_stats_update_on_db_open(false);
db_opts.set_max_bytes_for_level_base(512 * 1024 * 1024);
db_opts.set_use_direct_reads(true);
db_opts.set_use_direct_io_for_flush_and_compaction(true);
}
db_opts.set_block_based_table_factory(&block_based_options);
db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.create_if_missing(true);
db_opts.increase_parallelism(num_cpus::get() as i32);
//db_opts.set_max_open_files(config.rocksdb_max_open_files);
db_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
db_opts.optimize_level_style_compaction(10 * 1024 * 1024);
// https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
db_opts.set_max_background_jobs(6);
db_opts.set_bytes_per_sync(1048576);
// https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords
//
// Unclean shutdowns of a Matrix homeserver are likely to be fine when
// recovered in this manner as it's likely any lost information will be
// restored via federation.
db_opts.set_wal_recovery_mode(rocksdb::DBRecoveryMode::TolerateCorruptedTailRecords);
let prefix_extractor = rocksdb::SliceTransform::create_fixed_prefix(1);
db_opts.set_prefix_extractor(prefix_extractor);
db_opts
}
impl KeyValueDatabaseEngine for Arc<Engine> {
fn open(config: &Config) -> Result<Self> {
let cache_capacity_bytes = (config.db_cache_capacity_mb * 1024.0 * 1024.0) as usize;
let rocksdb_cache = rocksdb::Cache::new_lru_cache(cache_capacity_bytes);
let db_opts = db_options(&rocksdb_cache, config);
debug!("Listing column families in database");
let cfs = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::list_cf(
&db_opts,
&config.database_path,
)
.unwrap_or_default();
debug!("Opening column family descriptors in database");
info!("RocksDB database compaction will take place now, a delay in startup is expected");
let db = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::open_cf_descriptors(
&db_opts,
&config.database_path,
cfs.iter().map(|name| {
rocksdb::ColumnFamilyDescriptor::new(name, db_options(&rocksdb_cache, config))
}),
)?;
Ok(Arc::new(Engine {
rocks: db,
cache: rocksdb_cache,
old_cfs: cfs,
config: config.clone(),
}))
}
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>> {
if !self.old_cfs.contains(&name.to_owned()) {
// Create if it didn't exist
debug!("Creating new column family in database: {}", name);
let _ = self
.rocks
.create_cf(name, &db_options(&self.cache, &self.config));
}
Ok(Arc::new(RocksDbEngineTree {
name,
db: Arc::clone(self),
watchers: Watchers::default(),
write_lock: RwLock::new(()),
}))
}
fn flush(&self) -> Result<()> {
// TODO?
Ok(())
}
fn memory_usage(&self) -> Result<String> {
let stats =
rocksdb::perf::get_memory_usage_stats(Some(&[&self.rocks]), Some(&[&self.cache]))?;
Ok(format!(
"Approximate memory usage of all the mem-tables: {:.3} MB\n\
Approximate memory usage of un-flushed mem-tables: {:.3} MB\n\
Approximate memory usage of all the table readers: {:.3} MB\n\
Approximate memory usage by cache: {:.3} MB\n\
Approximate memory usage by cache pinned: {:.3} MB\n\
",
stats.mem_table_total as f64 / 1024.0 / 1024.0,
stats.mem_table_unflushed as f64 / 1024.0 / 1024.0,
stats.mem_table_readers_total as f64 / 1024.0 / 1024.0,
stats.cache_total as f64 / 1024.0 / 1024.0,
self.cache.get_pinned_usage() as f64 / 1024.0 / 1024.0,
))
}
fn clear_caches(&self) {}
}
impl RocksDbEngineTree<'_> {
fn cf(&self) -> Arc<rocksdb::BoundColumnFamily<'_>> {
self.db.rocks.cf_handle(self.name).unwrap()
}
}
impl KvTree for RocksDbEngineTree<'_> {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
Ok(self.db.rocks.get_cf(&self.cf(), key)?)
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
let lock = self.write_lock.read().unwrap();
self.db.rocks.put_cf(&self.cf(), key, value)?;
drop(lock);
self.watchers.wake(key);
Ok(())
}
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
for (key, value) in iter {
self.db.rocks.put_cf(&self.cf(), key, value)?;
}
Ok(())
}
fn remove(&self, key: &[u8]) -> Result<()> {
Ok(self.db.rocks.delete_cf(&self.cf(), key)?)
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
.iterator_cf(&self.cf(), rocksdb::IteratorMode::Start)
.map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
.iterator_cf(
&self.cf(),
rocksdb::IteratorMode::From(
from,
if backwards {
rocksdb::Direction::Reverse
} else {
rocksdb::Direction::Forward
},
),
)
.map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
let lock = self.write_lock.write().unwrap();
let old = self.db.rocks.get_cf(&self.cf(), key)?;
let new = utils::increment(old.as_deref()).unwrap();
self.db.rocks.put_cf(&self.cf(), key, &new)?;
drop(lock);
Ok(new)
}
fn increment_batch<'a>(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let lock = self.write_lock.write().unwrap();
for key in iter {
let old = self.db.rocks.get_cf(&self.cf(), &key)?;
let new = utils::increment(old.as_deref()).unwrap();
self.db.rocks.put_cf(&self.cf(), key, new)?;
}
drop(lock);
Ok(())
}
fn scan_prefix<'a>(
&'a self,
prefix: Vec<u8>,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new(
self.db
.rocks
.iterator_cf(
&self.cf(),
rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
)
.map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v)))
.take_while(move |(k, _)| k.starts_with(&prefix)),
)
}
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
self.watchers.watch(prefix)
}
}
+340
View File
@@ -0,0 +1,340 @@
use super::{watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{database::Config, Result};
use parking_lot::{Mutex, MutexGuard};
use rusqlite::{Connection, DatabaseName::Main, OptionalExtension};
use std::{
cell::RefCell,
future::Future,
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
};
use thread_local::ThreadLocal;
use tracing::debug;
thread_local! {
static READ_CONNECTION: RefCell<Option<&'static Connection>> = RefCell::new(None);
static READ_CONNECTION_ITERATOR: RefCell<Option<&'static Connection>> = RefCell::new(None);
}
struct PreparedStatementIterator<'a> {
pub iterator: Box<dyn Iterator<Item = TupleOfBytes> + 'a>,
pub _statement_ref: NonAliasingBox<rusqlite::Statement<'a>>,
}
impl Iterator for PreparedStatementIterator<'_> {
type Item = TupleOfBytes;
fn next(&mut self) -> Option<Self::Item> {
self.iterator.next()
}
}
struct NonAliasingBox<T>(*mut T);
impl<T> Drop for NonAliasingBox<T> {
fn drop(&mut self) {
unsafe {
let _ = Box::from_raw(self.0);
};
}
}
pub struct Engine {
writer: Mutex<Connection>,
read_conn_tls: ThreadLocal<Connection>,
read_iterator_conn_tls: ThreadLocal<Connection>,
path: PathBuf,
cache_size_per_thread: u32,
}
impl Engine {
fn prepare_conn(path: &Path, cache_size_kb: u32) -> Result<Connection> {
let conn = Connection::open(path)?;
conn.pragma_update(Some(Main), "page_size", 2048)?;
conn.pragma_update(Some(Main), "journal_mode", "WAL")?;
conn.pragma_update(Some(Main), "synchronous", "NORMAL")?;
conn.pragma_update(Some(Main), "cache_size", -i64::from(cache_size_kb))?;
conn.pragma_update(Some(Main), "wal_autocheckpoint", 0)?;
Ok(conn)
}
fn write_lock(&self) -> MutexGuard<'_, Connection> {
self.writer.lock()
}
fn read_lock(&self) -> &Connection {
self.read_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
}
fn read_lock_iterator(&self) -> &Connection {
self.read_iterator_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
}
pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
self.write_lock()
.pragma_update(Some(Main), "wal_checkpoint", "RESTART")?;
Ok(())
}
}
impl KeyValueDatabaseEngine for Arc<Engine> {
fn open(config: &Config) -> Result<Self> {
let path = Path::new(&config.database_path).join("conduit.db");
// calculates cache-size per permanent connection
// 1. convert MB to KiB
// 2. divide by permanent connections + permanent iter connections + write connection
// 3. round down to nearest integer
let cache_size_per_thread: u32 = ((config.db_cache_capacity_mb * 1024.0)
/ ((num_cpus::get().max(1) * 2) + 1) as f64)
as u32;
let writer = Mutex::new(Engine::prepare_conn(&path, cache_size_per_thread)?);
let arc = Arc::new(Engine {
writer,
read_conn_tls: ThreadLocal::new(),
read_iterator_conn_tls: ThreadLocal::new(),
path,
cache_size_per_thread,
});
Ok(arc)
}
fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> {
self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {name} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )"), [])?;
Ok(Arc::new(SqliteTable {
engine: Arc::clone(self),
name: name.to_owned(),
watchers: Watchers::default(),
}))
}
fn flush(&self) -> Result<()> {
// we enabled PRAGMA synchronous=normal, so this should not be necessary
Ok(())
}
fn cleanup(&self) -> Result<()> {
self.flush_wal()
}
}
pub struct SqliteTable {
engine: Arc<Engine>,
name: String,
watchers: Watchers,
}
type TupleOfBytes = (Vec<u8>, Vec<u8>);
impl SqliteTable {
fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> {
Ok(guard
.prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())?
.query_row([key], |row| row.get(0))
.optional()?)
}
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
guard.execute(
format!(
"INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)",
self.name
)
.as_str(),
[key, value],
)?;
Ok(())
}
pub fn iter_with_guard<'a>(
&'a self,
guard: &'a Connection,
) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
let statement = Box::leak(Box::new(
guard
.prepare(&format!(
"SELECT key, value FROM {} ORDER BY key ASC",
&self.name
))
.unwrap(),
));
let statement_ref = NonAliasingBox(statement);
//let name = self.name.clone();
let iterator = Box::new(
statement
.query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(move |r| r.unwrap()),
);
Box::new(PreparedStatementIterator {
iterator,
_statement_ref: statement_ref,
})
}
}
impl KvTree for SqliteTable {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
self.get_with_guard(self.engine.read_lock(), key)
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
let guard = self.engine.write_lock();
self.insert_with_guard(&guard, key, value)?;
drop(guard);
self.watchers.wake(key);
Ok(())
}
fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
let guard = self.engine.write_lock();
guard.execute("BEGIN", [])?;
for (key, value) in iter {
self.insert_with_guard(&guard, &key, &value)?;
}
guard.execute("COMMIT", [])?;
drop(guard);
Ok(())
}
fn increment_batch<'a>(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let guard = self.engine.write_lock();
guard.execute("BEGIN", [])?;
for key in iter {
let old = self.get_with_guard(&guard, &key)?;
let new = crate::utils::increment(old.as_deref())
.expect("utils::increment always returns Some");
self.insert_with_guard(&guard, &key, &new)?;
}
guard.execute("COMMIT", [])?;
drop(guard);
Ok(())
}
fn remove(&self, key: &[u8]) -> Result<()> {
let guard = self.engine.write_lock();
guard.execute(
format!("DELETE FROM {} WHERE key = ?", self.name).as_str(),
[key],
)?;
Ok(())
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
let guard = self.engine.read_lock_iterator();
self.iter_with_guard(guard)
}
fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
let guard = self.engine.read_lock_iterator();
let from = from.to_vec(); // TODO change interface?
//let name = self.name.clone();
if backwards {
let statement = Box::leak(Box::new(
guard
.prepare(&format!(
"SELECT key, value FROM {} WHERE key <= ? ORDER BY key DESC",
&self.name
))
.unwrap(),
));
let statement_ref = NonAliasingBox(statement);
let iterator = Box::new(
statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(move |r| r.unwrap()),
);
Box::new(PreparedStatementIterator {
iterator,
_statement_ref: statement_ref,
})
} else {
let statement = Box::leak(Box::new(
guard
.prepare(&format!(
"SELECT key, value FROM {} WHERE key >= ? ORDER BY key ASC",
&self.name
))
.unwrap(),
));
let statement_ref = NonAliasingBox(statement);
let iterator = Box::new(
statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(move |r| r.unwrap()),
);
Box::new(PreparedStatementIterator {
iterator,
_statement_ref: statement_ref,
})
}
}
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
let guard = self.engine.write_lock();
let old = self.get_with_guard(&guard, key)?;
let new =
crate::utils::increment(old.as_deref()).expect("utils::increment always returns Some");
self.insert_with_guard(&guard, key, &new)?;
Ok(new)
}
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
Box::new(
self.iter_from(&prefix, false)
.take_while(move |(key, _)| key.starts_with(&prefix)),
)
}
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
self.watchers.watch(prefix)
}
fn clear(&self) -> Result<()> {
debug!("clear: running");
self.engine
.write_lock()
.execute(format!("DELETE FROM {}", self.name).as_str(), [])?;
debug!("clear: ran");
Ok(())
}
}
+56
View File
@@ -0,0 +1,56 @@
use std::{
collections::{hash_map, HashMap},
future::Future,
pin::Pin,
sync::RwLock,
};
use tokio::sync::watch;
type Watcher = RwLock<HashMap<Vec<u8>, (watch::Sender<()>, watch::Receiver<()>)>>;
#[derive(Default)]
pub(super) struct Watchers {
watchers: Watcher,
}
impl Watchers {
pub(super) fn watch<'a>(
&'a self,
prefix: &[u8],
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
let mut rx = match self.watchers.write().unwrap().entry(prefix.to_vec()) {
hash_map::Entry::Occupied(o) => o.get().1.clone(),
hash_map::Entry::Vacant(v) => {
let (tx, rx) = tokio::sync::watch::channel(());
v.insert((tx, rx.clone()));
rx
}
};
Box::pin(async move {
// Tx is never destroyed
rx.changed().await.unwrap();
})
}
pub(super) fn wake(&self, key: &[u8]) {
let watchers = self.watchers.read().unwrap();
let mut triggered = Vec::new();
for length in 0..=key.len() {
if watchers.contains_key(&key[..length]) {
triggered.push(&key[..length]);
}
}
drop(watchers);
if !triggered.is_empty() {
let mut watchers = self.watchers.write().unwrap();
for prefix in triggered {
if let Some(tx) = watchers.remove(prefix) {
let _ = tx.0.send(());
}
}
};
}
}
-32
View File
@@ -1,32 +0,0 @@
use std::sync::Arc;
use super::KeyValueDatabaseEngine;
pub struct Cork {
db: Arc<dyn KeyValueDatabaseEngine>,
flush: bool,
sync: bool,
}
impl Cork {
pub(crate) fn new(db: &Arc<dyn KeyValueDatabaseEngine>, flush: bool, sync: bool) -> Self {
db.cork().unwrap();
Cork {
db: db.clone(),
flush,
sync,
}
}
}
impl Drop for Cork {
fn drop(&mut self) {
self.db.uncork().ok();
if self.flush {
self.db.flush().ok();
}
if self.sync {
self.db.sync().ok();
}
}
}
+123 -112
View File
@@ -1,137 +1,148 @@
use std::collections::HashMap; use std::collections::HashMap;
use ruma::{ use ruma::{
api::client::error::ErrorKind, api::client::error::ErrorKind,
events::{AnyEphemeralRoomEvent, RoomAccountDataEventType}, events::{AnyEphemeralRoomEvent, RoomAccountDataEventType},
serde::Raw, serde::Raw,
RoomId, UserId, RoomId, UserId,
}; };
use tracing::warn; use tracing::warn;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::account_data::Data for KeyValueDatabase { impl service::account_data::Data for KeyValueDatabase {
/// Places one event in the account data of the user and removes the /// Places one event in the account data of the user and removes the previous entry.
/// previous entry. #[tracing::instrument(skip(self, room_id, user_id, event_type, data))]
#[tracing::instrument(skip(self, room_id, user_id, event_type, data))] fn update(
fn update( &self,
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType, room_id: Option<&RoomId>,
data: &serde_json::Value, user_id: &UserId,
) -> Result<()> { event_type: RoomAccountDataEventType,
let mut prefix = room_id data: &serde_json::Value,
.map(ToString::to_string) ) -> Result<()> {
.unwrap_or_default() let mut prefix = room_id
.as_bytes() .map(|r| r.to_string())
.to_vec(); .unwrap_or_default()
prefix.push(0xFF); .as_bytes()
prefix.extend_from_slice(user_id.as_bytes()); .to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xff);
let mut roomuserdataid = prefix.clone(); let mut roomuserdataid = prefix.clone();
roomuserdataid.extend_from_slice(&services().globals.next_count()?.to_be_bytes()); roomuserdataid.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
roomuserdataid.push(0xFF); roomuserdataid.push(0xff);
roomuserdataid.extend_from_slice(event_type.to_string().as_bytes()); roomuserdataid.extend_from_slice(event_type.to_string().as_bytes());
let mut key = prefix; let mut key = prefix;
key.extend_from_slice(event_type.to_string().as_bytes()); key.extend_from_slice(event_type.to_string().as_bytes());
if data.get("type").is_none() || data.get("content").is_none() { if data.get("type").is_none() || data.get("content").is_none() {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Account data doesn't have all required fields.", "Account data doesn't have all required fields.",
)); ));
} }
self.roomuserdataid_accountdata.insert( self.roomuserdataid_accountdata.insert(
&roomuserdataid, &roomuserdataid,
&serde_json::to_vec(&data).expect("to_vec always works on json values"), &serde_json::to_vec(&data).expect("to_vec always works on json values"),
)?; )?;
let prev = self.roomusertype_roomuserdataid.get(&key)?; let prev = self.roomusertype_roomuserdataid.get(&key)?;
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.insert(&key, &roomuserdataid)?; .insert(&key, &roomuserdataid)?;
// Remove old entry // Remove old entry
if let Some(prev) = prev { if let Some(prev) = prev {
self.roomuserdataid_accountdata.remove(&prev)?; self.roomuserdataid_accountdata.remove(&prev)?;
} }
Ok(()) Ok(())
} }
/// Searches the account data for a specific kind. /// Searches the account data for a specific kind.
#[tracing::instrument(skip(self, room_id, user_id, kind))] #[tracing::instrument(skip(self, room_id, user_id, kind))]
fn get( fn get(
&self, room_id: Option<&RoomId>, user_id: &UserId, kind: RoomAccountDataEventType, &self,
) -> Result<Option<Box<serde_json::value::RawValue>>> { room_id: Option<&RoomId>,
let mut key = room_id user_id: &UserId,
.map(ToString::to_string) kind: RoomAccountDataEventType,
.unwrap_or_default() ) -> Result<Option<Box<serde_json::value::RawValue>>> {
.as_bytes() let mut key = room_id
.to_vec(); .map(|r| r.to_string())
key.push(0xFF); .unwrap_or_default()
key.extend_from_slice(user_id.as_bytes()); .as_bytes()
key.push(0xFF); .to_vec();
key.extend_from_slice(kind.to_string().as_bytes()); key.push(0xff);
key.extend_from_slice(user_id.as_bytes());
key.push(0xff);
key.extend_from_slice(kind.to_string().as_bytes());
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.get(&key)? .get(&key)?
.and_then(|roomuserdataid| { .and_then(|roomuserdataid| {
self.roomuserdataid_accountdata self.roomuserdataid_accountdata
.get(&roomuserdataid) .get(&roomuserdataid)
.transpose() .transpose()
}) })
.transpose()? .transpose()?
.map(|data| serde_json::from_slice(&data).map_err(|_| Error::bad_database("could not deserialize"))) .map(|data| {
.transpose() serde_json::from_slice(&data)
} .map_err(|_| Error::bad_database("could not deserialize"))
})
.transpose()
}
/// Returns all changes to the account data that happened after `since`. /// Returns all changes to the account data that happened after `since`.
#[tracing::instrument(skip(self, room_id, user_id, since))] #[tracing::instrument(skip(self, room_id, user_id, since))]
fn changes_since( fn changes_since(
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64, &self,
) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> { room_id: Option<&RoomId>,
let mut userdata = HashMap::new(); user_id: &UserId,
since: u64,
) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> {
let mut userdata = HashMap::new();
let mut prefix = room_id let mut prefix = room_id
.map(ToString::to_string) .map(|r| r.to_string())
.unwrap_or_default() .unwrap_or_default()
.as_bytes() .as_bytes()
.to_vec(); .to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(user_id.as_bytes()); prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
// Skip the data that's exactly at since, because we sent that last time // Skip the data that's exactly at since, because we sent that last time
let mut first_possible = prefix.clone(); let mut first_possible = prefix.clone();
first_possible.extend_from_slice(&(since + 1).to_be_bytes()); first_possible.extend_from_slice(&(since + 1).to_be_bytes());
for r in self for r in self
.roomuserdataid_accountdata .roomuserdataid_accountdata
.iter_from(&first_possible, false) .iter_from(&first_possible, false)
.take_while(move |(k, _)| k.starts_with(&prefix)) .take_while(move |(k, _)| k.starts_with(&prefix))
.map(|(k, v)| { .map(|(k, v)| {
Ok::<_, Error>(( Ok::<_, Error>((
RoomAccountDataEventType::from( RoomAccountDataEventType::from(
utils::string_from_bytes( utils::string_from_bytes(k.rsplit(|&b| b == 0xff).next().ok_or_else(
k.rsplit(|&b| b == 0xFF) || Error::bad_database("RoomUserData ID in db is invalid."),
.next() )?)
.ok_or_else(|| Error::bad_database("RoomUserData ID in db is invalid."))?, .map_err(|e| {
) warn!("RoomUserData ID in database is invalid: {}", e);
.map_err(|e| { Error::bad_database("RoomUserData ID in db is invalid.")
warn!("RoomUserData ID in database is invalid: {}", e); })?,
Error::bad_database("RoomUserData ID in db is invalid.") ),
})?, serde_json::from_slice::<Raw<AnyEphemeralRoomEvent>>(&v).map_err(|_| {
), Error::bad_database("Database contains invalid account data.")
serde_json::from_slice::<Raw<AnyEphemeralRoomEvent>>(&v) })?,
.map_err(|_| Error::bad_database("Database contains invalid account data."))?, ))
)) })
}) { {
let (kind, data) = r?; let (kind, data) = r?;
userdata.insert(kind, data); userdata.insert(kind, data);
} }
Ok(userdata) Ok(userdata)
} }
} }
+69 -44
View File
@@ -3,53 +3,78 @@ use ruma::api::appservice::Registration;
use crate::{database::KeyValueDatabase, service, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, utils, Error, Result};
impl service::appservice::Data for KeyValueDatabase { impl service::appservice::Data for KeyValueDatabase {
/// Registers an appservice and returns the ID to the caller /// Registers an appservice and returns the ID to the caller
fn register_appservice(&self, yaml: Registration) -> Result<String> { fn register_appservice(&self, yaml: Registration) -> Result<String> {
let id = yaml.id.as_str(); let id = yaml.id.as_str();
self.id_appserviceregistrations self.id_appserviceregistrations.insert(
.insert(id.as_bytes(), serde_yaml::to_string(&yaml).unwrap().as_bytes())?; id.as_bytes(),
serde_yaml::to_string(&yaml).unwrap().as_bytes(),
)?;
self.cached_registrations
.write()
.unwrap()
.insert(id.to_owned(), yaml.to_owned());
Ok(id.to_owned()) Ok(id.to_owned())
} }
/// Remove an appservice registration /// Remove an appservice registration
/// ///
/// # Arguments /// # Arguments
/// ///
/// * `service_name` - the name you send to register the service previously /// * `service_name` - the name you send to register the service previously
fn unregister_appservice(&self, service_name: &str) -> Result<()> { fn unregister_appservice(&self, service_name: &str) -> Result<()> {
self.id_appserviceregistrations self.id_appserviceregistrations
.remove(service_name.as_bytes())?; .remove(service_name.as_bytes())?;
Ok(()) self.cached_registrations
} .write()
.unwrap()
.remove(service_name);
Ok(())
}
fn get_registration(&self, id: &str) -> Result<Option<Registration>> { fn get_registration(&self, id: &str) -> Result<Option<Registration>> {
self.id_appserviceregistrations self.cached_registrations
.get(id.as_bytes())? .read()
.map(|bytes| { .unwrap()
serde_yaml::from_slice(&bytes) .get(id)
.map_err(|_| Error::bad_database("Invalid registration bytes in id_appserviceregistrations.")) .map_or_else(
}) || {
.transpose() self.id_appserviceregistrations
} .get(id.as_bytes())?
.map(|bytes| {
serde_yaml::from_slice(&bytes).map_err(|_| {
Error::bad_database(
"Invalid registration bytes in id_appserviceregistrations.",
)
})
})
.transpose()
},
|r| Ok(Some(r.clone())),
)
}
fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> { fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> {
Ok(Box::new(self.id_appserviceregistrations.iter().map(|(id, _)| { Ok(Box::new(self.id_appserviceregistrations.iter().map(
utils::string_from_bytes(&id) |(id, _)| {
.map_err(|_| Error::bad_database("Invalid id bytes in id_appserviceregistrations.")) utils::string_from_bytes(&id).map_err(|_| {
}))) Error::bad_database("Invalid id bytes in id_appserviceregistrations.")
} })
},
)))
}
fn all(&self) -> Result<Vec<(String, Registration)>> { fn all(&self) -> Result<Vec<(String, Registration)>> {
self.iter_ids()? self.iter_ids()?
.filter_map(Result::ok) .filter_map(|id| id.ok())
.map(move |id| { .map(move |id| {
Ok(( Ok((
id.clone(), id.clone(),
self.get_registration(&id)? self.get_registration(&id)?
.expect("iter_ids only returns appservices that exist"), .expect("iter_ids only returns appservices that exist"),
)) ))
}) })
.collect() .collect()
} }
} }
+253 -243
View File
@@ -4,298 +4,308 @@ use async_trait::async_trait;
use futures_util::{stream::FuturesUnordered, StreamExt}; use futures_util::{stream::FuturesUnordered, StreamExt};
use lru_cache::LruCache; use lru_cache::LruCache;
use ruma::{ use ruma::{
api::federation::discovery::{ServerSigningKeys, VerifyKey}, api::federation::discovery::{ServerSigningKeys, VerifyKey},
signatures::Ed25519KeyPair, signatures::Ed25519KeyPair,
DeviceId, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName, UserId, DeviceId, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName, UserId,
}; };
use crate::{ use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
database::{Cork, KeyValueDatabase},
service, services, utils, Error, Result,
};
const COUNTER: &[u8] = b"c"; const COUNTER: &[u8] = b"c";
const LAST_CHECK_FOR_UPDATES_COUNT: &[u8] = b"u"; const LAST_CHECK_FOR_UPDATES_COUNT: &[u8] = b"u";
#[async_trait] #[async_trait]
impl service::globals::Data for KeyValueDatabase { impl service::globals::Data for KeyValueDatabase {
fn next_count(&self) -> Result<u64> { fn next_count(&self) -> Result<u64> {
utils::u64_from_bytes(&self.global.increment(COUNTER)?) utils::u64_from_bytes(&self.global.increment(COUNTER)?)
.map_err(|_| Error::bad_database("Count has invalid bytes.")) .map_err(|_| Error::bad_database("Count has invalid bytes."))
} }
fn current_count(&self) -> Result<u64> { fn current_count(&self) -> Result<u64> {
self.global.get(COUNTER)?.map_or(Ok(0_u64), |bytes| { self.global.get(COUNTER)?.map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Count has invalid bytes.")) utils::u64_from_bytes(&bytes)
}) .map_err(|_| Error::bad_database("Count has invalid bytes."))
} })
}
fn last_check_for_updates_id(&self) -> Result<u64> { fn last_check_for_updates_id(&self) -> Result<u64> {
self.global self.global
.get(LAST_CHECK_FOR_UPDATES_COUNT)? .get(LAST_CHECK_FOR_UPDATES_COUNT)?
.map_or(Ok(0_u64), |bytes| { .map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("last check for updates count has invalid bytes.")) Error::bad_database("last check for updates count has invalid bytes.")
}) })
} })
}
fn update_check_for_updates_id(&self, id: u64) -> Result<()> { fn update_check_for_updates_id(&self, id: u64) -> Result<()> {
self.global self.global
.insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?; .insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?;
Ok(()) Ok(())
} }
#[allow(unused_qualifications)] // async traits async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> { let userid_bytes = user_id.as_bytes().to_vec();
let userid_bytes = user_id.as_bytes().to_vec(); let mut userid_prefix = userid_bytes.clone();
let mut userid_prefix = userid_bytes.clone(); userid_prefix.push(0xff);
userid_prefix.push(0xFF);
let mut userdeviceid_prefix = userid_prefix.clone(); let mut userdeviceid_prefix = userid_prefix.clone();
userdeviceid_prefix.extend_from_slice(device_id.as_bytes()); userdeviceid_prefix.extend_from_slice(device_id.as_bytes());
userdeviceid_prefix.push(0xFF); userdeviceid_prefix.push(0xff);
let mut futures = FuturesUnordered::new(); let mut futures = FuturesUnordered::new();
// Return when *any* user changed their key // Return when *any* user changed their key
// TODO: only send for user they share a room with // TODO: only send for user they share a room with
futures.push(self.todeviceid_events.watch_prefix(&userdeviceid_prefix)); futures.push(self.todeviceid_events.watch_prefix(&userdeviceid_prefix));
futures.push(self.userroomid_joined.watch_prefix(&userid_prefix)); futures.push(self.userroomid_joined.watch_prefix(&userid_prefix));
futures.push(self.userroomid_invitestate.watch_prefix(&userid_prefix)); futures.push(self.userroomid_invitestate.watch_prefix(&userid_prefix));
futures.push(self.userroomid_leftstate.watch_prefix(&userid_prefix)); futures.push(self.userroomid_leftstate.watch_prefix(&userid_prefix));
futures.push( futures.push(
self.userroomid_notificationcount self.userroomid_notificationcount
.watch_prefix(&userid_prefix), .watch_prefix(&userid_prefix),
); );
futures.push(self.userroomid_highlightcount.watch_prefix(&userid_prefix)); futures.push(self.userroomid_highlightcount.watch_prefix(&userid_prefix));
// Events for rooms we are in // Events for rooms we are in
for room_id in services() for room_id in services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(user_id) .rooms_joined(user_id)
.filter_map(Result::ok) .filter_map(|r| r.ok())
{ {
let short_roomid = services() let short_roomid = services()
.rooms .rooms
.short .short
.get_shortroomid(&room_id) .get_shortroomid(&room_id)
.ok() .ok()
.flatten() .flatten()
.expect("room exists") .expect("room exists")
.to_be_bytes() .to_be_bytes()
.to_vec(); .to_vec();
let roomid_bytes = room_id.as_bytes().to_vec(); let roomid_bytes = room_id.as_bytes().to_vec();
let mut roomid_prefix = roomid_bytes.clone(); let mut roomid_prefix = roomid_bytes.clone();
roomid_prefix.push(0xFF); roomid_prefix.push(0xff);
// PDUs // PDUs
futures.push(self.pduid_pdu.watch_prefix(&short_roomid)); futures.push(self.pduid_pdu.watch_prefix(&short_roomid));
// EDUs // EDUs
futures.push(Box::pin(async move { futures.push(self.roomid_lasttypingupdate.watch_prefix(&roomid_bytes));
let _result = services().rooms.typing.wait_for_update(&room_id).await;
}));
futures.push(self.readreceiptid_readreceipt.watch_prefix(&roomid_prefix)); futures.push(self.readreceiptid_readreceipt.watch_prefix(&roomid_prefix));
// Key changes // Key changes
futures.push(self.keychangeid_userid.watch_prefix(&roomid_prefix)); futures.push(self.keychangeid_userid.watch_prefix(&roomid_prefix));
// Room account data // Room account data
let mut roomuser_prefix = roomid_prefix.clone(); let mut roomuser_prefix = roomid_prefix.clone();
roomuser_prefix.extend_from_slice(&userid_prefix); roomuser_prefix.extend_from_slice(&userid_prefix);
futures.push( futures.push(
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.watch_prefix(&roomuser_prefix), .watch_prefix(&roomuser_prefix),
); );
} }
let mut globaluserdata_prefix = vec![0xFF]; let mut globaluserdata_prefix = vec![0xff];
globaluserdata_prefix.extend_from_slice(&userid_prefix); globaluserdata_prefix.extend_from_slice(&userid_prefix);
futures.push( futures.push(
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.watch_prefix(&globaluserdata_prefix), .watch_prefix(&globaluserdata_prefix),
); );
// More key changes (used when user is not joined to any rooms) // More key changes (used when user is not joined to any rooms)
futures.push(self.keychangeid_userid.watch_prefix(&userid_prefix)); futures.push(self.keychangeid_userid.watch_prefix(&userid_prefix));
// One time keys // One time keys
futures.push(self.userid_lastonetimekeyupdate.watch_prefix(&userid_bytes)); futures.push(self.userid_lastonetimekeyupdate.watch_prefix(&userid_bytes));
futures.push(Box::pin(services().globals.rotate.watch())); futures.push(Box::pin(services().globals.rotate.watch()));
// Wait until one of them finds something // Wait until one of them finds something
futures.next().await; futures.next().await;
Ok(()) Ok(())
} }
fn cleanup(&self) -> Result<()> { self.db.cleanup() } fn cleanup(&self) -> Result<()> {
self._db.cleanup()
}
fn flush(&self) -> Result<()> { self.db.flush() } fn memory_usage(&self) -> String {
let pdu_cache = self.pdu_cache.lock().unwrap().len();
let shorteventid_cache = self.shorteventid_cache.lock().unwrap().len();
let auth_chain_cache = self.auth_chain_cache.lock().unwrap().len();
let eventidshort_cache = self.eventidshort_cache.lock().unwrap().len();
let statekeyshort_cache = self.statekeyshort_cache.lock().unwrap().len();
let our_real_users_cache = self.our_real_users_cache.read().unwrap().len();
let appservice_in_room_cache = self.appservice_in_room_cache.read().unwrap().len();
let lasttimelinecount_cache = self.lasttimelinecount_cache.lock().unwrap().len();
fn cork(&self) -> Result<Cork> { Ok(Cork::new(&self.db, false, false)) } let mut response = format!(
"\
pdu_cache: {pdu_cache}
shorteventid_cache: {shorteventid_cache}
auth_chain_cache: {auth_chain_cache}
eventidshort_cache: {eventidshort_cache}
statekeyshort_cache: {statekeyshort_cache}
our_real_users_cache: {our_real_users_cache}
appservice_in_room_cache: {appservice_in_room_cache}
lasttimelinecount_cache: {lasttimelinecount_cache}\n"
);
if let Ok(db_stats) = self._db.memory_usage() {
response += &db_stats;
}
fn cork_and_flush(&self) -> Result<Cork> { Ok(Cork::new(&self.db, true, false)) } response
}
fn cork_and_sync(&self) -> Result<Cork> { Ok(Cork::new(&self.db, true, true)) } fn clear_caches(&self, amount: u32) {
if amount > 0 {
let c = &mut *self.pdu_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 1 {
let c = &mut *self.shorteventid_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 2 {
let c = &mut *self.auth_chain_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 3 {
let c = &mut *self.eventidshort_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 4 {
let c = &mut *self.statekeyshort_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 5 {
let c = &mut *self.our_real_users_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 6 {
let c = &mut *self.appservice_in_room_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 7 {
let c = &mut *self.lasttimelinecount_cache.lock().unwrap();
*c = HashMap::new();
}
}
fn memory_usage(&self) -> String { fn load_keypair(&self) -> Result<Ed25519KeyPair> {
let auth_chain_cache = self.auth_chain_cache.lock().unwrap().len(); let keypair_bytes = self.global.get(b"keypair")?.map_or_else(
let our_real_users_cache = self.our_real_users_cache.read().unwrap().len(); || {
let appservice_in_room_cache = self.appservice_in_room_cache.read().unwrap().len(); let keypair = utils::generate_keypair();
let lasttimelinecount_cache = self.lasttimelinecount_cache.lock().unwrap().len(); self.global.insert(b"keypair", &keypair)?;
Ok::<_, Error>(keypair)
},
|s| Ok(s.to_vec()),
)?;
let max_auth_chain_cache = self.auth_chain_cache.lock().unwrap().capacity(); let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff);
let max_our_real_users_cache = self.our_real_users_cache.read().unwrap().capacity();
let max_appservice_in_room_cache = self.appservice_in_room_cache.read().unwrap().capacity();
let max_lasttimelinecount_cache = self.lasttimelinecount_cache.lock().unwrap().capacity();
let mut response = format!( utils::string_from_bytes(
"\ // 1. version
auth_chain_cache: {auth_chain_cache} / {max_auth_chain_cache} parts
our_real_users_cache: {our_real_users_cache} / {max_our_real_users_cache} .next()
appservice_in_room_cache: {appservice_in_room_cache} / {max_appservice_in_room_cache} .expect("splitn always returns at least one element"),
lasttimelinecount_cache: {lasttimelinecount_cache} / {max_lasttimelinecount_cache}\n\n" )
); .map_err(|_| Error::bad_database("Invalid version bytes in keypair."))
if let Ok(db_stats) = self.db.memory_usage() { .and_then(|version| {
response += &db_stats; // 2. key
} parts
.next()
.ok_or_else(|| Error::bad_database("Invalid keypair format in database."))
.map(|key| (version, key))
})
.and_then(|(version, key)| {
Ed25519KeyPair::from_der(key, version)
.map_err(|_| Error::bad_database("Private or public keys are invalid."))
})
}
fn remove_keypair(&self) -> Result<()> {
self.global.remove(b"keypair")
}
response fn add_signing_key(
} &self,
origin: &ServerName,
new_keys: ServerSigningKeys,
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
fn clear_caches(&self, amount: u32) { let mut keys = signingkeys
if amount > 1 { .and_then(|keys| serde_json::from_slice(&keys).ok())
let c = &mut *self.auth_chain_cache.lock().unwrap(); .unwrap_or_else(|| {
*c = LruCache::new(c.capacity()); // Just insert "now", it doesn't matter
} ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now())
if amount > 2 { });
let c = &mut *self.our_real_users_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 3 {
let c = &mut *self.appservice_in_room_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 4 {
let c = &mut *self.lasttimelinecount_cache.lock().unwrap();
*c = HashMap::new();
}
}
fn load_keypair(&self) -> Result<Ed25519KeyPair> { let ServerSigningKeys {
let keypair_bytes = self.global.get(b"keypair")?.map_or_else( verify_keys,
|| { old_verify_keys,
let keypair = utils::generate_keypair(); ..
self.global.insert(b"keypair", &keypair)?; } = new_keys;
Ok::<_, Error>(keypair)
},
Ok,
)?;
let mut parts = keypair_bytes.splitn(2, |&b| b == 0xFF); keys.verify_keys.extend(verify_keys);
keys.old_verify_keys.extend(old_verify_keys);
utils::string_from_bytes( self.server_signingkeys.insert(
// 1. version origin.as_bytes(),
parts &serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"),
.next() )?;
.expect("splitn always returns at least one element"),
)
.map_err(|_| Error::bad_database("Invalid version bytes in keypair."))
.and_then(|version| {
// 2. key
parts
.next()
.ok_or_else(|| Error::bad_database("Invalid keypair format in database."))
.map(|key| (version, key))
})
.and_then(|(version, key)| {
Ed25519KeyPair::from_der(key, version)
.map_err(|_| Error::bad_database("Private or public keys are invalid."))
})
}
fn remove_keypair(&self) -> Result<()> { self.global.remove(b"keypair") } let mut tree = keys.verify_keys;
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
fn add_signing_key( Ok(tree)
&self, origin: &ServerName, new_keys: ServerSigningKeys, }
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
let mut keys = signingkeys /// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found for the server.
.and_then(|keys| serde_json::from_slice(&keys).ok()) fn signing_keys_for(
.unwrap_or_else(|| { &self,
// Just insert "now", it doesn't matter origin: &ServerName,
ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now()) ) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
}); let signingkeys = self
.server_signingkeys
.get(origin.as_bytes())?
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.map(|keys: ServerSigningKeys| {
let mut tree = keys.verify_keys;
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
tree
})
.unwrap_or_else(BTreeMap::new);
let ServerSigningKeys { Ok(signingkeys)
verify_keys, }
old_verify_keys,
..
} = new_keys;
keys.verify_keys.extend(verify_keys); fn database_version(&self) -> Result<u64> {
keys.old_verify_keys.extend(old_verify_keys); self.global.get(b"version")?.map_or(Ok(0), |version| {
utils::u64_from_bytes(&version)
.map_err(|_| Error::bad_database("Database version id is invalid."))
})
}
self.server_signingkeys.insert( fn bump_database_version(&self, new_version: u64) -> Result<()> {
origin.as_bytes(), self.global.insert(b"version", &new_version.to_be_bytes())?;
&serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"), Ok(())
)?; }
let mut tree = keys.verify_keys;
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
Ok(tree)
}
/// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
/// for the server.
fn signing_keys_for(&self, origin: &ServerName) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
let signingkeys = self
.server_signingkeys
.get(origin.as_bytes())?
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.map_or_else(BTreeMap::new, |keys: ServerSigningKeys| {
let mut tree = keys.verify_keys;
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
tree
});
Ok(signingkeys)
}
fn database_version(&self) -> Result<u64> {
self.global.get(b"version")?.map_or(Ok(0), |version| {
utils::u64_from_bytes(&version).map_err(|_| Error::bad_database("Database version id is invalid."))
})
}
fn bump_database_version(&self, new_version: u64) -> Result<()> {
self.global.insert(b"version", &new_version.to_be_bytes())?;
Ok(())
}
fn backup(&self) -> Result<(), Box<dyn std::error::Error>> { self.db.backup() }
fn backup_list(&self) -> Result<String> { self.db.backup_list() }
fn file_list(&self) -> Result<String> { self.db.file_list() }
} }
+304 -257
View File
@@ -1,317 +1,364 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use ruma::{ use ruma::{
api::client::{ api::client::{
backup::{BackupAlgorithm, KeyBackupData, RoomKeyBackup}, backup::{BackupAlgorithm, KeyBackupData, RoomKeyBackup},
error::ErrorKind, error::ErrorKind,
}, },
serde::Raw, serde::Raw,
OwnedRoomId, RoomId, UserId, OwnedRoomId, RoomId, UserId,
}; };
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::key_backups::Data for KeyValueDatabase { impl service::key_backups::Data for KeyValueDatabase {
fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> { fn create_backup(
let version = services().globals.next_count()?.to_string(); &self,
user_id: &UserId,
backup_metadata: &Raw<BackupAlgorithm>,
) -> Result<String> {
let version = services().globals.next_count()?.to_string();
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.insert( self.backupid_algorithm.insert(
&key, &key,
&serde_json::to_vec(backup_metadata).expect("BackupAlgorithm::to_vec always works"), &serde_json::to_vec(backup_metadata).expect("BackupAlgorithm::to_vec always works"),
)?; )?;
self.backupid_etag self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?; .insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version) Ok(version)
} }
fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> { fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.remove(&key)?; self.backupid_algorithm.remove(&key)?;
self.backupid_etag.remove(&key)?; self.backupid_etag.remove(&key)?;
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
} }
Ok(()) Ok(())
} }
fn update_backup(&self, user_id: &UserId, version: &str, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> { fn update_backup(
let mut key = user_id.as_bytes().to_vec(); &self,
key.push(0xFF); user_id: &UserId,
key.extend_from_slice(version.as_bytes()); version: &str,
backup_metadata: &Raw<BackupAlgorithm>,
) -> Result<String> {
let mut key = user_id.as_bytes().to_vec();
key.push(0xff);
key.extend_from_slice(version.as_bytes());
if self.backupid_algorithm.get(&key)?.is_none() { if self.backupid_algorithm.get(&key)?.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup.")); return Err(Error::BadRequest(
} ErrorKind::NotFound,
"Tried to update nonexistent backup.",
));
}
self.backupid_algorithm self.backupid_algorithm
.insert(&key, backup_metadata.json().get().as_bytes())?; .insert(&key, backup_metadata.json().get().as_bytes())?;
self.backupid_etag self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?; .insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version.to_owned()) Ok(version.to_owned())
} }
fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> { fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let mut last_possible_key = prefix.clone(); let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes()); last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
self.backupid_algorithm self.backupid_algorithm
.iter_from(&last_possible_key, true) .iter_from(&last_possible_key, true)
.take_while(move |(k, _)| k.starts_with(&prefix)) .take_while(move |(k, _)| k.starts_with(&prefix))
.next() .next()
.map(|(key, _)| { .map(|(key, _)| {
utils::string_from_bytes( utils::string_from_bytes(
key.rsplit(|&b| b == 0xFF) key.rsplit(|&b| b == 0xff)
.next() .next()
.expect("rsplit always returns an element"), .expect("rsplit always returns an element"),
) )
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid.")) .map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))
}) })
.transpose() .transpose()
} }
fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, Raw<BackupAlgorithm>)>> { fn get_latest_backup(
let mut prefix = user_id.as_bytes().to_vec(); &self,
prefix.push(0xFF); user_id: &UserId,
let mut last_possible_key = prefix.clone(); ) -> Result<Option<(String, Raw<BackupAlgorithm>)>> {
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes()); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
self.backupid_algorithm self.backupid_algorithm
.iter_from(&last_possible_key, true) .iter_from(&last_possible_key, true)
.take_while(move |(k, _)| k.starts_with(&prefix)) .take_while(move |(k, _)| k.starts_with(&prefix))
.next() .next()
.map(|(key, value)| { .map(|(key, value)| {
let version = utils::string_from_bytes( let version = utils::string_from_bytes(
key.rsplit(|&b| b == 0xFF) key.rsplit(|&b| b == 0xff)
.next() .next()
.expect("rsplit always returns an element"), .expect("rsplit always returns an element"),
) )
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))?; .map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))?;
Ok(( Ok((
version, version,
serde_json::from_slice(&value) serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))?, Error::bad_database("Algorithm in backupid_algorithm is invalid.")
)) })?,
}) ))
.transpose() })
} .transpose()
}
fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> { fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm self.backupid_algorithm
.get(&key)? .get(&key)?
.map_or(Ok(None), |bytes| { .map_or(Ok(None), |bytes| {
serde_json::from_slice(&bytes) serde_json::from_slice(&bytes)
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid.")) .map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))
}) })
} }
fn add_key( fn add_key(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str, key_data: &Raw<KeyBackupData>, &self,
) -> Result<()> { user_id: &UserId,
let mut key = user_id.as_bytes().to_vec(); version: &str,
key.push(0xFF); room_id: &RoomId,
key.extend_from_slice(version.as_bytes()); session_id: &str,
key_data: &Raw<KeyBackupData>,
) -> Result<()> {
let mut key = user_id.as_bytes().to_vec();
key.push(0xff);
key.extend_from_slice(version.as_bytes());
if self.backupid_algorithm.get(&key)?.is_none() { if self.backupid_algorithm.get(&key)?.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup.")); return Err(Error::BadRequest(
} ErrorKind::NotFound,
"Tried to update nonexistent backup.",
));
}
self.backupid_etag self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?; .insert(&key, &services().globals.next_count()?.to_be_bytes())?;
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(session_id.as_bytes()); key.extend_from_slice(session_id.as_bytes());
self.backupkeyid_backup self.backupkeyid_backup
.insert(&key, key_data.json().get().as_bytes())?; .insert(&key, key_data.json().get().as_bytes())?;
Ok(()) Ok(())
} }
fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> { fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes()); prefix.extend_from_slice(version.as_bytes());
Ok(self.backupkeyid_backup.scan_prefix(prefix).count()) Ok(self.backupkeyid_backup.scan_prefix(prefix).count())
} }
fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> { fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
Ok(utils::u64_from_bytes( Ok(utils::u64_from_bytes(
&self &self
.backupid_etag .backupid_etag
.get(&key)? .get(&key)?
.ok_or_else(|| Error::bad_database("Backup has no etag."))?, .ok_or_else(|| Error::bad_database("Backup has no etag."))?,
) )
.map_err(|_| Error::bad_database("etag in backupid_etag invalid."))? .map_err(|_| Error::bad_database("etag in backupid_etag invalid."))?
.to_string()) .to_string())
} }
fn get_all(&self, user_id: &UserId, version: &str) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> { fn get_all(
let mut prefix = user_id.as_bytes().to_vec(); &self,
prefix.push(0xFF); user_id: &UserId,
prefix.extend_from_slice(version.as_bytes()); version: &str,
prefix.push(0xFF); ) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes());
prefix.push(0xff);
let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new(); let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new();
for result in self for result in self
.backupkeyid_backup .backupkeyid_backup
.scan_prefix(prefix) .scan_prefix(prefix)
.map(|(key, value)| { .map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xFF); let mut parts = key.rsplit(|&b| b == 0xff);
let session_id = utils::string_from_bytes( let session_id =
parts utils::string_from_bytes(parts.next().ok_or_else(|| {
.next() Error::bad_database("backupkeyid_backup key is invalid.")
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, })?)
) .map_err(|_| {
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?; Error::bad_database("backupkeyid_backup session_id is invalid.")
})?;
let room_id = RoomId::parse( let room_id = RoomId::parse(
utils::string_from_bytes( utils::string_from_bytes(parts.next().ok_or_else(|| {
parts Error::bad_database("backupkeyid_backup key is invalid.")
.next() })?)
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, .map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?,
) )
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?, .map_err(|_| {
) Error::bad_database("backupkeyid_backup room_id is invalid room id.")
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid room id."))?; })?;
let key_data = serde_json::from_slice(&value) let key_data = serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?; Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
})?;
Ok::<_, Error>((room_id, session_id, key_data)) Ok::<_, Error>((room_id, session_id, key_data))
}) { })
let (room_id, session_id, key_data) = result?; {
rooms let (room_id, session_id, key_data) = result?;
.entry(room_id) rooms
.or_insert_with(|| RoomKeyBackup { .entry(room_id)
sessions: BTreeMap::new(), .or_insert_with(|| RoomKeyBackup {
}) sessions: BTreeMap::new(),
.sessions })
.insert(session_id, key_data); .sessions
} .insert(session_id, key_data);
}
Ok(rooms) Ok(rooms)
} }
fn get_room( fn get_room(
&self, user_id: &UserId, version: &str, room_id: &RoomId, &self,
) -> Result<BTreeMap<String, Raw<KeyBackupData>>> { user_id: &UserId,
let mut prefix = user_id.as_bytes().to_vec(); version: &str,
prefix.push(0xFF); room_id: &RoomId,
prefix.extend_from_slice(version.as_bytes()); ) -> Result<BTreeMap<String, Raw<KeyBackupData>>> {
prefix.push(0xFF); let mut prefix = user_id.as_bytes().to_vec();
prefix.extend_from_slice(room_id.as_bytes()); prefix.push(0xff);
prefix.push(0xFF); prefix.extend_from_slice(version.as_bytes());
prefix.push(0xff);
prefix.extend_from_slice(room_id.as_bytes());
prefix.push(0xff);
Ok(self Ok(self
.backupkeyid_backup .backupkeyid_backup
.scan_prefix(prefix) .scan_prefix(prefix)
.map(|(key, value)| { .map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xFF); let mut parts = key.rsplit(|&b| b == 0xff);
let session_id = utils::string_from_bytes( let session_id =
parts utils::string_from_bytes(parts.next().ok_or_else(|| {
.next() Error::bad_database("backupkeyid_backup key is invalid.")
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, })?)
) .map_err(|_| {
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?; Error::bad_database("backupkeyid_backup session_id is invalid.")
})?;
let key_data = serde_json::from_slice(&value) let key_data = serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?; Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
})?;
Ok::<_, Error>((session_id, key_data)) Ok::<_, Error>((session_id, key_data))
}) })
.filter_map(Result::ok) .filter_map(|r| r.ok())
.collect()) .collect())
} }
fn get_session( fn get_session(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str, &self,
) -> Result<Option<Raw<KeyBackupData>>> { user_id: &UserId,
let mut key = user_id.as_bytes().to_vec(); version: &str,
key.push(0xFF); room_id: &RoomId,
key.extend_from_slice(version.as_bytes()); session_id: &str,
key.push(0xFF); ) -> Result<Option<Raw<KeyBackupData>>> {
key.extend_from_slice(room_id.as_bytes()); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(session_id.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xff);
key.extend_from_slice(room_id.as_bytes());
key.push(0xff);
key.extend_from_slice(session_id.as_bytes());
self.backupkeyid_backup self.backupkeyid_backup
.get(&key)? .get(&key)?
.map(|value| { .map(|value| {
serde_json::from_slice(&value) serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")) Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
}) })
.transpose() })
} .transpose()
}
fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> { fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
} }
Ok(()) Ok(())
} }
fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> { fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
} }
Ok(()) Ok(())
} }
fn delete_room_key(&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str) -> Result<()> { fn delete_room_key(
let mut key = user_id.as_bytes().to_vec(); &self,
key.push(0xFF); user_id: &UserId,
key.extend_from_slice(version.as_bytes()); version: &str,
key.push(0xFF); room_id: &RoomId,
key.extend_from_slice(room_id.as_bytes()); session_id: &str,
key.push(0xFF); ) -> Result<()> {
key.extend_from_slice(session_id.as_bytes()); let mut key = user_id.as_bytes().to_vec();
key.push(0xff);
key.extend_from_slice(version.as_bytes());
key.push(0xff);
key.extend_from_slice(room_id.as_bytes());
key.push(0xff);
key.extend_from_slice(session_id.as_bytes());
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
} }
Ok(()) Ok(())
} }
} }

Some files were not shown because too many files have changed in this diff Show More